text stringlengths 38 1.54M |
|---|
# cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
# For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
# Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
# Implement car and cdr.
... |
import os
import time
from . import ElectrumTestCase
from electrum.simple_config import SimpleConfig
from electrum.wallet import restore_wallet_from_text, Standard_Wallet, Abstract_Wallet
from electrum.invoices import PR_UNPAID, PR_PAID, PR_UNCONFIRMED, BaseInvoice, Invoice, LN_EXPIRY_NEVER
from electrum.address_sync... |
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import requests
import os.path
import errno
try:
os.mkdir(os.path.join('E:\\',"years"))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
for q in range(2000,2021):
req = Request('https://naasongs... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
class Mapper:
def run(self):
data = self.readInput()
for cur_id, follow in data:
print('%d\t%d' % (int(cur_id), int(follow)))
def readInput(self):
for line in sys.stdin:
yield line.encode("utf8").stri... |
'''
Created on 18 Oct 2011
@author: Steven
'''
from lib import feedparser
f= open("G:\\top.xml","r")
feed = feedparser.parse("http://www.mitbbs.com/rss/top.xml")
s= feed.channel["title"]
f.close()
|
# -*- coding: utf-8 -*-
import pandas as pd
import cv2
import os
import numpy as np
class Graph(object):
def __init__(self, graph):
self.graph = graph
def sub_graphs_connected(self):
"""
根据图对生成文本行
:return: list of list; 文本行列表,每个文本行是文本框索引号列表
"""
sub_graphs = []
... |
import sys
import numpy
import random
import matplotlib.pyplot as plt
from pylab import *
covariancematrix=numpy.eye(4,4)
umean=numpy.ones(4).T
class priorWeight(object):
"""docstring for priorWeight"""
u=umean
cov=covariancematrix
step=0
length=0
def __init__(self, step):
super(priorWeight, self).__init__()... |
import numpy as np
import re
import os
import argparse
from sklearn.manifold import TSNE
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import glob
from tqdm import tqdm
import time
import pdb
import random
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedC... |
import json
import sys
import time
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from django.core.management import call_command
from django.utils.html import strip_tags
from cms.categories.models import Category, CategorySubSite
from cms.pages.models import BasePage
from cms.posts.models import (Pos... |
"""
https://www.hackerrank.com/challenges/30-linked-list-deletion/problem
Output Format
Your removeDuplicates function should return the head of the updated linked list.
The locked stub code in your editor will print the returned list to stdout.
Sample Input
6
1
2
2
3
3
4
Sample Output
1 2 3 4
The data elements ... |
N, M = map(int, input().split())
g = [ [False] * N for _ in range(N) ]
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a][b] = True
g[b][a] = True
vis = [False] * N
ans = 0
def f(v, d):
global vis, ans
if d == N:
ans += 1
return
for nxt in range(N):
if g[v][nxt] and not... |
import turtle # turtle
import time
turtscreen = turtle.Screen() # window
def circledrawer(L, H): # L = lower, H = higher
for i in range(L, H): # function to move to
met.forward(50) # position and draw circle
met.right (90) # then move
... |
import collections
def correct_one(p):
stack = []
for i in range(len(p)):
if p[i] == '(':
stack.append('(')
else:
if not stack:
return False
stack.pop()
return len(stack) == 0
def balanced_one(p):
counter = collections.Counter(p)
... |
"""
Dependency Provider for Array Operations
Low level code for array operations
"""
from nameko.extensions import DependencyProvider
class ArrayOps:
"""
The ArrayOps class forms the base of the dependency
provider for array operations.
"""
@staticmethod
def square_odds(int_arr):
"""
... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
#Defines the pines
frontRight = 2
backRight = 3
frontLeft = 17 #Pin four not working for some reson
backLeft = 5
buzzer = 6
trigger = 7
echo = 8
for i in range(2, 12):
GPIO.setup(i,GPIO.OUT) ... |
from flex.logger.logger_parser import LoggerParser
from flex.core import core
def launch():
logger_parser = LoggerParser()
logger_generator = logger_parser.parse(core.config)
core.register_object('logger', logger_generator)
|
import os
from glob import glob
import cv2
import numpy as np
import pickle
from tqdm import tqdm
from utils import *
import Features
path = '/nfs/nas-5.1/wbcheng/cc_hw2/HW2-database-20f/'
Categories, ImagePaths = [], []
for f in glob(os.path.join(path, 'database', '*')):
ImagePaths.append(glob(os.path.join(f, '*... |
# Michael P. Hayes UCECE, Copyright 2018--2019
import numpy as np
from ipywidgets import interact, interactive, fixed
from matplotlib.pyplot import figure
from .lib.signal_plot import signal_plot2
from .lib.utils import gauss
def kf_demo1_plot(steps=0, v=1, A=1, B=1, C=1, sigmaX0=1, sigmaV=1, sigmaW=1):
dt = 1
... |
from transforms.Transform import Transform
from transforms.CameraCalibration import CameraCalibration
from transforms.Thresholding import Thresholding
import matplotlib.pyplot as plt
import cv2
import numpy as np
import glob
import logging
class PerspectiveTransform(Transform):
X = 1280
Y = 720
#Points in ... |
'''
main.py
Created by JO HYUK JUN on 2021
Copyright © 2021 JO HYUK JUN. All rights reserved.
'''
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
seeker = {}
for s in stones:
if s in seeker:
seeker[s] += 1
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-23 18:22
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class... |
import unittest
import numpy as np
from ..casino import Casino
from ..hmm_multinoulli import HMMMultinoulli
class TestHMMMultinoulli(unittest.TestCase):
def setUp(self):
np.random.seed(2019)
def test_condition(self):
hmm = HMMMultinoulli(Casino.A, Casino.PX, Casino.INIT)
seq = [2, 4... |
import argparse
import os
import sys
from traceback import print_exc
import toml
from colors import cyan
from ..version import __version__
from .subparsers import build
from .subparsers import clean
from .subparsers import help as help_
from .subparsers import install
from .subparsers import lint
from .subparsers imp... |
#coding=utf-8
import time,datetime
TIME_ZONE=" +0800"
################ str="xx:xx"
'''
start="20180222044300 +0000" stop="20180222071500 +0000"
'''
##获取日期字符串20180222044300
def timeTostrOfsec(hs,d,flag=0):
tmp=d+datetime.timedelta(days=flag)
return timetofomat(tmp)+hs.replace(":","")+"00"
##获取结束时间
def stop... |
from random import randint
import matplotlib.pyplot as plt
import numpy as np
n = 1000
nodes = [0] * n
infectionDone = False
currentInfected = 1
infectedPerLoop = 0
infectionRate = []
curInf = []
attempts = []
x=1
nodes[randint(0,n-1)] = 1
while not infectionDone:
for i in range(n):
if nodes[i] == 1:
... |
# Generated by Django 2.0.13 on 2019-04-28 22:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crudpoints', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='funcionario',
name='genero',
... |
# Copyright 2020 Xilinx Inc.
#
# 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 applicable law or agreed to in writing, ... |
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 50, 50
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'... |
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, DeleteView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib import messages
from django.shortcuts import render
from django.forms import inlineformset_factory, modelformset_factory, T... |
#!/usr/bin/env python3
import re
class NoMatch(Exception):
pass
class Grammar:
def __add__(self, other):
if isinstance(self, ALL):
self.things += [other]
return self
return ALL(self, other)
def __or__(self, other):
if isinstance(self, OR):
self.things += [other]
return sel... |
from __main__ import app
from flask import url_for, render_template, session
from models import User, ArticleSeries, Article
from sqlalchemy import desc
@app.route('/series/<int:series_id>/<string:slug>', methods=['GET'])
def page_series_articles(series_id, slug):
session['next'] = url_for('page_series_articles', ser... |
# first import things as you would usually
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.activations import relu, softmax
# import talos
import talos
# load rthe iris dataset
x, y = t... |
import numpy as np
from scipy.optimize import minimize
'''
Things that need to be done here:
- Make naming conventions for r and R consistent. Complex reflection coefficient?
Reflectivity? Complex reflectivity? Which one is power vs field?
**** reflectance and reflection coefficient mean the same thing. T... |
SECTION = 0
COUNT_IN_SECTION = 0
NUMBER_OF_PRODUCT = 0
USER_ID = 0
USER_NAME = ''
NUMBER_OF_PRODUCT_BASKET = 0
COUNT_IN_BASKET = 0
|
#@+leo-ver=5-thin
#@+node:ekr.20090717092906.12765: * @file leoVersion.py
"""
A module holding the following version-related info:
leoVersion.static_date: The date of official releases.
Also used when the git repo is not available.
leoVersion.version: Leo's version number.
"""
#@+<< version... |
from .apartment import Apartment
from .shadow import Shadow
from .exceptions.incorrect_desc_exception import MissingKeyException, IncorrectValueException
from .exceptions.not_in_exception import NotInBuildingException
class Building:
B_NAME_KEY = "name"
B_APARTMENTS_COUNT_KEY = "apartments_count"
B_DISTANCE_KEY = ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-05-01 15:57
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('dresscodeapp', '0007_auto_20170501_183... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import json
from abc import ABC
from typing import Any, Iterable, List, Mapping, Optional, Tuple
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources import AbstractSource
from airbyte_cdk.sources.streams import Stream
from airby... |
import csv
import numpy as np
from numpy import nan
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
# Initialize the Linear Regression
reg = LinearRegression()
# lable = pd.DataFrame(sf['maxPrice'])
... |
# Print the reverse string of the original string
def reverseSTR(str1):
if type(str1) != str:
raise TypeError(f"{str1} type should be string not {type(str1)}")
str_len = len(str1) - 1
while str_len >= 0:
print(str1[str_len], end="")
str_len -= 1
print()
st... |
import numpy as np
import cv2
vid_name = "20200810_163938.mp4"
cap = cv2.VideoCapture(f"fall_vids/{vid_name}")
count = 1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray, (... |
#####
# Python By Example
# Exercise 130
# Christopher Hagan
#####
from tkinter import *
import csv
fileName = 'listOfNumbers.csv'
def addValue():
valueEntered = userValue.get()
if (valueEntered.isdigit()):
listOfNumbers.insert(END, valueEntered)
messageValue['fg'] = 'green'
messageVa... |
import os
import sys
from Bio import Entrez
def download_by_gi(result_dir, gi):
Entrez.email = "3066268521@qq.com"
filename = "gi_"+gi+".fasta"
if not os.path.isfile(filename):
print("Downloading...")
net_handle = Entrez.efetch(db="nucleotide", id=gi, rettype="fasta", retmode="text")
... |
# 回溯法
from typing import List
class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def check(x, y, s):
# 检查对应的行列里有没有S
for i in range(9):
... |
#! /usr/bin/python
import serial
from time import sleep
ending = chr(13) + chr(10);
bluetoothSerial = serial.Serial("/dev/rfcomm1", baudrate=9600)
command = "SN"; #send data
count = 1;
#while True:
print "C " + str(count) + ":"
bluetoothSerial.write(str(command) + ending)
response = bluetoothSerial.readline()
prin... |
class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
# 时间复杂度O(N),空间复杂度O(1)
# 状态转移方程dp[i] = dp[i-1] + 1
if len(p) == 0:
return 0
dp = [0] * 26
dp[ord(p[0]) - ord('a')] = 1
last = 1
for i in range(1, len(p)):
if dp[ord... |
class Node:
def __init__(self, name, key):
self.name = name
self.key = key
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# O(1)
# Cada item com nome e key é adicionado no início da lista em cada posição
def append(self, word, key):
... |
from gluon.custom_import import NATIVE_IMPORTER
import sys
# Fix capitalization imcompatibility between Keras and web2py
Keras = NATIVE_IMPORTER('keras')
sys.modules['keras'] = Keras
|
"""
Groundwork recipe pattern.
Provides function to register, get and build recipes.
Recipes are used create directories and files based on a given template and some user input.
It is mostly used to speed up the set up of new python packages, groundwork applications or projects.
Based on cookiecutter: https://github... |
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from django_mptt_admin.admin import DjangoMpttAdmin
# from mptt_tree_editor.admin import TreeEditor Bug pour Python 3.5
from .models import Sejour, Work, TissueCategory, Tissue, WorkCategory
admin.site.register(Sejour)
admin.site.register(Work)
ad... |
from django.urls import path
from . import views
urlpatterns = [
path('login/register/', views.register, name='register'),
path('login/register/login', views.login, name='login'),
path('enquiry/', views.enquiry, name='enquiry'),
path('login/', views.login, name='login'),
path('', views.home... |
import unittest
import acs.ai as ai
import acs.farm as farm
class TestCropChance(unittest.TestCase):
def setUp(self):
self.crop_1 = farm.Crop(1, 'Crop 1', 'Crop 1', 10, 20, 1.1, 0.9, 2, 0.5)
self.crop_2 = farm.Crop(2, 'Crop 2', 'Crop 2', 5, 15, 1.2, 0.8, 0.5, 2)
self.crop_chance_1 = ai.C... |
#3. Write a Python program of recursion list sum.
Test_Data = [4, 2, [3,1,[9,12,[14,5]]], [7,1]]
def fact_sum(a_list):
x = 0
for i in a_list:
if isinstance(i, list):
print "i is a list:", i
x = x + fact_sum(i)
#print "*",fact_sum(i)
else:
print "... |
# Načítajte z klávesnice reťazec znakov ukončený znakom "nového riadku". Slová vo vstupe sú oddelené najmenej jedným znakom "medzera". Uvažujte aj prvé, resp. posledné slovo vstupu. Určte počet slov obsahujúcich len písmená malej abecedy. Počet (0-255) vytlačte osmičkovo.
# Toto je moja veta. Spravnym vystupom na zakl... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class WebPageItem(scrapy.Item):
url = scrapy.Field()
title = scrapy.Field()
buy_button = scrapy.Field()
last_updated = scrapy.Field()
... |
##this is the class that creates the hangman game
class hangman:
def __init__(self, word):
##this is where we initialize the instance variables
self.word = word
self.chances = len(word) + 4
## this returns the chances left
def __str__(self):
return f'You have {self.chance... |
###########PARSER SYMBOLS
class CONSTANTS:
OPERATORS = '!+|^'
OPERATOR_NOT = '!'
OPERATOR_AND = '+'
OPERATOR_OR = '|'
OPERATOR_XOR = '^'
OPERATOR_SYMBOL = '@'
IMPLIES = '=>'
DUBLEX_IMPLIES = '<=>'
FORBIDDEN_OVERWRITING = 'Current mode forbid overwriting for existing rules' |
# 类
class Restaurant():
"""指出餐厅名字和菜品"""
def __init__(self,restaurant_name,cuisine_type): # 特殊的方法(函数),三个形参,self相当于实例自己
# 属性
self.restaurant_name = restaurant_name # 餐厅名字
self.cuisine_type = cuisine_type # 菜品
# 方法
def describe_restaurant(self): # 需要有形参self,让实例能够访问方法
... |
#!/usr/bin/python
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id, title, width=8, height=8):
size = 35
self.width = width
self.height = height
wx.Frame.__init__(self, parent, id, title, (-1, -1),
wx.Size(size*width + 5, size*height + 5))
panel = wx.Panel... |
import scipy.stats as stats
import numpy as np
def tau_distance(r1, r2):
"""
Tau distance
Values close to 1 indicate strong agreement,
and values close to -1 indicate strong disagreement.
:param r1: list1
:param r2: list2
:return: tau distance between two lists
"""
tau... |
'''
Created on Mar 7, 2016
@author: mike
'''
from patgen import EMPTYSET, DIGITS
from patgen.suffix_array import SuffixArray
class PatternSet(list):
def __init__(self):
list.__init__(self)
@property
def maxchunk(self):
if len(self) == 0:
return 0
return max(... |
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
appear = set()
while True:
appear.add(n)
new = 0
while n:
new += (n%10)**2
n /= 10
n = new
if n ... |
import pygame
import random
import os
import logging
pygame.init()
clock = pygame.time.Clock()
##### DISPLAY #####
from shared.display import gameDisplay, DISPLAY_WIDTH, DISPLAY_HEIGHT, fullScreenImage
pygame.display.set_caption("Game Zulu")
# TODO: Get game icon. Maybe a small spaceship.
###### IMAGES #####
stars ... |
'''
Created on Nov 18, 2012
@author: mrfish
'''
import SimpleDiscreteRobotEnvironment.ProbTransitionMatrix as ProbTransitionMatrix
UNINITALLIZED = -1
class ExtendedDiscreteTransitionMatrix:
'''
A matrix which stores the actions that lead from one state to another
'''
def __init__(self, noOfSta... |
import os
from typing import cast
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError
from constants import DEFAULT_DATABASE_URL
DATABASE_URL = os.environ.get('DATABASE_URL') or DEFAULT_DATABASE_URL
db = SQLAlchemy()
def setup_db(app, database_url=DATABASE_URL):
app.config['SQLA... |
import os
import chainer
from chainer import functions as F
import gym
import gym.wrappers
import numpy as np
import chainerrl
from models.clipped_gaussian.clipped_model import ClippedModel
from models.clipped_gaussian.train_trpo_gym import ClippedGaussianPolicy
class ObsNormalizedModel(chainerrl.agents.a3c.A3CSep... |
import unittest
from Project_2.problem_1.KeyValue import KeyValue
class KeyValueTest(unittest.TestCase):
def test_creation_key_value(self):
key_value = KeyValue(1, 1)
self.assertEqual(key_value.key, 1)
self.assertEqual(key_value.value, 1)
def test_creation_key_with_value_none(self):
... |
# Copyright (c) 2019-2023, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner.
#
# Distributed under the 3-clause BSD license, see accompanying file LICENSE
# or https://github.com/scikit-hep/vector for details.
"""
.. code-block:: python
Spatial.is_parallel(self, other, tolerance=...)
"""
from __... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: xibin.yue
date: 2016/12/21
descrption:
"""
import pandas as pd
import os
import datetime
class DataGenerator(object):
def __init__(self):
self.data_path = 'data'
self.time_format = '%Y-%m-%d'
self.Y = pd.DataFrame()
s... |
import collections
import functools
import re
import socket
import string
import inspect
from threading import Timer, RLock
import time
def lchop(string, prefix):
"""Removes a prefix from string
:param string: String, possibly prefixed with prefix
:param prefix: Prefix to remove from string
:returns... |
import cs50
cc = cs50.get_string("Number: ")
# Check cards validity
# Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ !!digits!! together.
product = 0
# Sum the digits that weren’t multiplied by 2.
total_sum = 0
ticker = 0
for i in reversed(cc):
if ... |
import numpy as np
from dpp_functions import *
items = np.random.normal(size=(100, 25))
print sample_from_dpp(items)
|
#!/usr/bin/env python
import RPi.GPIO as IO
import time
import os, sys
import rospy
from std_msgs.msg import String
#import msvcrt
import getch
#initializer IO
IO.setwarnings(False)
LM1 = 7 #pin26 raspi3
LM2 = 1 #pin28 raspi3
LM_en = 12 #32 raspi3
RM1 = 5 #pin29 raspi3
RM2 = 6 #pin31 raspi3
RM_en = 25 #pin33 raspi3... |
import html2text, os
def convert():
celexs = os.listdir("data_scraping/data_html")
converted = os.listdir("data/converted")
text_maker = html2text.HTML2Text()
text_maker.ignore_images = True
text_maker.ignore_links = True
i = 0
for celex in celexs:
i += 1
if int(cel... |
import numpy as np
def get_params(x_matrix, t_vec) -> [float]:
return np.linalg.pinv(x_matrix.T @ x_matrix) @ x_matrix.T @ t_vec
def get_params_with_penalty(x_matrix, t_vec, lambda_penalty):
return (
np.linalg.pinv(
x_matrix.T @ x_matrix + lambda_penalty * np.identity(x_matrix.shape[1])
... |
# Generated by Django 3.0.5 on 2020-04-30 18:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zeno', '0002_auto_20200430_1851'),
]
operations = [
migrations.AddField(
model_name='zenoitem',
name='zenoid',
... |
import random
import numpy as np
import torch
from main import logger
def set_seeds(seed, n_gpu):
""""set random seeds"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(seed)
def get_device():
"""目前暂未支持分布式训练, 目前只做... |
import cv2
import numpy as np
def imageRead(openpath, flag=cv2.IMREAD_UNCHANGED):
image = cv2.imread(openpath, flag)
if image is not None:
print("Image Opened")
return image
else:
print("Image Not Opened")
print("Program Abort")
exit()
def imageShow... |
import eHive
import os
import tempfile
from VcfQC import VcfQC
class PlotVariantDensity(eHive.BaseRunnable):
"""Plot Variant density using a VCF file"""
def param_defaults(self):
return {
}
def run(self):
filepath=self.param_required('filepath')
self.warning('Analysi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-22 02:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
# -*- coding: utf-8 -*-
import urllib
from bs4 import BeautifulSoup
from urllib.request import urlopen
import os
import sys
from colorama import init
init(strip=not sys.stdout.isatty())
from termcolor import cprint
from pyfiglet import figlet_format
from prettytable import PrettyTable
source = "https://m.biqudu.com"
... |
if __name__ == '__main__':
import os, sys
import tests.testapp as TA
app = TA.testapp()
os.chdir(sys.path[0])
import protocols
def _main():
import wx
import hooks
import services.service_provider as SP
sps = [p.provider_id for p in wx.GetApp().plugins if p.info.type == 'service_pro... |
import math as math
import Geo_Utils.detector as geo
import ROOT
# Define these locally for ease
xlo = geo.GetX_Bounds()[0]
xhi = geo.GetX_Bounds()[1]
ylo = geo.GetY_Bounds()[0]
yhi = geo.GetY_Bounds()[1]
zlo = geo.GetZ_Bounds()[0]
zhi = geo.GetZ_Bounds()[1]
def mc_neutron_induced_contained(f):
tf = ROOT.TFile("{... |
# -*- coding: utf-8 -*-
import random
import sqlite3
# РАБОТА С ПОЛЬЗОВАТЕЛЯМИ
#Создание таблицы
conn = sqlite3.connect('fitness.sqlite')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS users (user_id int primary key, surname varchar, name varchar, gruppa varchar, status varchar)")
conn.commit() #отправка дан... |
import numpy as np
import readgadget,readfof
#########################################################################
# read header
header = readgadget.header(snapshot)
BoxSize = header.boxsize/1e3 #Mpc/h
Nall = header.nall #Total number of particles
Masses = header.massarr*1e10 #Masses of the parti... |
# Peter Finnerty - Project 2020
# Write a program called analysis.py that:
# • outputs a summary of each variable to a single text file,
# • saves a histogram of each variable to png files, and
# • outputs a scatter plot of each pair of variables.
#-----------------------------------------------------------
import ma... |
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
model = ResNet50(weights='imagenet')
Predicted = []
for i in range(2):
img_path = "/Users/yh/PycharmProjects/keras_examples/IMG/%d.... |
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework import status
from rest_framework_jwt.settings import api_settings
from .utils import OAuthQQ
from .exceptions import QQAPIException
from .models import OAuthQQUs... |
# encoding: utf-8
import os, sys, re
class ParserException(Exception):
pass
class Parser(object):
WHITESPACE = ''
#WHITESPACE = " \t\n\r\f"
# we divide the uri-safe glyphs into three sets
# <rison> and <reserved> classes are illegal in ids.
# <rison> - used by rison (possibly later)
# ... |
""" Text rendered using a diy points class and special shader uv_fontmultcoloured.
vertices[0] x position of centre of point relative to centre of screen in pixels
vertices[1] y position
vertices[2] z depth but fract(z) is used as a multiplier for point size
normals[0] rotation in radians
normals[1]... |
import threading
import urwid
import xmlrpclib
import copy
import time
import Queue
from M2Crypto import m2xmlrpclib, SSL
from decimal import Decimal
try:
import simplejson as json
except ImportError, e:
import json
class RIRCWorkerThread(threading.Thread):
IDLE = -1
INIT = 0
SEND = 1
NETWORKS ... |
#!/usr/bin/env python
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
|
import RPi.GPIO as GPIO #Import GPIO library
import time #Import time library
GPIO.setmode(GPIO.BCM)
from dronekit import connect, VehicleMode, LocationGlobalRelative, Command, LocationGlobal
from pymavlink import mavutil
TRIG = 23 ... |
# Generated by Django 3.0.4 on 2020-04-05 12:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20200405_1550'),
]
operations = [
migrations.DeleteModel(
name='User',
),
]
|
import pandas as pd
from sqlalchemy import create_engine
import os
import sys
from auto_ml import Predictor
from auto_ml.utils import get_boston_dataset
from sklearn.model_selection import train_test_split
try:
df = pd.read_csv('cache_of_model_intput.tmp')
except:
with open('regression_query.sql', 'r') as f... |
import xml.etree.ElementTree as xml
import copy
def indent(elem, level=0):
'''for prettyprinting XML
'''
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
#try:
# elem.text += i + " "
#except TypeError:
elem.t... |
import pygame
from Network import Network
width = 800
height = 800
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")
def draw_window(win, players):
win.fill((255,255,255))
for key, player in players.items():
player.draw(win)
pygame.display.update()
def main():
... |
import os
try:
from .settings import *
except ImportError:
pass
DEBUG = False
# Celery Settings
CELERY_BROKER_URL = 'redis://redis-dev.4nnstd.0001.euw2.cache.amazonaws.com:6379/0'
ALLOWED_HOSTS = [
'127.0.0.1',
'www.textivist.net',
'ec2-52-56-202-26.eu-west-2.compute.amazonaws.com'
]
DATABASES ... |
# Core
import datetime
import os
import glob
# Analysis
import xarray as xr
import numpy as np
import pyproj as pp
import scipy as sp
import transect_analysis as ta
ASCAT = xr.open_mfdataset('/g/data/w40/esh563/ASCAT_12.nc')
ASCAT.time.attrs['time_zone'] = 'local solar time'
ASCAT = ASCAT.sel(latitude = slice(-12... |
import yaml
import requests
import sys
import settings
import json
import logging as log
import csv
from uuid import uuid4
from confluent_kafka import Producer
"""
Execute a crawl plan produced by crawl_plan.py.
"""
def cluster_healthcheck():
"""
:return: True if Scrapy Cluster is fully operational, else Fal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.