text stringlengths 8 6.05M |
|---|
#!/usr/bin/python3
"""Experimental script comparing performance of pairing heap and smooth heap
as priority queue in Dijkstra's algorithm. Algorithm is run on randomly generated
10-regular graphs of variable size.
Results are stored as .csv files in ../data folder and plots of results in ../plots"""
import networkx as... |
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from direct.directnotify import DirectNotifyGlobal
class PiratesTutorialManagerAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('PiratesTutorialManagerAI')
def __init__(self, air):
DistributedObjectAI._... |
# -*- coding: utf-8 -*-
__author__ = 'lish'
from insertBSheet import insertbooksheet as insertbs
import urllib2,bs4,re
import urllib2
import urllib,random
import re,json,os
import sys,time
import ConfigParser
import requests,MySQLdb
import GenerateSheetCover as gsc
import sys
reload(sys)
sys.setdefaultencoding('utf8')
... |
import tensorflow as tf
import cv2
import skvideo.io
import skimage.transform
import numpy as np
import datetime
from cv2 import VideoWriter, VideoWriter_fourcc
import os
import glob
import shutil
"""
Author: CS6670 Group
Code structure inspired from carpedm20/DCGAN-tensorflow, GV1028/videogan
"""
def clear_genvideos... |
USERS = (
{'username': 'Timmy', 'password': 'password'},
{'username': 'Johny', 'password': 'Hf7FAbf6'},
{'username': 'Alice', 'password': 'alice'},
{'username': 'Roger', 'password': 'pass'},
{'username': 'Simon', 'password': 'says'},
{'username': 'Admin', 'password': 'ads78adsg7dasga'}
)
class... |
import math
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
import PIL.Image
import torch
from torch.utils._pytree import tree_flatten, tree_unflatten, TreeSpec
from torchvision import transforms as _transforms, tv_tensors
from torchvision.transforms import _functional_tensor as _FT
from to... |
import serial
import serial.tools.list_ports
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(initialdir="D:\\Documents\\GitHub\\dpf-line-cutter\\code\\launch archive\\2021-10... |
# -*-coding: utf8 -*-
"""
dynamic_group comes from http://djangosnippets.org/snippets/2511/
"""
from importlib import import_module
from itertools import groupby, chain
from datetime import datetime
import time
import re
from pytimeago.english import english as english_ago
from pytimeago.english_short import english... |
import os
import json
import codecs
from optparse import OptionParser
import pandas as pd
from ..util import file_handling as fh, defines
import data_splitting as ds
def make_label_metaindex():
input_filename = os.path.join('.', 'codes.json')
with codecs.open(input_filename, 'r') as input_file:
code... |
# -*- coding: utf-8 -*-
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
class HttpClientListener(object):
ROBOT_LISTENER_API_VERSION = 3
def __init__(self, requests_lib):
self._requests_lib = requests_lib
def end_test(self, data, result):
self._requests_lib.dele... |
# created by Ryan Spies
# rspies@lynkertech.com
# 2/23/2016
# Python 2.7
# Description: create a new ColdStateFiles directory by copying the old directory contents
# and replacing the params_previous.xml with a new file using the moduleparfile
# Also copy the original statesI.txt to the new directory
# The scr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Download files for udemy-dl."""
from __future__ import unicode_literals
from __future__ import print_function
import os
import subprocess
import sys
import colorlog
import requests
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import... |
import numpy as np
import cv2
from FaceRecognizer import _find_vectors_distance
def hist(img, histSize, channels, mask, ranges):
return cv2.calcHist([img], histSize=histSize, channels=channels, mask=mask, ranges=ranges)
def sliding_window(img, window_size):
vectors = []
img_shape = img.shape
for ro... |
import os
import sys
import hydra
import time
import datetime
import subprocess
import regex as re
import logging
logger = logging.getLogger(__name__)
def check_instance_preemptible(instance_name):
output = subprocess.run(
f"gcloud compute instances describe {instance_name}", shell=True, check=True, stdou... |
from pymongo import MongoClient
c = MongoClient(host='localhost', port=27017, replicaset="foo")
db = c.my_db
print "connectiong to db"
def resetReplicaSet():
cl = MongoClient(host='localhost', port=27017)
config = cl.admin.command("replSetGetConfig")['config']
statusMembers = cl.admin.command("replSetGetS... |
# coding=UTF-8
class Ponto(object):
def __init__(self, x, y):
self.__x = x
self.__y = y
def get_x(self):
return self.__x
def get_y(self):
return self.__y
def set_x(self, x):
if x > 0:
self.__x = x
def set_y(self, y):
if y > 0:
... |
class Color:
colors = {
"blue": "blue",
"red": "red",
"black": "black",
"green": "green",
"orange": "orange",
"silver": "silver"
}
def get_color(self):
return self.colors
|
#!/bin/python3
import sys
n = int(3)
a = list(map(int, [3, 2, 1]))
# Write Your Code Here
numberOfSwaps = 0
for i in range(n):
for j in range(i, n - 1):
if a[i] > a[j + 1]:
numberOfSwaps += 1
a[i], a[j + 1] = a[j + 1], a[i]
print('Array is sorted in {} swaps.'.format(numberOfSwa... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 19 14:20:28 2019
The actual work of creating the wavelet and conducting the 2d convolution
@author: matthewmorriss
"""
def conv2_mexh(patch,a,dx):
import numpy as np
from scipy import signal
#Generated the Mexican hat wavelet kerne at wavelet scale a. The ke... |
from django.conf.urls.defaults import *
urlpatterns = patterns('mulan.views',
(r'^contacts', 'Contacts'),
(r'^menu(?:/(-?\d+))?', 'Menu'),
(r'^business(\+)?', 'BusinessLunch'),
(r'^vacancies', 'Vacancies'),
(r'^delivery_success', 'DeliverySuccess'),
(r'^delivery', 'Delivery'),
(r'^upload', ... |
from datetime import date
class AwakenHistory:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
# YELLOW = '\033[93m'
YELLOW = ''
RED = '\033[91m'
# BOLD = '\033[1m'
BOLD = ''
UNDERLINE = '\033[4m'
# END = '\033[0m'
E... |
import base64
import logging
import os
import httpx
from fastapi import FastAPI, UploadFile, File, HTTPException
from prometheus_client import Counter, REGISTRY
from pydantic import BaseModel
from prometheus_fastapi_instrumentator import Instrumentator
app = FastAPI(
docs_url="/doc",
)
logger = logging.getLogger(... |
#!/usr/bin/python3
# ^^ note the python directive on the first line
# COMP 9414 agent initiation file
# requires the host is running before the agent
# designed for python 3.6
# typical initiation would be (file in working directory, port = 31415)
# python3 agent.py -p 31415
# created by Leo Hoare
# with slight... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
my_dict={'insert_me': 'INSERTED FROM VIEW','second_key':'AGAIN FROM VIEW'}
return render(request,'first_app/Index.html',my_dict)
def home(request):
return HttpResponse("<h1>WELCOME TO TH... |
from Language import LanguageInstance
__author__ = 'Ritwik'
PYTHON_EXTENSION = "py"
PYTHON_EXEC_COM = "python"
class PythonInstance(LanguageInstance):
def __init__(self, working_directory):
LanguageInstance.__init__(self, working_directory, PYTHON_EXTENSION, "", PYTHON_EXEC_COM)
def run_s... |
# Requires api from setup.py and avg polarity from sentiment.py #
# Updates status #
import setup, sentiment as snt
setup.api.update_status("Test tweet for a demo")
|
import unittest
from katas.kyu_8.beginner_lost_without_a_map import maps
class MapsTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(maps([1, 2, 3]), [2, 4, 6])
def test_equal_2(self):
self.assertEqual(maps([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
[0, 2, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 31 15:13:57 2017
@author: mulugetasemework
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 28 17:34:06 2017
@author: mulugetasemework
This code does geometric transfomations to "corrupt" data and increase
the size of ... |
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
# initial area, left and right pointers
area, left, right = 0, 0, len(height) - 1
while left < right:
new_area = (right - left) * min(height[left], heig... |
import setuptools
setuptools.setup(
name="dmoj-tool-dessertion",
version="0.1.7",
author="Desertion",
author_email="73731354pi@gmail.com",
description="CLI submission to DMOJ",
# scripts=['bin/dmoj-tool'],
packages=['dmoj_tool'],
package_dir={'dmoj-tool':'dmoj_tool'},
entry_points={... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0002_auto_20150616_2121'),
migrations.swappable_dependency(settings... |
import time
class Timer:
def __init__(self):
self.elapsed_time = 0
self.start_time = 0
pass
def start(self):
if self.start_time > 0:
pass
self.start_time = time.time()
def end(self):
if self.elapsed_time > 0:
pass
self.elap... |
import numpy as np
import matplotlib.pyplot as plt
import time
# Load the data:
X_train = np.load('data/q2xTrain.npy')
y_train = np.load('data/q2yTrain.npy')
X_test = np.load('data/q2xTest.npy')
y_test = np.load('data/q2yTest.npy')
def construct_polynomial(X_vec, degree):
X = np.ones((X_vec.shape[0], 1))
for... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
spec = load_test_spec("vpp", "scale")
@slash.requires(have_ffmpeg)
@slash.requires(have_ffmpeg_qsv_accel)
@slash.requires(*have_ffmpeg_filter("vpp_qsv"))
@slash.requires(usin... |
# Copyright Ramón Vila Ferreres - 2021
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR AN... |
# -*- coding: utf-8 -*-
from base.models import AppOptions, Author, OauthAccount, Post, Taxonomy
from google.appengine.ext import ndb
from custom.utils import rst2html, md2html
def to_slug(string):
"""缩略名
:param string: str
:return: str
"""
import re, urllib
ret = re.sub(r'([_\+=!?.\'"]|\s)+'... |
from lasagne.layers import Layer
import theano.tensor as T
import lasagne
class TensorDotLayer(Layer):
def __init__(self, incoming, n_filters, axis, W=lasagne.init.Normal(),
**kwargs):
super(TensorDotLayer, self).__init__(incoming, **kwargs)
self.axis = axis
axis_length = i... |
#import urllib2
import csv
import sys
import re
from datetime import datetime
import time
import pandas as pd
import configparser
import hashlib
import os
import rdflib
import logging
logging.getLogger().disabled = True
if sys.version_info[0] == 3:
from importlib import reload
reload(sys)
if sys.version_info[0] == ... |
# here are some trick in python ...
class A:
psss = 0
a = A()
print(a.__class__)
class B(A):
def __init__(self):
print("Inside the B")
b = B()
print(b.__class__)
# note:-
# ' object.__class__ ' return the class name
print(isinstance(b, B)) # isinstance() method return true or false
print(issubclass(B,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 6 12:42:44 2020
@author: catiefinkenbiner
"""
import numpy as np
import scipy as sp
from scipy import stats
## Step 4 Use prediction to create conditional copula generated values
def main(tsP,xday_stats,H_scale,O_scale):
# Observed P statistic... |
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from mainApi.models import UserProfile, AllMedHistory
from mainApi.models import AllEvent, UserEvent, Like, Comment, UserCreatedEvent
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_fr... |
from pyparsing import Or, Group, ZeroOrMore, Literal
from .lexical_items import number, HYPHEN_MINUS, identifier, LEFT_PARENTHESIS, RIGHT_PARENTHESIS, \
COMMA, modulereference, FULL_STOP, valuereference, RIGHT_CURLY_BRACKET, LEFT_CURLY_BRACKET, \
cstring
NULL = Literal("NULL")
# 19.1
SignedNumber = Or([
... |
from re import compile, finditer
REGEX = compile(r'(?P<chunk>[a-zA-Z]+)(?:_|-|$)')
def to_camel_case(text):
result = []
for i, a in enumerate(finditer(REGEX, text)):
current = a.group('chunk')
if not i and current[0].islower():
result.append(current.lower())
else:
... |
"""
Unit and regression test for the maxsmi package.
"""
# Import package, test suite, and other packages as needed
# import maxsmi
import pytest
import sys
import torch
from maxsmi.utils_evaluation import evaluation_results
def test_maxsmi_imported():
"""Sample test, will always pass so long as import statement... |
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
res = [[], []]
for i in range(len(nums1)):
if nums1[i] not in nums2 and nums1[i] not in res[0]:
res[0].append(nums1[i])
for i in range(len(nums2)):
if nu... |
'''
Created on Nov 9, 2016
@author: micro
'''
import numpy as np
import cv2
def find_marker(image):
#convert the image to grayscale, blur it, and detect edges (in that order))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5,5), 0)
edged = cv2.Canny(gray, 35... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.terraform.dependencies import TerraformInitRequest, TerraformInitResponse
from pants.backend.terraform.target_types import TerraformDeploymentFieldSet
from pants.backend.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import shelve
import requests
from oauthlib.oauth2 import TokenExpiredError
from requests_oauthlib import OAuth2Session
from six.moves.urllib.parse import urljoin
from pymonzo.api_objects import MonzoAccount, MonzoBalance, MonzoTransaction
fro... |
from flask_wtf import Form
from wtforms import StringField, PasswordField, TextAreaField
from wtforms.validators import (DataRequired)
class LoginForm(Form):
value = StringField('********', validators=[DataRequired()]) |
#! /usr/bin/env python
from __future__ import division
from numpy import *
from numpy.random import normal
from scipy.stats import norm,betai
from scipy.special import betaln
from pylab import where
from scipy import weave
def lprob2sigma(lprob):
""" translates a log_e(probability) to units of Gaussian sigmas
... |
# Generated by Django 2.2.4 on 2019-09-16 08:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('whiskydatabase', '0029_auto_20190914_1232'),
]
operations = [
migrations.AlterField(
model_name='personalwhiskynote',
... |
print('doesn\'t')
print('"si,"le dijo.')
|
#!/usr/bin/env python
print(" ")
print(" ")
print("MMMMM MMMMM AAAA CCCCCCCCCC ")
print("MMM MM MM MMM AAA AAA CCC ")
print("MMM MM MM MMM AAA AAA CCC ")
print("MMM MM MMM AAA@@@@@@AAA ... |
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework import status
from .services import *
from .permissions import *
from utils.serializer_validator import validate_serial... |
import time
import pandas as pd
from random import random, randint
from kafka import KafkaConsumer, KafkaProducer
class UserLocationProducer():
MALL_GPS_LOC = (28.457523, 77.026344)
LATTITUDE = 28.457523
LONGITUDE = 77.026344
# approximate radius of earth in km
R = 6371.0087714150598
@static... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# ... |
# -*- coding: utf-8 -*-
'''
Copyright of DasPy:
Author - Xujun Han (Forschungszentrum Jülich, Germany)
x.han@fz-juelich.de, xujunhan@gmail.com
DasPy was funded by:
1. Forschungszentrum Jülich, Agrosphere (IBG 3), Jülich, Germany
2. Cold and Arid Regions Environmental and Engineering Research Institute, Chinese Academ... |
void preorder(node * root) {
if(root == NULL)
return
cout << root -> data << " "
preOrder(root -> left)
preOrder(root -> right)
}
e
|
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_VisualizerMainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(772, 800)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
... |
import threading
import time
def run(n):
print("task:",n)
time.sleep(2)
print("task-end",n)
# t1 = threading.Thread(target=run,args=('t1',))
# t2 = threading.Thread(target=run,args=('t2',))
# t1.start()
# t2.start()
thread_list = []
start_time = time.time()
for i in range(50):
t = threading.Thread(ta... |
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DetailView, DeleteView
from .models import Material
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
# Create yo... |
from datetime import datetime, timedelta
import json
import inspect
# https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
def GetCurrentQuarterStartDate() -> datetime:
return FindQuarterDates(datetime.now())[0]
def GetCurrentQuarterEndDate() -> datetime:
return FindQuarterDates(datet... |
# activate theano on gpu
from __future__ import print_function
import os;
os.environ['THEANO_FLAGS'] = "device=gpu";
import theano;
theano.config.floatX = 'float32';
import numpy as np;
import sys, os;
import gzip;
from six.moves import cPickle;
from vae_conv import conv_variational_autoencoder;
from keras import bac... |
#!/usr/bin/python
import math
total = 0
for n in range(1, 101):
for r in range(n):
if math.factorial(n) // math.factorial(r) // math.factorial(n - r) > 1000000:
total += 1
print(total)
|
from flask import Blueprint, url_for
import app.adapters.repository as repo
import app.utilities as util
# Configure Blueprint.
services_blueprint = Blueprint(
'services_bp', __name__)
def get_genres_and_urls():
genres_name = util.get_genres(repo.repo_instance)
genre_url = dict()
for genre in genres... |
#https://gist.github.com/stared/dfb4dfaf6d9a8501cd1cc8b8cb806d2e
import keras
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Flatten, Dense, Activation
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib impor... |
import requests
def check(pin):
try:
response = requests.get('http://localhost:8000')
except:
response = None
if response and response.status_code == 200:
try:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(... |
# SQLite and Python
# Anatoli Penev
# 15.04.2018
# SQLite integration in Python
import sqlite3
import sys
# connect to the database
conn = sqlite3.connect("C:\\sqlite\\EAL.db")
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE customer(
idCust integer NOT NULL,
... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.javascript.subsystems import nodejs
from pants.backend.openapi.lint.openapi_format import rules as openapi_format_rules
from pants.backend.openapi.lint.openapi_format im... |
from unittest import TestCase
import msal
from settings import settings
from office365.graph_client import GraphClient
def get_token():
"""
Acquire token via MSAL ROPC flow!
"""
authority_url = 'https://login.microsoftonline.com/{0}'.format(settings['tenant'])
app = msal.PublicClientApplication... |
from rest_framework import viewsets, status
from .models import Notification
from .serializers import NotificationSerializer
from rest_framework import viewsets, status
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from annoying.functions import get_object_o... |
from itm import ITM
class Sim_Com(ITM):
def __init__(self, k, bits, crupt, sid, pid, channels, pump, poly, importargs):
self.crupt = crupt
self.ssid = sid[0]
self.committer = sid[1]
self.receiver = sid[2]
self.table = {}
self.revtable = {}
self.receiver_rand... |
"""
We are going to define a simple form with an action and two fields
coming from a Zope interface.
We put our example in a separate file, since the configure.zcml of
zeam.form needs to be loaded in order to be able to create the fields,
which is no the case when the tests are collected.
Let's grok our example:
>... |
# Copyright 2017 The Forseti Security 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 required by a... |
import socket
from gosnu.consumer import Consumer
from gosnu.producer import Producer
class Connection():
def __init__(self, ip, port=8081):
self.ip = ip
self.port = port
self.tcp_client = None
def connect(self):
# Initialize a TCP client socket using SOCK_STREAM
self... |
from virtualscada.vs import removeRows
from virtualscada.vs import removeValues
from virtualscada.vs import fillValuesMLPFForward |
#!/usr/bin/env python3
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com
# miTorch: Medical Imaging with PyTorch
# Deep Learning Package for 3D medical imaging in PyTorch
# Implemented by Mahdi Biparva, April 2021
# Brain Imaging Lab, Sunnybrook Research Institute (SRI)
import torch
import num... |
from cap_res_prob import CapResProb
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import time
np.random.seed(0)
# Small example:
n = 20 # Number of nodes.
m = 50 # Number of edges.
K = 10 # Number of scenarios.
# Large example:
# n = 2000 # Number of nodes.
# m = 5000... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from revolver import contextmanager as ctx
from revolver import directory as dir
from revolver import package, file, core
def install():
package.ensure(["curl", "git-core"])
if not dir.exists(".php-build"):
cor... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.engine.target import (
COMMON_TARGET_FIELDS,
Dependencies,
MultipleSourcesField,
SingleSourceField,
Target,
TargetFil... |
from collections import OrderedDict
absolute_path = r'D:\__Alexzander_files__\__computer_science__\python_stuff\andrew_packages\programming_problems\reply_challenge'
class TestCase:
def __init__(self, index, total_teams, total_logs, teams_stats_list):
self.index = index
self.total_teams =... |
class SymbolTable:
def __init__(self):
self.symbol_table = {
'scope_0': {
'name': 'scope_0',
'parent': None,
'rules': [],
}
}
self.current_scope = 'scope_0'
def insert(self, symbol):
self.symbol_table[self.c... |
import speech_recognition as sr
import struct
import base64
import wave
import matplotlib.pyplot as plt
import numpy as np
from scipy.fft import fft, ifft
r = sr.Recognizer()
myframerate = 88000
mychannel = 1
mysampleWidth = 2
duration = 7 # edit duration of sound here
myframes = duration * myframerate... |
from jousting.round.phase import Phase
from jousting.util.dice import D6, roll
from jousting.util.rps import SHIELD
class TasteOfTheLance(Phase):
def do_taste_of_the_lance(self):
p1 = self._controller.get_p1()
p2 = self._controller.get_p2()
if not p1.get_failed_to_start() and not p2.get_f... |
import numpy as np
def bootstrap_idx(dataset_size, n_bootstraps=150):
"""
Obtains indices for bootstrapping
:param dataset_size: size of the dataset
:param n_bootstraps: number of bootstraps to run
:return:
"""
data_idx = np.random.choice(np.arange(dataset_size), size=(n_bootstraps, dataset... |
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import os
import time
import re
import random
import json
import threading
se = requests.session()
class Pixiv():
def __init__(self):
self.base_url = 'https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index'
... |
# -*- coding: utf-8 -*-
import unittest
import time
class TestGenerator(unittest.TestCase):
def setUp(self):
pass
def simple_generator(self):
yield 2
for i in range(10):
yield i
def test_simple(self):
for i in self.simple_generator():
pass
... |
import xlrd
import traceback
import json
import sys
def convert_jet():
input_filename = 'JetCategories.xlsx'
output_filename = 'jet_categories.json'
# output_filename1 = 'pricefalls_categories1.json'
xls_categories = get_xls_data(input_filename)
categories_list = get_categories_list(xls_categories... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given a positive integer, output its complement number.
# The complement strategy is to flip the bits of its binary representation.
# Note:
# The given integer is guaranteed to fit within the range of a 32-bit signed integer.
# You could assume no leading zero bit in the ... |
import arcpy
arcpy.env.overwriteOutput = True
folder = arcpy.GetParameterAsText(0)
datapoints = arcpy.GetParameterAsText(1)
pieceofplace = arcpy.GetParameterAsText(2)
nameDataBase = arcpy.GetParameterAsText(3)
arcpy.CreateFileGDB_management(folder, nameDataBase + '.gdb')
arcpy.AddMessage('Created new File GDB: {}.gdb... |
s=input('Enter:')
temp=''
for i in s:
temp=i+temp
if temp==s:
print('Palindrome')
else:
print('No') |
def saludar():
print('Hola')
from tkinter import*
ventana=Tk()
boton=Button(ventana, text='Púlsame', command=saludar)
boton.pack()
|
# -*- 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 OpenPensionCrawlerItem(scrapy.Item):
# The fields for out item
file_name = scrapy.Field()
page_url = scrapy.Field()
|
from __future__ import print_function
import os
# TODO: Add theano if statement check
# activate theano on gpu
#os.environ['THEANO_FLAGS'] = "device=gpu"
#import theano
#theano.config.floatX = 'float32'
import numpy as np
import sys
import gzip
from six.moves import cPickle
from vae_conv import conv_variational_auto... |
#!/usr/bin/python3
from PIL import ImageFile
import sys
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BACKG = (30, 30, 30)
GREEN = (0, 128, 0)
THRESHOLD = 150
def distance(pixel, color):
distance = 0
for i in range(3):
distance += pow(color[i] - pixel[i], 2)
return distance
def is_green(pixel):
... |
#maxtrix사용 안했을때#
import tensorflow as tf
tf.compat.v1.enable_eager_execution()#그래프를 생성하지 않고 함수를 바로 실행하는 명령형 프로그래밍 환경
#난수 생성 초기값 부여
tf.compat.v1.set_random_seed(0)#set_random_seed를 통해 모든 random value generation function들이 매번 같은 값을 반환함
x1 = [73., 93., 89., 96., 73.]
x2 = [80., 88., 91., 98., 66.]
x3 = [75., 93.,... |
from objects import *
import pygame
from homescene import HomeScene
from game import App
class WinnerScene:
def __init__(self, post_game):
self._running = True
self.size = self.width, self.height = 400, 800
self.post_game = post_game
self.center = (self.width/2, self.height/2)
... |
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
import ssl
import requests
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter URL - ')
if len(url... |
import cv2
import numpy as np
# Global Varibules
res = [1280, 720]
eps = 1.5
face_cascade = cv2.CascadeClassifier('/Users/jeremy.meyer/opencv/data/haarcascades/haarcascade_frontalface_default.xml')
# Draws bounding box and text from coordinates.
def bbox(img, x1, y1, x2, y2, base_color=(255, 0, 0), text='Human Det... |
__author__ = "Narwhale"
#考察匿名函数把t1和t2合并用zip函数,再将k,v合并成字典,考察列表推导式
# t1 = (('a'),('b'))
# t2 = (('c'),('d'))
# res = lambda t1,t2:[{k:v} for k,v in (zip(t1,t2))]
# # res = lambda t1,t2:[dict(zip(t1,t2))]
# print(res(t1,t2))
################################################
#什么是匿名函数,匿名函数有什么好处?
#当我们创建函数时不需要显示的定义函数,省去了给... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.