text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
# Compare a file on S3 to see if we have the latest version
# If not, upload it and invalidate
import hashlib
import os
import sys
import threading
import time
import logging
import boto3
from optparse import OptionParser
from datetime import datetime
from time import gmtime, strft... |
import json
import pandas as pd
from api.repositories import balances_repo, products_repo, prices_repo, users_repo, transactions_repo
from api.shared.helpers.pricing_helper import calculate_asset_balance
from api.shared.helpers.holdings_helpers import map_product, map_price, map_spot
def calculate_balance(user_id, ti... |
import scipy.io as sio
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
mat = sio.loadmat('PCA.mat')#load the mat file where X= 3+1+8+1= 13
#print(mat)#for key in mat:print(key)
# Extracting specific keys from dictionary- extract the ['DataMatrix']
res = dict((k, mat[k]) fo... |
from interf import *
numBits = 5
def constant0(x: int) -> int:
return 0
def constant1(x: int) -> int:
return 1
def balanced1(x: int) -> int:
return x % 2
def balanced2(x: int) -> int:
if (x < (2**numBits)/2):
return 0
return 1
def balanced3(x: int) -> int:
return 1 - balanced2(x)
... |
"""OpenAQ Air Quality Dashboard with Flask."""
from flask import Flask, render_template, request
import openaq
from flask_sqlalchemy import SQLAlchemy
APP = Flask(__name__)
# set up API object
api = openaq.OpenAQ()
# retrieve data from API and put into list
# return [('2019-03-08T00:00:00.000Z', 8.13), ('2019-03-07T... |
import torch
from core import TT
from module import Module
import utils
from utils import round_tt # round_tt is used in doctests
class LinearNoBatching(Module):
"""Linear transormation layer. No batching.
Search for the `Linear` class below for a version which
supports batching.
Example:
>>... |
from django.contrib import admin
from account.models import ProjectUser
admin.site.register(ProjectUser) |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
this implements a simple metric to quantify synteny score of blast hits
the score is contributed by the quality and density of the blast pairs nearby
weighted by the distance to the query blast pair
"""
import sys
import pprint
import collections
import numpy as np
f... |
import vk_api, requests, json, db
from random import randrange
from vk_api.longpoll import VkLongPoll, VkEventType
from infons import *
vk_session = vk_api.VkApi(token=group_token)
longpoll = VkLongPoll(vk_session)
def get_keyboard(buts):
nb = []
for i in range(len(buts)):
nb.append([])
for k ... |
import os
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from simple import simple_form
from custom_templates import contact_form
from custom_validators import validators_form... |
# Arithmetic expressions - numbers, operators, expressions
# Operations
# Addition, Subtraction, Multiplication, and Division
# They are calculated as usual according to the order of
# operations
# Addition
print "Ex. 1:", 4 + 5
print "Ex. 2:", 3 + 4 + 7
print
# Subtraction
print "Ex. 3:", 5 - 2
prin... |
fo=open("demp.txt","w")
##fo.write("Hello Python \n")
##fo.write("This is sid")
words=["first\n","second\n","third"]
fo.writelines(words)
fo.close() |
'''
This script saves the digis and the
'''
import ROOT as r
import numpy as np
import argparse
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=str, required=True)
parser.add_argument('-o', '--output', type=str, required=True)
args = parser.parse_args()
f = r.TFile(a... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from django.db import models
# Create your models here.
class Category(models.Model):
title = models.CharField(default='', max_length=200)
slug = models.CharField(max_length=100, default='')
description = models.TextField(default='')
active = models.BooleanField(default=True)
def __str__(self):
... |
#!/usr/bin/env python
#
# command-line VEX lifter
import sys
import angr
RED = '\x1B[31m'
NORMAL = '\x1B[0m'
def usage():
print('usage: %s <platform> <bytes>' % sys.argv[0])
print('')
print('examples:')
print(' eg: %s ARM 14 d0 4d e2 01 20 a0 e1 00 30 a0 e1 00 c0 a0 e3' % sys.argv[0])
print(' eg: %s ARM64 6... |
import pcl
p = pcl.load("tabletop.pcd", loadRGB=True)
fil = p.make_statistical_outlier_filter()
fil.set_mean_k(50)
fil.set_std_dev_mul_thresh(1.0)
pcl.save(fil.filter(), "tabletop_inliers.pcd")
fil.set_negative(True)
pcl.save(fil.filter(), "tabletop_outliers.pcd") |
#I've tested with Nexus7010-version 6.2(8) this code.
#When a user enters a IP, you can check the MAC / VLAN / Interface / Description information.
#Example Result)
#NEXUS-7K# python ipinfo.py 10.10.10.12
#10.10.10.12 : Not found IP Address Infomation
#NEXUS-7# python ipinfo.py 10.10.10.11
#========================... |
from __future__ import print_function
from flask import request, Blueprint
import time, traceback
from sys import path, stderr
from os import getenv, getcwd
from requests import get, post
path.append(getcwd())
from . import task_utils
# from task import task_utils
task_app = Blueprint('task_app', __name__)
task_hand... |
import re
string = """
sadadasd file_name.txt dfdasfafdjlf;jldaf\n
fdsfasfdfdfdsf f.txt ddfafdfdsfdsf\n
dafdsfafddsfads gggg.txt dfasdfaf"""
find_list = re.findall(' \w+.txt', string)
for f in find_list:
print f[:-4] |
import sublime, sublime_plugin
class ConvertSpacesToTabs(sublime_plugin.TextCommand):
def run(self, edit):
self.view.run_command('unexpand_tabs', {"set_translate_tabs": False}) |
"""
monobit.constants
(c) 2019--2023 Rob Hagemans
licence: https://opensource.org/licenses/MIT
"""
VERSION = '0.42'
CONVERTER_NAME = f'monobit v{VERSION}'
|
# coding=utf-8
import billiard as mp # billiard used for compatibility with Celery
from forecasting_engine.holtwinters_forecast import HoltWinters
from forecasting_engine.arima_forecast import Arima
from forecasting_engine.auto_arima import Auto_Arima
from forecasting_engine.hw_new import HoltWinters_new
from forecast... |
import tweepy
from textblob import TextBlob
consumer_key = 'nuCCcKoG0CwzTyW39WxWWlSVW'
consumen_secret = 'IutAmoVEZUkwgrEivasMRnE2KFyFRQux1ZoMtqhIlEiaMYezYd'
access_token = '1257246690441965568-BMUAt5yO1wqBbkznps9OnFOJp08hd2'
access_token_secret = '0SDI1NbnxKHdeN6z7cc6aJ8RHgHKBTtReAKPMrXc5gDKp'
auth = tweepy.OA... |
import music.midi as midi
import threading
import time
import random
import warnings
from utilities import sprout, scale
from copy import copy
import global_vars
midi = global_vars.midi
min_piano_dur = global_vars.min_piano_dur
events = global_vars.events
class Instrument:
playing = False
frozen = False
r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set noexpandtab:
import json
import urllib
import urllib2
import base64
import time
import sys
import os
import re
from datetime import datetime, timedelta
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencod... |
hour, minute = map(int, input().split(' '))
time = int(input())
minute += time
if minute >= 60:
hour += minute // 60
minute %= 60
if hour > 23:
hour %= 24
print(hour, minute)
|
from pypurr.cli.build_dataset import _build_dataset
from pypurr.cli.extract_negatives import _extract_negatives
from pypurr.cli.train_cli import _train
if __name__ == '__main__':
for run_id in range(15, 25):
_extract_negatives(run_id)
_build_dataset(run_id)
_train(run_id) |
months = ["",
"JANUARY",
"FEBRUARY",
"MARCH",
"APRIL",
"MAY",
"JUNE",
"JULY",
"AUGUST",
"SEPTEMBER",
"OCTOBER",
"NOVEMBER",
"DECEMBER",
]
class indexPage():
def __init__(self, selenium... |
from django.urls import path
from django.contrib.auth import views as auth_views
from website import views
urlpatterns = [
path('register/', views.register, name="register"),
path('profile/', views.profile, name="profile"),
path('login/',
auth_views.LoginView.as_view(template_name="website/login.... |
"""
Stable Version of grabCoordinates
To be used with MCMC_CircularGaussian
This is the GUI promt that will ask the user to choose an image file (.fits format) and specify which part of the image to calculate the flux of a bright object such as a quasar or galaxy
Depends on MCMC_CircularGaussian to run. This conta... |
# from collections import defaultdict
rr = lambda: input()
rri = lambda: int(input())
rrm = lambda: list(map(int, input().split()))
INF=float('inf')
primes = None # set later on
def solve(N,A):
# O(n^2)
used = set()
pairs = []
for i in range(len(A)):
if i in used:
continue
# search for same parity
for j... |
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from hospital.commons.api.v1.serializers.contact import ContactSerializer
from hospital.commons.models import contact
class ContactViewSet(viewsets.ModelViewSet):
queryset = contact.objects.all()
serializer_class = ContactSer... |
from numpy import *
from numpy.fft import *
from matplotlib.pylab import *
from misc import *
from scipy.ndimage import *
# from skimage.filters import *
import os
from skimage.feature import register_translation
from scipy.ndimage import fourier_shift
import pickle
from scipy.misc import imresize
def ImgToArray(I):
... |
# -*- coding: utf-8 -*-
""" Inherit ~tornado.web.RequestHandler to change the template engine,
and define a decorator to wrap handler to do url route.
Here is the example::
from common.web import BaseHandler, route
@route(r'/')
class IndexHandler(BaseHandler):
def get(self):
self.wri... |
# Programmer: David Romanski
# Pi Madhava Formula
# Created: 04/09/2020
# Updated: 04/12/2020
# This program uses the Madhava formula to estate Pi
# Updated to include a loop
answer = 1
x = 50000
denom = 1
while (x>0):
denom += 2
print(4*answer)
answer -=1/denom
denom += 2
print(4*answer)
answe... |
# -*- coding:utf-8 -*-
"""
输入两个非负10进制整数A和B(<=230-1),输出A+B的D (1 < D <= 10)进制数。
输入格式:
输入在一行中依次给出3个整数A、B和D。
输出格式:
输出A+B的D进制数。
输入样例:
123 456 8
输出样例:
1103
"""
a, b, d = map(int, raw_input().split())
n = a + b
r = ''
while True:
n, i = divmod(n, d)
r += str(i)
if n == 0:
break
print r[::-1]
|
from pygame import draw, Rect, Surface
from guns.ASnarad import APatron
from old.Ini import write_ini_file
SPEED = int(write_ini_file().get("Others", "speed of bullet"))
RADIUS = int(write_ini_file().get("Others", "radius bullet"))
BLOCK_SIZE = int(write_ini_file().get("Others", "block size"))
class Patron2(APatron... |
# -*- encoding: utf-8 -*-
#------------------------------------------------------------------------#
# Programa: Punto de venta 2.0 #
#------------------------------------------------------------------------#
# Propósito: conexion a la BD #
#---... |
from parameter_tuning.optimized_nio.mf_optimized_pso_plume import PSO
from applications.plume import GaussianPlumeEAAI
import numpy as np
def main():
"""PSO solving the source term estimation problem."""
# Model setup
source = np.array([1500, 8, 10, 5]) # assume source concentration and 3D coordinates
... |
#
# Copyright (c) 2020 by Alexis LEBEL, BOUDRY Hugo and PEDROSA Théo. All Rights Reserved.
#
import sys
sys.path.insert(0, "ioactions")
sys.path.insert(0, "gui/launcher")
import csvactions as csvactions
import settings as settings
import launcher
sett = settings.Settings('settings.yaml')
launch = launcher.Launcher()
... |
# -*- coding: utf-8 -*-
import entity.cards.BARL_015H.LETL_390
import entity.cards.BARL_015H.LETL_391
import entity.cards.BARL_015H.LETL_392
|
import plugins, os
def _initialise(bot):
plugins.register_handler(_got_a_message, type="message", priority=50)
def _got_a_message(bot, event, command):
if "merkle" in event.text.lower():
yield from bot.coro_send_message(
event.conv,
_("YOU SAID THE SECRET WORDDDDDD!!!").format... |
import random
class PlaneSimulator(object):
def __init__(self, plane):
self.plane = plane
def generate_tilt(self):
tilt = random.gauss(0, 1)
if -45 < tilt < 45:
return tilt
return self.generate_tilt()
def __iter__(self):
while True:
print "... |
# 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, software
# distributed under the... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the model module.
"""
from astropy.io import fits
import numpy as np
import os.path as op
import pytest
from .make_test_data import make_test_image
from ..ellipse import Ellipse
from ..geometry import EllipseGeometry
from ..model import bui... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 09:57:47 2020
@author: sjsty
"""
import numpy as np
import numpy.random as rnd
from sklearn.linear_model import LinearRegression
import threading
import logging
LRn222 = 3.8235 * 24 * 60 * 60 # the half-life for Rn-222 (in seconds)
LPo218 = 3.098 ... |
"""This module contains dialogues, which will query user input"""
from functools import lru_cache
import contextlib
with contextlib.redirect_stdout(None):
import pygame
from . import surface_composition as psc
from . import eventlistener as pel
from . import misc
def _center_renderer(elem):
misc.display(psc... |
from tasks.set_tasks.union import get_union
def test_get_union(new_set):
assert get_union(new_set, {3, 4, 6, 7, 8, 9, 10}) == {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}
|
from django.shortcuts import render
# Create your views here.
from django.http import JsonResponse
from django.core import serializers
import json
from .models import information
def show_information(request):
if request.method == "GET":
内容 = information.objects.all() #从数据库获取数据QuerySet类型
内容 = j... |
from rest_framework import serializers
from common.models.general import Sector
class SectorSerializer(serializers.ModelSerializer):
label = serializers.StringRelatedField(source='Description')
value = serializers.StringRelatedField(source='SectorId')
class Meta:
model = Sector
fields = (... |
from relier.web.views import AuthenticatedView
from relier.models import Invitation
from flask import render_template, g, abort, redirect, request
class DeleteInvitation(AuthenticatedView):
def get(self, invitation_id):
if not g.user.is_admin:
abort(403)
if Invitation.select().where(... |
import abc
import math
class Location(abc.ABC):
def __init__(self, disaster=None):
self._disaster = disaster
self._population = 0
self._old_pop = 0
@property
def population(self):
pass
@abc.abstractmethod
def random(self):
pass
@abc.abstractmet... |
import os
from pipes import quote
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
# Which district
NONE = ""
DISTRICT_1 = "District 1 - Drew Pearson"
DISTRICT_2 = "District 2 - Alex Madsen"
DISTRICT_3 = "District 3 - Scott Peterson"
DISTRICT_... |
# -*- encoding: utf-8 -*-
"""
@File : 883-三维形体投影面积.py
@Time : 2023/08/08 11:18:10
@Author : TYUT ltf
@Version : v1.0
@Contact : 18235121656@163.com
@License : (C)Copyright 2020-2030, GNU General Public License
"""
# here put the import lib
from typing import List
"""
在 n x n 的网格 grid 中,我们放置了一些与 x,y,... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread('data/img5.jpg',cv2.IMREAD_COLOR)
#cv2.imshow('before',img)
img=cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
Y=img[:,:,0]
Y=cv2.equalizeHist(Y)
img[:,:,0]=Y
img=cv2.cvtColor(img,cv2.COLOR_YCR_CB2BGR)
#cv2.imshow('after',img)
cv2.imwrite('equalize... |
from ZZ_Libraries import alpaca_trade_api as tradeapi
from BeginnerPractice import Read_A_CSV
API_KEY = "************"
API_SECRET = "***********************"
APCA_API_BASE_URL = "https://paper-api.alpaca.markets"
def run_strategy(var14=None, var16=None):
# orders = self.alpaca.list_orders(status="open")
# o... |
def calcWin(userPick, compPick): #Diese Funktion überprüft anahnd von zwei Eingaben wer Gewonnen hat.
if userPick == compPick:
return "same"
if userPick == "Schere":
if compPick == "Stein":
return "compWin"
elif compPick == "Papier":
return "userWin"
else:... |
import tweepy
import time
print("\n\nHelloWorld! I am BOT. My name is Hola\n\n")
CONSUMER_KEY = 'XXXXXX'
CONSUMER_SECRET = 'XXXXXX'
ACCESS_KEY = 'XXXXXX'
ACCESS_SECRET = 'XXXXXX'
auth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY,ACCESS_SECRET)
api = tweepy.API(au... |
from model.encoder_model import *
class EncoderModelWrapper:
""" Wrapper for encoder model """
@staticmethod
def get_encoder_model(model_type, config, constants, bootstrap_model=None):
if model_type == "backwardmodel":
return BackwardEncoderModel(config, constants, bootstrap_model)
... |
# https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
# 121. 买卖股票的最佳时机
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
mini = prices[0]
ret = 0
for i in prices:
ret = max(ret, i - mini)
mini = min(mini, i)
... |
from copy import deepcopy
from priorityQueues.priorityQueue import AdaptableHeapPriorityQueue
from priorityQueues.priorityQueue import HeapPriorityQueue
class Vertex:
"""Lightweight vertex structure for a graph"""
def __init__(self, x):
"""Do not call constructor directly. Use Graph's insert.vertex(x)"... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from .forms import CreateMainEvent, ModifyMainEvent, CreateSmallEvent, ModifySmallEvent
from .forms import RegisterToEvent, AddOpinion
from .models import EventRegister, EventSmallRegister, eventOpinion, M... |
from celery import task
from oms_pds.pds.models import Profile, Notification, Device
from bson import ObjectId
from pymongo import Connection
import time
from datetime import date, timedelta
import json
import pdb
import math
import cluster
import requests
import random
from gcm import GCM
from oms_pds.pds.models impor... |
import numpy as np
import json
word2class={int(k):v for k,v in json.load(open("code/train_dict_network/out_all_5000_sequestered/label_dict.json")).items()}
lines=[l.split(",") for l in open("code/train_dict_network/rendered_image_preds.csv").read().strip().split("\n")[1:]]
probs=np.array([float(l[1]) for l in lines]... |
from db.run_sql import run_sql
from models.artist import Artist
def save(artist):
sql = "INSERT INTO artists (name) VALUES (%s) RETURNING *"
values = [artist.name]
results = run_sql(sql, values)
id = results[0]['id']
artist.id = id
return artist
def delete_all():
sql = "DELETE FROM artist... |
import smtplib
smtp_server = "smtp.gmail.com"
port = 465 # For SSL
sender_email = "mostafa.3zazi@gmail.com"
receiver_email = "mostafa.3zazi2@gmail.com"
message = """\
Subject: enter the subject here
write your message."""
#gmail pass for sender email
password = "enter your password here"
server =... |
import asyncio, time, re, hashlib, json, logging, markdown2
from coreweb import get, post
from aiohttp import web
from models import User, Blog, Comment, next_id
from apis import APIError, APIValueError, APIPermissionError, APIResourceNotFoundError, Page
from config import configs
logging.basicConfig(level=logging.INF... |
#!/usr/bin/env python3
import asyncio
import pytz
import datetime
import pycountry
import urllib.parse, urllib.request, json
import discord
import re
from discord.ext.commands import converter, errors
from discord import utils
from utils import database, shared
def age_from_birthdate(birthdate):
born = datetime... |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ll1, ll2 = l1, l2
node = ListNode(0)
head = node
carry = 0
while ll1 and ll2:
val = (... |
from __future__ import division
# these things are bits of old code or need updating
####################################################
# possiblechangepoints stuff (power application) #
####################################################
# NOTE: these only work with iid-like emissions with aBl (that includes
#... |
from datetime import datetime
from mock import patch
from gittip.billing.payday import Payday
from gittip import testing
from gittip import wireup
from tests import serve_request
class TestStatsPage(testing.GittipBaseTest):
def get_stats_page(self):
response = serve_request('/about/stats.html')
... |
#!/usr/bin/python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
#!/Users/nicolasf/anaconda/bin/python
import os
import sys
import argparse
import json
import matplotlib
matplotlib.use('Agg')
sys.path.insert(0, '../')
from paleopy import analogs
from paleopy import ensemble
from paleopy import WR
from paleopy.plotting import scalar_plot
from paleopy.plotting import indices
from p... |
"""
Utility constants and functions for Old Bird detector evaluation.
Edit the RECORDINGS_DIR_PATH, ANNOTATIONS_DIR_PATH, and WORKING_DIR_PATH
constants below to set the input and output directories for the
run_old_bird_detectors and evaluate_old_bird_detectors scripts.
Edit NUM_DETECTION_THRESHOLDS to adjust the num... |
def lcm(x,y):
if x>y:
x,y=y,x
for i in range(y,(x*y)+1,y):
if i%x==0:
return i
x,y=map(int,input().split())
res=lcm(x,y)
print(res) |
listaVariables = []
def return_variable(nombre_var):
global listaVariables
for variable in listaVariables:
if variable.nombre == nombre_var:
return variable
class Variable:
def __init__(self, nombre, valor):
self.__nombre = str(nombre)
self.__valor = int(valor)
d... |
from operator import itemgetter
from time import sleep
from random import choice
from multiprocessing import Pool
spells = {
'Poison':
{
'rank': 0,
'name': 'Poison',
'cost': 173,
'dmg': 3,
'hp': 0,
'armor': 0,
'mana': 0,
'effect': 6
},
'Shield':
{
'rank': 1,
... |
from enum import Enum
from enum import IntEnum
from typing import List
import pytest
from drf_yasg import openapi
import winter
from winter.web.routing import get_route
from winter_openapi import PathParametersInspector
class IntegerValueEnum(Enum):
RED = 1
GREEN = 2
class StringValueEnum(Enum):
RED =... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
python indexlot.py IndexLotDatasetAPITask --local-scheduler
python tasks/indexlot.py IndexLotDatasetCSVTask --local-scheduler
"""
import luigi
import pandas as pd
from collections import Orde... |
from turtle import Turtle, Screen
from pong import Pong
from ball import Ball
from scoreboard import ScoreBoard
import time
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)
pong_1 = Pong((350, 0))
pong_2 = Pong((-350, 0))
ball = Ball()
scor... |
#Importing json
import json
#Variable to store dictionary
game_stats = []
#Lists containing information about current level
ranks = ['Elementary School', 'Junior High', 'High School', 'Undergraduate Student', 'Graduate Student', 'PhD student', 'Teaching Assistant', 'Associate Professor','Full Professor','Nobel Prize ... |
import requests
from requests.auth import HTTPDigestAuth
url = 'https://smithping.herokuapp.com/ping'
r = requests.get(url, auth=HTTPDigestAuth('vcu', 'rams'))
print(r.text)
|
def multiply(pi1, pi2):
result = {}
for key in pi1:
value = pi1[key]
result[key] = pi2[value]
return result
def pi_reversed(pi):
result = {}
for key, value in pi.items():
result[value] = key
return result
def generate_n_identity_permutation(n):
result = {}
f... |
#!/usr/bin/env python
'''reports a summary of the database - needs more work'''
from __future__ import division
import sys
sys.path.extend(['..'])
from chippy.express.db_query import make_session, get_chroms, get_species,\
get_sample_counts, get_reffile_counts, get_gene_counts, get_exon_counts,\
get_... |
# 注意10.5和11.5的区别
print(round(10.4)) #10
print(round(10.5)) #10
print(round(10.6)) #11
print()
print(round(11.4)) #11
print(round(11.5)) #12
print(round(11.6)) #12 |
import math
import numpy
from lib.gnc.control.frames import Frames
from lib.tools.conversions import unit_vector
class Communication(Frames):
''' Communications Pointing Control Mode '''
def __init__(self):
super(Communication, self).__init__()
self.fname = 'communication'
def track(sel... |
import objgraph
from flask import Response
import uuid
import time
import gc
from pympler.asizeof import asizeof
class Agent:
stringCount = 0
global isWaiting
global startTime
global endTime
def __init__(self):
self.stringCount = 0
self.startTime = 0
self.isWaiting = Fals... |
from app import app, db, q
from app.forms import RegistrationForm, WoosyListingFromEtsyForm
import flask
import json
from copy import copy
from flask import flash, redirect, render_template, jsonify, Markup
from urllib.parse import urlparse
from urllib.parse import urljoin
from flask import request, url_for
from flask_... |
#!/usr/bin/env python
from ngram_helpers import *
from word_counts import *
def readchats(file_name):
with open(file_name, 'r') as f:
for line in f:
yield line.strip()
if __name__ == '__main__':
facc = {}
cacc = {}
chatlines = [c for c in readchats('out.txt')][:100]
for line in chatlines:
sta... |
# -*- coding:utf-8 -*-
'''
@author: leisun
@contact: leisun98@gmail.com
@file: cb_SUNY_parser.py
@time: 2018/7/13 上午8:01
'''
from utils.connection import *
import requests
import time
from db.operateSql import People
from db.operateSql import connect_db
# book = xlwt.Workbook(encoding="UTF-8")
# sheet = book.... |
# IMPORTS
import random
# Jeu à deux joueurs, à tour de rôle
# Joueur 1 utilise "X", Joueur 2 utilise "O"
# AI - Anticiper les coups (plus tard !)
# détecter QUAND la partie se termine -> QUI à gagné (X,O) ou égalité
# VARIABLES "GLOBALES"
LINES = 3
# DÉFINITIONS DE FONCTIONS
def show_board(a_board: list):
"... |
from sqlalchemy.orm import Session
import json
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from . import models, schemas
###Define the get_detroit function for returning all of the data
def get_detroit(db: Session):
###Query the... |
#!/usr/bin/python
from BeautifulSoup import BeautifulSoup
import urllib
import simplejson
import re, sys, os
import psycopg2 as pg
import psycopg2.extras
BTICOIN_CONNECTIONS="bitcoin_connections"
LOGINS="logins"
EXECUTIONS="executions"
MISC_CONN="misc_connections"
HTTP_CON="http_conn"
URLS_REQUESTED="urls_requested"
O... |
import math
def poisson_prob(lda):
# return math.pow(lda, k) * math.pow(math.e, -lda) / math.factorial(k)
return 1 - math.pow(math.e, -lda)
def bernouilli(lda):
return float(lda) |
import pygame
import pygame.image
import pygame.display
import numpy
import setting
import apple
import box
import move
import hud
fps_clock = pygame.time.Clock()
def main():
pygame.init()
apple.apple_list.load_apple()
box.box_play.load_box()
logo = pygame.image.load("img/fruit_apple.png")
bg = ... |
# -*- coding:utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
import numpy as np
def dubois_1995(ks : float,
lambda_cm : float,
pq : str,
theta_deg : float,
epsilon_real : float,):
"""
Computes radar backscatter based on the empirical model from Dubois et al., 1995
Note: there were multiple typos in th... |
import os
from django.shortcuts import render, redirect
from django.conf import settings
def testQrCodePage(request):
return render(request, 'qrCodeApp/test.html') |
from django.urls.conf import path
from track import views
app_name = 'track'
urlpatterns = [
path('', views.start, name='start'),
path('save/', views.save, name='save'),
# path('', views.IndexView.as_view(), name='index'),
# path('specs/<int:pk>/', views.DetailView.as_view(), name='detail'),
# path(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.