content stringlengths 5 1.05M |
|---|
import os
MOTHERBRAIN_PATH = os.path.dirname(__file__)
|
import hashlib;
class sha256generator(object):
"""Generate a sha1 value to validate mozu events or form posts"""
def getHash(sharedSecret, date, body):
hashString = sharedSecret+sharedSecret;
m = hashlib.sha256(hashString.encode());
m.digest();
hash1 = m.hexdigest();
hashString = hash1+date+body;
m = h... |
import sys
from shared import timeit
import numpy as np
import mdtraj as md
from mdtraj.geometry.dihedral import indices_phi, indices_psi
def ramachandran(traj):
md.compute_phi(traj)
md.compute_psi(traj)
pdbfile = sys.argv[1]
repeats = int(sys.argv[2])
traj = md.load(pdbfile)
print(timeit(ramachandran, t... |
import FWCore.ParameterSet.Config as cms
RecoVertexFEVT = cms.PSet(
outputCommands = cms.untracked.vstring('keep *_offlinePrimaryVertices__*',
'keep *_offlinePrimaryVerticesWithBS_*_*',
'keep *_offlinePrimaryVerticesFromCosmicTracks_*_*',
'keep *_nuclearInteractionMaker_*_*',
'kee... |
"""Provide a class for ODT invisibly tagged chapters and scenes export.
Copyright (c) 2021 Peter Triesberger
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
from pywriter.odt.odt_file import OdtFile
clas... |
import psycopg2
import databasePasswordDecryption
import json
DATABASE_NAME = "postgres"
DATABASE_USER = "swapstreamAdmin"
DATABASE_HOST = "swapstreamdb.ck8zwecvtffz.us-east-2.rds.amazonaws.com"
DATABASE_PORT = "5432"
DATABASE_PASSWORD = databasePasswordDecryption.getDBPassword()
def get_test_data():
conn = None... |
from compas.geometry import Point
from compas.geometry import Polyline, Bezier
from compas.geometry import NurbsCurve
from compas.artists import Artist
from compas.colors import Color
points = [Point(0, 0, 0), Point(1, 2, 0), Point(2, -2, 0), Point(3, 0, 0)]
bezier = Bezier(points)
points = [Point(4, 0, 0), Point(5,... |
from setuptools import setup
from os import path
from io import open
this_directory = path.abspath(path.dirname(__file__))
def readme():
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
return f.read()
with open(path.join(this_directory, 'requirements.txt'),
encoding='u... |
from itertools import combinations
def part1(numbers):
combos = [pair for pair in combinations(numbers, 2)
if sum(pair) == 2020]
return combos[0][0] * combos[0][1]
def part2(numbers):
combined_sum = 2020
combos = [pair for pair in combinations(numbers, 3)
if sum(pair) == ... |
"""
Django settings for ryu project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import... |
import base64
from hashlib import pbkdf2_hmac, sha256
import hmac
import json
from secrets import token_bytes
from pathlib import Path
from src.models import KeyList, Master
# hash and check
def check_master(password, keylist):
hashed = hash_master(
password, keylist.master.salt, keylist.master.iter_coun... |
import os
def CSharpSolutionFile( path, **kwargs ):
#remove '.ycm_extra_conf.py' and 'extra-conf-abs' from filename
location=os.path.dirname( __file__ )
location=os.path.dirname( location )
return os.path.join( location, 'testy2.sln' )
|
"""
retrieve the satelite weather forcast map for a location
convert that from png to jpg
display this on the M5 display in a window
uses :
- weather underground API
- free API Key, needs registration
- filestack
- initial free plan (500 conversions)
"""
i... |
from ..utils import Object
class SendPassportAuthorizationForm(Object):
"""
Sends a Telegram Passport authorization form, effectively sharing data with the service. This method must be called after getPassportAuthorizationFormAvailableElements if some previously available elements need to be used
Attri... |
import discord
import re
import uuid
from threading import Thread
import asyncio
import socket
import os
import config
import downloader
downloadDir = "tmp/"
mentionPattern = "\s*((<@&?\d{18}>)|@(everyone|here))\s*"
client = discord.Client()
def formatMsg(content):
return re.sub(mentionPattern, "", content).st... |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed =... |
# -*- coding: utf-8 -*-
# Base imports
import os
import kivy
import gettext
import json
from os import listdir
from os.path import isfile, join
# Import library for html generate
from yattag import Doc
from yattag import indent
# Import for working with DB when new test was made
import psycopg2
# This will be used ... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... |
from __future__ import annotations
import typing
import attr
import enum
class TlFileLineType(enum.Enum):
'''
describes the two types of lines, either
a comment or a line defining a type or function
'''
COMMENT = "comment"
DEFINITION = "definition"
class TlClassTypeEnum(enum.Enum):
''' d... |
import logging
import requests
import boto3
from random import random
from django.core.management.base import BaseCommand
from django.db.models import Q
from botocore.exceptions import ClientError
from user.models import User
from django.conf import settings
from PIL import Image
from io import BytesIO
SMALL_IMAGE_SI... |
#! /usr/bin/env python
class DataStore():
"""An agnostic data storage unit that holds and queries all data points, by all indices.
"""
def __init__(self,Training_Set_Lines,Test_Set_Lines,Patient_Status_Lines):
"""Assumes no headers are included. Assumes column 0 is the gene names for both tra... |
"""
IRC check.
"""
def select_irc_target(direction='forward'):
"""
This method is to inform job checker which targets
to check, which need meet one requirement:
1. status is job_launched or job_running
Returns a list of targe
"""
qm_collection = db['qm_calculate_center']
... |
"""
Iniciar la aplicacion.
"""
import random
from dog_api import DogAPI
from podio import Podio
def main():
"""
Iniciar la aplicacion.
"""
ancho = 72
print('=' * ancho)
print('Jagua Maravichu'.center(ancho))
print('=' * ancho)
razas = []
opciones = []
api = DogAPI()
podi... |
from collections import defaultdict
from typing import Iterator
from ..types.openapi import OpenApiSchema, OpenApiSpec
from ..types.python import (
PythonClassAttribute,
PythonEnumAttribute,
PythonImport,
)
from .constants import MODELS_PACKAGE
from .formatter import enum2attribute, property2attribute
from... |
# Generated by Django 3.1.5 on 2021-02-10 18:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20210211_0226'),
]
operations = [
migrations.AlterField(
model_name='snapshot',
name='verified',
... |
# Problem:
# Write a program that introduces a product name and checks whether it is a fruit or a vegetable.
# -> Fruit are: banana, apple, kiwi, cherry, lemon and grapes
# -> Vegetables are: tomato, cucumber, pepper and carrot
# -> All others are unknown ;
# Display "fruit", "vegetable" or "unknown" according to t... |
import pandas as pd
from pandas import json_normalize
import json
import os
from pathlib import Path
path = "./json_files"
file_list = os.listdir(path)
print ("file_list: {}".format(file_list))
path_fixed = "./json_files/csv_files"
for file in file_list:
if file.endswith(".json"):
print ("f... |
#!/usr/bin/env python3
from texttable import Texttable
from .fetch_coins import fetch_crypto_data
from .args_parser import parse_args
def generate_table(headers, data):
t = Texttable(max_width=0)
headersRow = []
for h in headers:
headersRow.append(h['title'])
dataRow = []
for index, item ... |
"""
Copyright 2014 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 by applicable law or ... |
import tensorflow as tf
from pplp.core import losses
from pplp.core import orientation_encoder
from pplp.core.pplp_fc_layers import ops
KEY_CLASSIFICATION_LOSS = 'classification_loss'
KEY_REGRESSION_LOSS = 'regression_loss'
KEY_PPLP_LOSS = 'pplp_loss'
KEY_OFFSET_LOSS_NORM = 'offset_loss_norm'
KEY_ANG_LOSS_NORM = 'ang... |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore,QtGui
from pineboolib import decorators
from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor
from pineboolib.utils import DefFun
from pineboolib.fllegacy.FLRelationMetaData import FLRelationMetaData
from pineboolib.fllegacy.FLFieldMetaData import FLFieldMetaData
fro... |
import simplejson as json
from glob import glob
from bs4util.spantable import TableFrame, frame_keys, describe_frame
from collections import OrderedDict
from itertools import chain
from copy import deepcopy
import logging
log = logging.getLogger()
def show_log():
print("log = %s" % log)
log.info("info! %s" % ... |
"""
Views for the Jetpack application
"""
import commonware.log
import os
import shutil
import codecs
import tempfile
import urllib2
import time
import waffle
from contextlib import closing
from simplejson import JSONDecodeError
from statsd import statsd
from zipfile import ZipFile, ZIP_DEFLATED
from django.contrib i... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... |
from threading import Thread
import time
from hallo.events import EventMessage
def test_threads_simple(hallo_getter):
test_hallo = hallo_getter({"hallo_control"})
test_hallo.function_dispatcher.dispatch(
EventMessage(test_hallo.test_server, None, test_hallo.test_user, "active threads")
)
dat... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
# ----------------------------------------------------------------------------
# If you submit this package back to Spack ... |
import xml.etree.ElementTree as ET
from ltr.judgments import _judgments_by_qid
def fold_whoopsies(whoopsies1, whoopsies2):
""" Merge whoopsies2 into whoopsies1
sorted on query, then descending on magnitude
of the whoops (so biggest whoops for queries come first)"""
whoopsies1.extend(whoopsies2)... |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-ServiceTriggerPerfEventProvider
GUID : 6545939f-3398-411a-88b7-6a8914b8cec7
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp... |
"""
Script for extracting an analyzing a GraphMCF with a cleft
(v3) 24.03.16 - Modification for not to compute filaments
Input: - Density map tomogram
- Segmentation tomogram
Output: - GraphMCF
"""
__author__ = 'Antonio Martinez-Sanchez'
# ################ Package import
import time
... |
"""Top-level package for cookiecutter_example."""
__author__ = """Max Nikoi van der Merwe"""
__email__ = 'maxnvdm@yahoo.com'
__version__ = '0.1.0'
|
from typing import List
from aiomailserver.core.service import MailService
from aiomailserver.auth.base import MailUser
class BaseMailbox(MailService):
async def store_message(self, user: MailUser, message):
raise NotImplementedError()
async def folders(self, user: MailUser) -> List[str]:
ret... |
from django.db import models
from django_countries.fields import CountryField
from django.utils import timezone
# Create your models here.
class Group(models.Model):
''' A group is an organisation that receives an invitation. '''
def __str__(self):
return self.display_name
pnr = models.CharField... |
from trsbuts.UTSConnection import UTSConnection
class SearchProductDefinitionService:
def __init__(self):
self._servicepath = "/UTS/rest/tibbiCihaz"
# ÜRÜN SORGULAMA SERVİSİ
# Birincil ürün numarası ve üretici ÜTS firma numarası ile ürün bilgilerini sorgulamasını sağlayan servistir.
def uruns... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
#packages
import pandas as pd
import os.path
import csv
# In[6]:
#Saving tweet data in csv
def saveTweetData(topicName, tweetId, createdAt, text, retweetCount, likeCount, isQuote, place, geo, hashtags,
userMentions, source, sourceUrl, userId, user... |
# Copyright (c) 2016 Intel, 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 ... |
alist = []
def app(env, start_response):
'''
print 'foo!'
print type(start_response)
print dir(start_response)
c = start_response.__class__
try:
c()
except:
import traceback; traceback.print_exc()
try:
class x(c): pass
except:
import traceback; traceb... |
import numpy as np
import tensorflow as tf
from .Layer import Layer
from .initializers import zeros
class RNN(Layer):
def __init__(self, output_dim,
input_dim=None,
initializer='glorot_uniform',
recurrent_initializer='orthogonal',
recurrent_activ... |
from pathlib import Path
import pytest
from tabler import HTML, Table
from ...test_tools import TablerTestTools
class TestHTML:
def test_open(self):
with pytest.raises(NotImplementedError):
Table("", table_type=HTML())
def test_write(self, tmpdir):
table = TablerTestTools.basic... |
"""
Tests for the package structure and import names.
Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
"""
import unittest
import Pyro4
import Pyro4.constants
import Pyro4.core
import Pyro4.errors
import Pyro4.naming
import Pyro4.nsc
import Pyro4.socketutil
import Pyro4.t... |
"""Parser for future statements"""
from . import ast
from .visitor import ASTVisitor
def is_future(stmt):
"""Return true if statement is a well-formed future statement"""
if not isinstance(stmt, ast.From):
return 0
if stmt.modname == "__future__":
return 1
else:
return 0
cla... |
import numpy as np
import unittest
from feudal_networks.policies.feudal_batch_processor import FeudalBatchProcessor, FeudalBatch
from feudal_networks.algos.policy_optimizer import Batch
class TestFeudalBatchProcessor(unittest.TestCase):
def test_simple_c_1(self):
# simple case ignoring the fact that the... |
"""Summarise hazard data
Get OD data and process it
Author: Raghav Pant
Date: April 20, 2018
"""
import configparser
import csv
import glob
import os
import fiona
import fiona.crs
import rasterio
from sqlalchemy import create_engine
import subprocess as sp
import psycopg2
import osgeo.ogr as ogr
import pandas as p... |
'''
Generate stylesheet for stimuli version 2
'''
def get_interval_style(index: int, duration: int, delay: int) -> str:
'''
Get style for a particular interval (element class)
:params:
- index (int): interval number
- duration (int): time taken to play the animation, in milliseconds
- delay (in... |
import signal
import sys
import time
import pyupm_grove as grove
import pyupm_ttp223 as ttp223
import pyupm_i2clcd as lcd
import dweepy
# create the button object using GPIO pin 0
button = grove.GroveButton(8)
# create the TTP223 touch sensor object using GPIO pin 0
touch = ttp223.TTP223(7)
# Initialize Jhd1313m1 ... |
import numpy as np
# from scipy.integrate import trapz
import numba
from tqdm import trange
# ==========================================
@numba.jit(nopython=True)
def phi(x, pe):
'''
Effective potential energy
Input:
x = numpy array of positions, [-0.5, 0.5]
pe = scalar, peclet number
Return... |
# -*- encoding: utf-8 -*-
"""
@version: 0.01
@author: Tony Qiu
@contact: tony.qiu@liulishuo.com
@file: las.py
@time: 2018/04/19 午後5:56
"""
def max_ascend_len(ary):
maxlist = []
if len(ary) == 0:
return 0
start = 0
end = 0
for idx in range(1, len(ary)):
if ary[idx] > ary[idx-1]:
... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import sys
sys.path.append("..")
import torch
from options.opts import get_training_arguments
from cvnets import get_model
from loss_fn import build_loss_fn
from utils.tensor_utils import create_rand_tensor
from... |
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
txt = "The price is {:.2f} dollars"
print(txt.format(price))
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49
... |
from os import mkdir
from os.path import join, exists
import cv2
def extract_frames(video_filename):
"""Extract video frames
Keyword Arguments:
@param video_filename: The input video file name
@type video_filename: str
@returns: The video frames
@rtype: list
"""
# Initializing the v... |
import os
from functools import partial
from typing import List, Tuple
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
from jax.experimental import optix
from rljax.algorithm.sac import SAC
from rljax.network import ContinuousQFunction, SACDecoder, SACEncoder, SACLinear, StateDependentGaussia... |
import discord
import os
import random
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
groupList = []
groupSize = 0
grpBool = False
now = datetime.now()
current_time = now.strftime("[ %d.%m.%y | %H:%M:%S ] ")
class MyClient(discord.Client):
async d... |
import random
from operator import add
MIN_DELTA = 1e-4
class GridMDP(object):
def __init__(self, metadata):
self.width = metadata['width']
self.height = metadata['height']
self.initial_value = metadata['initial_value']
self.obstacles = metadata['obstacles']
self.living_cos... |
import os
import uuid
import logging
import requests
from werkzeug.routing import Rule
from flask import Flask, request, Response, redirect, url_for, render_template
logging.basicConfig(level=logging.DEBUG)
SUBPATH = os.getenv("SUBPATH", "/proxy")
SPLUNK_USERNAME = "andrewb"
SPLUNK_PASSWORD = "PkbdAGSdCJa8"
SPLUNK_... |
from pypadre.core.model.computation.run import Run
from pypadre.pod.backend.i_padre_backend import IPadreBackend
from pypadre.pod.repository.local.file.generic.i_file_repository import File
from pypadre.pod.repository.local.file.run_repository import RunFileRepository
from pypadre.pod.repository.serializer.serialiser i... |
import discord
from discord import message
from discord.ext import commands
from datetime import datetime
class admins(commands.Cog):
def __init__(self, client):
self.client = client
#Comando de Ban
@commands.command(name="ban", help="Bane alguém do seu servidor. ```R>ban <ID ou ... |
from __future__ import division
from __future__ import print_function
import numpy as np
from data import preproc as pp
import pandas as pd
import os
class Sample:
"single sample from the dataset"
def __init__(self, gtText, filePath):
self.gtText = gtText
self.filePath = filePa... |
# -*- coding: utf-8 -*-
r"""
Navier-Stokes equations for incompressible fluid flow in 2D.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}
+ \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{u}) \cdot \ul{v}
- \int_{\Omega} p\ \nabla \cdot \ul{v}
= 0
\;, ... |
# Copyright (C) 2019-2021, François-Guillaume Fernandez.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import pytest
import torch
from torch.nn import Linear
from torch.nn.functional import cross_entrop... |
"""Eager mode TF policy built using build_tf_policy().
It supports both traced and non-traced eager execution modes."""
import functools
import logging
import numpy as np
from ray.util.debug import log_once
from ray.rllib.evaluation.episode import _flatten_action
from ray.rllib.models.catalog import ModelCatalog
fro... |
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Checks if a tuple exists in a list of tuples. #
# Program ... |
# -*- coding: utf-8 -*-
"""
# @file name : RMB_data_augmentation.py
# @author : Jianhua Ma
# @date : 20210330
# @brief : Based on lec06/train_lenet.py, add the data augmentation.
"""
import os
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torchvisi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __coconut_hash__ = 0xc33625b4
# Compiled with Coconut version 1.2.3-post_dev1 [Colonel]
# Coconut Header: --------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, division
import sys as _coconut... |
from django import forms
class DownloadForm(forms.Form):
post = forms.CharField()
|
# -*- coding: utf-8 -*-
import os
import re
from datetime import datetime
import scrapy
from pymongo import MongoClient
from sinastock.items import NewsItem
class SinastockSpiderSpider(scrapy.Spider):
name = 'sinastock_spider'
allowed_domains = ['finance.sina.com.cn']
mongo = MongoClient(
host=os... |
# Authors: Michael Hawes, Tony Tran
# Date: 12 Novemebr 2016
# Hack RPI
import jinja2
import html2text
import requests
import queue
import re
import nltk
import json
from collections import Counter
from bs4 import BeautifulSoup
from google import search
from stop_words import get_stop_words
from stemming.porter2 import... |
from django.shortcuts import render
from django.shortcuts import HttpResponse
from .forms import FoodFitnessForm
from django.contrib.auth.models import User
# function to test with
def index(request):
return HttpResponse("You made it.")
# function to create new user
def createUser(request):
form = FoodFitness... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('news', '0005_informationpage'),
('wagtailimages', '0006_add_verbose_names... |
#
# @lc app=leetcode.cn id=120 lang=python3
#
# [120] 三角形最小路径和
#
from typing import List
class Solution:
# 一行一行向下叠加(也可向上叠加)
# 将累加的路径和填入下一行中
def minimumTotal(self, triangle: List[List[int]]) -> int:
try:
row_count = len(triangle)
if row_count == 0:
return 0
... |
from datetime import datetime
def get_departures():
departures = []
with open('../data/departure-data.txt') as f:
for line in f.read().splitlines():
departure = get_departure(line)
if departure:
departures.append(departure)
return departures
def get_departur... |
import prepare_settings
from unittest import TestCase, main
from django_documents.documents import Model
from django_documents import related
from django_documents import fields
from django_documents.serializer import JsonSerializer, JsonUnSerializer
"""
class Category(Model):
... |
import pywikibot
from pywikibot.data import api
import wikiSQL as SQL
import re
'''
Items
'''
def getItem(site, wdItem, token):
request = api.Request(site=site,
action='wbgetentities',
format='json',
ids=wdItem)
return request.submit()
d... |
from django import forms
from django.contrib import admin, messages
from django.utils import timezone
from tinymce.widgets import TinyMCE
from .models import Article
# Register your models here.
class ArticleForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE())
class ArticleAdmin(admin.ModelAdmin... |
#!/usr/bin/env python3
from argparse import ArgumentParser
import logging
import bitcoin
import json
import codecs
import urllib3
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
http = urllib3.PoolManager()
def get_hash_by_height(height):
url = 'https://blockchain.info/block-height/'+str(he... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
# trainToyOTflow.py
# training driver for the two-dimensional toy problems
import argparse
import os
import time
import datetime
import torch.optim as optim
import numpy as np
import math
import lib.toy_data as toy_data
import lib.utils as utils
from lib.utils import count_parameters
from src.plotter import plot4
from ... |
#Crie um programa que leia quanto de dinheiro a pessoa tem na sua carteira e mostra quantos dólares ela pode comprar. Considerando que o dólar custa 3,27 Reais
name = str(input("Qual é o seu nome? "))
carteira = float(input("Quanto dinheiro na carteira você tem, {}? ".format(name)))
carteira_convertida = float(carteir... |
import time
import json
from elasticsearch import Elasticsearch, helpers
from controllers.logging import log_info, log_error
class EsClient(Elasticsearch):
# Class Attributes
default_settings = json.load(open('config/settings.json'))
es_host = default_settings.get('services')['elasticsearch']['host']
... |
import os
import json
import copy
import shutil
import numpy as np
from collections import defaultdict
dir_save = "./demo/combined_rec_vector_segments"
preds_root = "./demo/all_rec_vector_segments"
if os.path.isdir(dir_save):
shutil.rmtree(dir_save)
os.makedirs(dir_save)
fname_base_to_fnames_map = defaultdict(... |
import pytest_spec.basic as basic
from pytest_mock import mocker
def test_loop_define(mocker):
mocker.patch.object(basic, "loop_define", side_effect=[2, 3, 0])
mocker.patch.object(basic, "hello")
basic.loop_sample_define()
basic.loop_define.assert_any_call(1)
assert len(basic.loop_define.mock_call... |
from django.test import TestCase
from tools.testing import TestData
from logistics.models import StockWish
from internalise.models import InternaliseDocument, InternaliseLine, DataValidityError
from stock.models import Stock
from stock.stocklabel import OrderLabel
from order.models import OrderLine
class InternaliseT... |
# 3.uzdevums
my_name = str(input('Enter sentence '))
words = my_name.split()
rev_list = [word[::-1] for word in words]
rev_string=" ".join(rev_list)
result=rev_string.capitalize()
print(result)
print(" ".join([w[::-1] for w in my_name.split()]).capitalize()) |
from .optimize_ar import Optimize_Acquisition_Rate
|
from setuptools import find_packages, setup
setup(
name='tmc_summarizer',
packages=find_packages(),
version='0.1.1',
description='Process raw TMC data into more functional formats',
author='Aaron Fraint, AICP',
entry_points="""
[console_scripts]
tmc=tmc_summarizer.cli:main
"... |
from time import sleep
#https://www.youtube.com/watch?v=hWrFEU_605g&ab_channel=LinusTechTips
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread, QObject, pyqtSignal, QRunnable, QThreadPool
from pytube import YouTube
class Runnable(QRunnable):
def __init__(self, n):
su... |
from cloudant import Cloudant
from flask import Flask, render_template, request, jsonify
import atexit
import cf_deployment_tracker
import os
import json
# Emit Bluemix deployment event
cf_deployment_tracker.track()
app = Flask(__name__)
db_name = 'mydb'
client = None
db = None
# On Bluemix, get the port number fro... |
import logging
import curses
from core.config import theme
logger = logging.getLogger('colors')
colors = {}
def init():
color_definitions = theme['colors']
for i, color_name in enumerate(color_definitions.keys()):
foreground, background = color_definitions[color_name]
curses.init_pair(i + 1... |
#
# BitBake Graphical GTK User Interface
#
# Copyright (C) 2011-2012 Intel Corporation
#
# Authored by Joshua Lock <josh@linux.intel.com>
# Authored by Dongxiao Xu <dongxiao.xu@intel.com>
# Authored by Shane Wang <shane.wang@intel.com>
#
# This program is free software; you can redistribute it and/or modify
# it unde... |
import os
import unittest
import sqlalchemy as sa
conn = None
creds = None
engine = None
def parse_connection_string(connstr):
creds = {}
s = None
if connstr.startswith('postgresql://'):
creds['use_sqlite'] = False
s = connstr[len('postgresql://'):]
elif connstr.startswith('sqlite://... |
#!/usr/bin/env python
from matplotlib import cm
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.style
import matplotlib as mpl
import sys
#seaborn-colorblind, ggplot, fivethirtyeight, bmh seaborn-pastel are decent
#mpl.style.use('bmh')
mpl.style.use('bmh')
print('plotting...')
if(len(sys.argv) < 2... |
import tensorflow as tf
from data_types.training_result import TrainingResult
from data_types.training_set import TrainingSet
from timeseries.build import compile_and_fit
from timeseries.multi_output.residual_wrapper import ResidualWrapper
from timeseries.window_generator import WindowGenerator
def evaluate_residual... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.