content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from typing import List, Union, Tuple
from timeit import default_timer as timer
import datetime
import time
import pyroglyph
TIME_START = timer()
def duration_tuple(secs: Union[int, float]) -> Tuple[int, int, int, int]:
secs = int(secs)
days, secs = divmod(secs, 86400)
hours, sec... |
from axil_cdc import AxilCDC
from axilite2bft import AxiLite2Bft
from bft import Bft
from interface_wrapper import InterfaceWrapper
from litex.soc.interconnect.axi import AXILiteInterface, AXIStreamInterface
from litex.soc.interconnect.stream import (ClockDomainCrossing, Converter,
... |
"""
test effect of connecting standard streams to text and binary mode files
same holds true for socket.makefile: print requires text mode, but text
mode precludes unbuffered mode -- use -u or sys.stdout.flush() calls
"""
import sys
def reader(F):
tmp, sys.stdin = sys.stdin, F
line = input()
print(line)
... |
#!/usr/bin/env python
import pygame
import time
from datetime import datetime
import pygame.camera
from pygame.locals import *
import cv2
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
RED = ( 255, 0, 0)
DEVICE = '/dev/video0'
SIZE = (640, 480)
FILENAME = 'capture.png'
# This ... |
import os
default_events_service = 'http://127.0.0.1:5000'
EVENTS_SERVICE_URL = os.environ.get('EVENTS_SERVICE_URL',
default_events_service)
EVENTS_API_KEY = os.environ.get('EVENTS_API_KEY', "424242")
TEMPLATES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__f... |
#
# Copyright (c) 2017-2021 NVIDIA CORPORATION. All rights reserved.
# This file is part of the WebDataset library.
# See the LICENSE file for licensing terms (BSD-style).
#
"""Train PyTorch models directly from POSIX tar archive.
Code works locally or over HTTP connections.
"""
import os
import random
import sys
i... |
#
# render animAction frames in 8-directions
# before run, remember set target-obj.Rotation.z == 0 !!!
#
import bpy
import os
from random import randint
#-------------------- out path ---------------------------
pathDir_out = "C:\\Users\\Administrator\\Desktop\\OUT\\"
pathDirs= [ "1_Left", "2_LeftTop", ... |
_base_ = ['./draw_bboxes.py']
attribution_method = dict(type='ExtremalPerturbation', areas=[0.1], attr_normalizer=dict(type='IdentityNormalizer'))
|
from copy import deepcopy
class RecommendedName():
def __init__(self):
self.fullName = None
self.ecNumber = None
class Protein():
def __init__(self):
self.recommendedName = RecommendedName()
self.alternativeName = []
class UniProtKBEntry():
def __init__(self):
... |
# Torch agents (in alphabetical order)
from .a2c import A2CAgent
from .dqn import DQNAgent
from .reinforce import REINFORCEAgent
|
# 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 t... |
from django.test import TestCase
class TestSimpleComponent(TestCase):
def test_basic_sum(self):
assert 1+1 == 2
|
from django.core.mail import send_mail
from celery import shared_task
from pictures.service.recognize import recognize_multi
from pictures.service.config import mongo_db
from hellofamilyclub.utils.websocket import send_message
@shared_task()
def send_recognize_mail(subject, message, from_email, recipient_list, fail... |
# !/usr/bin/python
# Written against python 2.7
# Matasano Problem 13
#
# Created by 404 on 15/11/26.
#
# Copyright (c) 2015 404. All rights reserved.
from base64 import b64decode
from Crypto.Cipher import AES
from os import urandom
KEY = urandom(16)
def parse(input_string):
list_of_pairs = input_string.sp... |
# -*- coding: utf-8 -*-
'''
@author: kebo
@contact: kebo0912@outlook.com
@version: 1.0
@file: multi_head_attention.py
@time: 2021/05/15 23:26:07
这一行开始写关于本文件的说明与解释
'''
import tensorflow as tf
class MultiHeadAttention(tf.keras.layers.Layer):
def __init__(self, num_heads, hidden_dim, **kwargs):
super()._... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator 2.3.3... |
import os
import shutil
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Command remove assets files"""
help = "Remove assets files"
def remove_dist_dir(self):
try:
shutil.rmtree(settings.DIST_DIR)
self.s... |
from django.test import TestCase
from data.lando import LandoJob, LandoConfig
from data.models import LandoConnection, Workflow, WorkflowVersion, Job, JobFileStageGroup, \
DDSJobInputFile, DDSEndpoint, DDSUserCredential, ShareGroup, JobFlavor, VMProject, JobSettings, CloudSettingsOpenStack
from data.tests_models im... |
# some imports
from flask_mysqldb import MySQL
from shutil import rmtree
import os
from python.token_check.check import *
delete_product_bluprint = Blueprint('delete_product_bluprint', __name__)
mysql = MySQL(app)
# add new product page
@delete_product_bluprint.route('/api/delete_product', methods=['DELETE'])
@toke... |
import random
import regex as re
import libcst
from lampion.transformers.addneutral import AddNeutralElementTransformer, _reduce_brackets
# Floats
def test_addneutral_for_float_should_add_plus_0():
example_cst = libcst.parse_module("def some(): \n\ta = 0.5 \n\treturn a")
random.seed(1996)
transformer ... |
'''randomize um valor interio de 0 à 10 entre com um valor do jogador
para adivinhar até acertar mostrando no final quantos palpites foram necessários'''
from random import randint
computador = randint(0, 10)
print('{:-^40}'.format('JOGO ADVINHAÇÂO'))
acerto = palpites = 0
while acerto == 0:
jogador = int(input('Sua v... |
""" file: reproject.py (spatial)
author: Jess Robertson, @jesserobertson
date: Sunday, 27 January 2019
description: Reprojection algorithms for shapely geometries
"""
from functools import partial
from shapely.geometry import Polygon, MultiPolygon, MultiLineString, \
LineString, LinearRing, Po... |
from flask import Flask
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logging.basicConfig(format='%(asctime)s||%(levelname)-8s||%(message)s||%(name)s',
filename='/tmp/flask.log',
filemode='w',
)
J... |
# Dummy links to test functionality
dummy_link_1 = "https://www.youtube.com/watch?v=C0DPdy98e4c"
dummy_link_2 = "https://www.youtube.com/watch?v=ucZl6vQ_8Uo"
dummy_link_3 = "https://www.youtube.com/watch?v=krDWc30PAGg"
|
import unittest
from typing import NewType, Dict
import hypothesis.strategies as st
from grapl_analyzerlib.grapl_client import GraphClient
from grapl_analyzerlib.nodes.process import ProcessView
from grapl_analyzerlib.node_types import PropType
from grapl_analyzerlib.test_utils.dgraph_utils import random_key_for_test... |
# Copyright 2009 Luc Saffre
# License: BSD (see file COPYING for details)
"""
Based on http://www.djangosnippets.org/snippets/102/
Added by LS:
20090621
- template can now also be a list or tuple of filenames
- renamed parameter "type" to "outtype"
- support for templates containing non-ascii data
"""
from __futur... |
from klein import Klein
app = Klein()
@app.route("/user/<username>")
def pg_user(request, username):
return f"Hi {username}!"
app.run("localhost", 8080)
|
# Copyright (c) 2020 PaddlePaddle 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 appli... |
#!/usr/bin/env python2
# bin/read_yaml.py <filename> <key>..
import sys, json, yaml, os
filename = sys.argv[1]
with open(filename) as f:
values = yaml.load(f)
def get_from_dict(values, keys):
if len(keys) > 1:
return get_from_dict(values[keys[0]], keys[1:])
else:
return values[keys[0]]
... |
from dataclasses import dataclass
from typing import Optional
import enum
class RegionAttr(enum.Enum):
READONLY = enum.auto()
READWRITE = enum.auto()
EXECUTABLE = enum.auto()
ALLOCATABLE = enum.auto()
INITIALIZED = enum.auto()
def to_string(self) -> str:
if self == RegionAttr.READONLY... |
# Refazer o 61, para que o usuário possa pedir
# mais X termos depois do final dos 10 termos padrão
# até que o usuário digite 0 para sair .
print('Digite um primeiro termo e uma razão:')
a0 = float(input('>>>\t'))
r = float(input('>>>\t'))
current = a0
nSteps = 10
totalSteps = 10
while nSteps != 0:
i = 0
whil... |
import pytest
from os import path
import pandas as pd
import networkx as nx
import qiime2
from q2_SCNIC._transformer import _1, _2, _3, _4, _5, _6
@pytest.fixture()
def data_path():
return path.join(path.realpath(path.dirname(__file__)), 'data')
@pytest.fixture()
def correls_spar(data_path):
correls = pd.re... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Cisco Systems, Inc. and others. 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... |
"""degvabank URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
import os
import re
import sys
import fileinput
def read_test_dir(outputdir):
allfiles= []
resultfiles = []
try:
for (dirpath, dirnames, filenames) in os.walk(outputdir):
allfiles.extend(filenames)
for file in allfiles:
filename, file_extension = os.path.splitext(fi... |
from linkedlist_helper import *
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if not head:
return head
fast = head
while fast is not None and n > 1:
fast = fast.next
n -= 1
# illegal input, n is larger than size... |
# extensions
from flask import render_template
# local modules
from app import db
from app.errors import bp
@bp.app_errorhandler(404)
def not_found_error(error):
return render_template('errors/404.html'), 404
@bp.app_errorhandler(500)
def internal_error(error):
db.session.rollback() # resets the session
r... |
# -*- coding: utf-8 -*-
"""
LxcAttach command test module.
:copyright: Nokia Networks
:author: I_MOLER_DEV
:contact: I_MOLER_DEV@internal.nsn.com
:maintainer: I_MOLER_DEV
:contact: I_MOLER_DEV@internal.nsn.com
"""
__author__ = 'Agnieszka Bylica, Marcin Usielski'
__copyright__ = 'Copyright (C) 2019-2020, Nokia'
__emai... |
from .lorentz_lorenz import LorentzLorenz
from chemml.published.RI.input_files import load_hyperparameters, load_small_organic_data, load_small_organic_data_10k, load_model
__all__= [
'LorentzLorenz',
'load_hyperparameters',
'load_small_organic_data',
'load_small_organic_data_10k',
'load_model'
... |
"""
Takes a gff3 file and a file with
list of IDs (one per line).
Output is a gff3 file containing
only features with ID or Parent
from the IDs list.
"""
from __future__ import print_function
import sys
in_gff = sys.argv[1]
in_list = sys.argv[2]
out_gff = sys.argv[3]
with open(in_list) as f:
ids_list = set([l.stri... |
# Generated by Django 2.2.2 on 2019-08-22 10:48
from django.db import migrations, models
import django.db.models.deletion
import {{cookiecutter.project_slug}}.apps.user.managers
class Migration(migrations.Migration):
dependencies = [
('user', '0002_actiontoken_temporarytoken'),
]
operations = [
... |
from pylab import *
import postgkyl
style.use('postgkyl.mplstyle')
def calcMeanSpect(fn, lo, up):
d = postgkyl.GData("%s_00%d.bp" % (fn, lo))
s = d.getValues()
g = d.getGrid()
dx = g[0][1]-g[0][0]
gc = linspace(g[0][0]+0.5*dx, g[0][-1]-0.5*dx, g[0].shape[0]-1)
for i in range(lo+1, up+1):
... |
import os
from dotenv import load_dotenv
from starlette.datastructures import CommaSeparatedStrings, Secret
from databases import DatabaseURL
API_V1_STR = "/api"
JWT_TOKEN_PREFIX = "Token"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # one week
load_dotenv(".env")
MAX_CONNECTIONS_COUNT = int(os.g... |
# coding:utf-8
'''
This code fragment from DaLao @lotuc
'''
import contextlib
import imp
import os
import sys
import uuid
from functools import partial
import urllib3
import requests
# from webdog.lib.log import get_logger
# LOG = get_logger()
def load_file_as_module(dir_or_file, filename=None):
"""加载plugin 为p... |
import json
class T5CopyVocabulary(object):
def __init__(self, vocab_path, tokenizer, sep=','):
with open(vocab_path) as out:
self.d_to_w_group = {}
self.i_to_w = {}
self.w_to_i = {}
self.i_to_cls = {}
self.id_to_category = {}
self.wo... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
import os
from typing import Union
# ReadTheDocs
from sims... |
###############################################################
# Program: package.py
# Description: Package the Addon
# Author: jamedina@gmail.com
# -------------------------------------------------------------
# Required Modules:
###############################################################
# ---------------------... |
import json
from pprint import pprint
from operator import itemgetter
import csv
writer = open('Sentiment\\All_Sentiments.txt','w')
#with open('Sentiment\\All_Sentiments.csv','w') as SentimentFile:
#writer = csv.writer(SentimentFile)
for i in range(123):
print(i+1)
data = json.load(open('Sentiment\\'+str(i+1)+'.j... |
"""
A bridge between an xml document (formerly a jinja2 template) and a python object
"""
from jinja2 import Environment, FileSystemLoader
from xmlcommandparser.parser import XmlCommandParser
from xmlcommandparser.helpers import tojson, sanitize_filepath, MACRO
class LoaderWithMacro(FileSystemLoader):
"""Custom ji... |
# Your Token for Telegram Bot, get it on Bot Father
TOKEN = "TOKEN"
# Start message
start_msg = "Benvenuto nel Bot relativo allo stand del MakerSpace di Fabriano! Digita il comando /info per ottenere "\
"maggiori informazioni riguardanti questa realtà o digita il comando /timeline per visualizzare un'... |
"""
Constants and utility functions used for LRR event handling.
.. moduleauthor:: Scott Petersen <scott@nutech.com>
"""
def get_event_description(event_type, event_code):
"""
Retrieves the human-readable description of an LRR event.
:param event_type: Base LRR event type. Use LRR_EVENT_TYPE.*
:type... |
from queue import PriorityQueue
import asar_search_algorithm.Pi_Cfg as CONFIG
import base64
import logging
with open('search.log', 'w'):
pass
logging.basicConfig(filename='search.log', level=logging.INFO)
log = logging.getLogger(__name__)
TERRAIN_HEIGHT = CONFIG.TERRAIN_HEIGHT # number of tiles down the side
TE... |
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from pytorch_model import *
from pytorch_clean import *
from sklearn.metrics import classification_report
from torch.optim import optimizer
from transformers import AutoModel, AutoTokenizer
from vncorenlp import VnCoreNLP
from vncorenlp.vncorenlp... |
# © 2020 지성. all rights reserved.
# <llllllllll@kakao.com>
# MIT License
import argparse
import h5py
from dlgo import rl
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--learning-agent', required=True)
parser.add_argument('--agent-out', required=True)
parser.add_argument('--lr',... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class Contacts(models.Model):
_name = 'calendar.contacts'
_description = 'Calendar Contacts'
user_id = fields.Many2one('res.users', 'Me', required=True, default=lambda ... |
# Copyright 2020 Raytheon BBN Technologies
#
# 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
# Drivers for controling the DS Instruments pures... |
from .retinanet import *
from .backbones import ResNet18FPN, ResNet34FPN, ResNet50FPN, ResNet101FPN |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from threading import Thread
from typing import Dict, Optional, Union
# fast api imports
import uvicorn as uvicorn
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors... |
#! /usr/bin/python3
def main():
global image,w,h,smoothed,gradient,M,M1
default_path="img1.jpg"
path=""
image=None
while True:
path=input("Path to the image: (default to "+default_path+") ")
if path is "":
path=default_path
try:
image=Image.open(pat... |
import torch
import torch.nn as nn
from torch import Tensor
from ...ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules
from ...utils import common_utils
from .roi_head_template import RoIHeadTemplate
class PyramidHead(RoIHeadTemplate):
def __init__(self, input_channels, model_cfg, ... |
from app.game.game_exceptions import GameNotFound
from app.question.question_exceptions import (
InvalidLanguageCode,
InvalidLimit,
QuestionExistsException,
)
add_question_data = [
(
{"content": "this is a question?", "round": "pair", "game_name": "quibly"},
{
"question_id":... |
#!/usr/bin/env python
"""Tests for the ``api_views`` module in the ``jwql`` web application.
Authors
-------
- Matthew Bourque
Use
---
These tests can be run via the command line (omit the -s to
suppress verbose output to stdout):
::
pytest -s test_api_views.py
"""
import json
import pyt... |
#!/usr/bin/env python
import schemabase
from appionlib import appiondata, apDisplay
class SchemaUpdate17311(schemabase.SchemaUpdate):
'''
This will add a 'phaseflipped' field to appion.ApRefineStackData to allow querys on old refine stacks
In general, eman and xmipp stacks are phaseflipped and Frealign stacks are n... |
print(len(input().split(','))) |
from django.contrib import admin
from django.template.defaultfilters import linebreaksbr
from django.utils.translation import ugettext_lazy as _
from talkback.models import FeedbackItem
class ResolvedListFilter(admin.SimpleListFilter):
"""
Filter for FeedbackAdmin, which filters on the `resolved` field,
... |
# -*- coding: utf-8 -*-
#
# @autor: Ramón Invarato Menéndez
# @version 1.0
from datetime import datetime
from pathlib import Path
from sorted_in_disk import sorted_in_disk
"""
Execute this script to see sorted result in console
iterator_with_data_to_sort: any iterable with data to sort
tmp_dir: temporal folder to so... |
from Colors import bcolors
def Banner(version,modulesNum):
print ' _______ '
print '< SMOD >'
print ' ------- '
print ' \ ^__^'
print ' \ (xx)\_______'
print ' (__)\\ )\\/\\'
print ' U ||----w |'
print ' || ||'
print ' '*10 + '--=' + bcolors.... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/proto/monitoring/v3/metric_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from goo... |
import os
import math
from collections import OrderedDict, namedtuple
from fractions import Fraction
from dataclasses import dataclass, field
from typing import List, Tuple, Dict, Union
from ast import literal_eval
from kaiko.utils import biparsers as bp
from . import beatmaps
def Context(beat, length, **update):
... |
import matplotlib.pyplot as plt
from read_simulation import results as sr
from read_measured import results as mr
import numpy as np
rows = 4
cols = 4
OFFSET = 6
fig = plt.figure(figsize=(30, 20))
gs = fig.add_gridspec(rows, cols, hspace=0.4, wspace=0.2)
axs = gs.subplots()
for i in range(OFFSET, rows + OFFSET):
... |
from PySide2 import QtWidgets, QtGui, QtCore
from skinning.gui import icon
__all__ = [
"SearchWidget"
]
CLOSE_ICON = icon.get_icon_file_path("nodeGrapherClose.png")
class SearchWidget(QtWidgets.QWidget):
"""
The search widget is a line edit that will trigger both a text changed and
a return presse... |
from TwitchCubieBot import CubieBot
from TwitchCubieBot import View
from TwitchCubieBot import MessageSource
import json, time, logging, os
from Log import Log
Log(__file__)
from Settings import Settings
from App import App
class AppView(View):
def __init__(self, bot):
super().__init__(bot)
def ... |
lst = ["A", "B", "C"]
item = {"key": 100}
#dictionary name key
item2 = {"name": "McKenzi"}
print(item["key"])
print(item2["name"])
# dictionay can contain multiple pairs of info
hero = {"name": "Iron Man", "nationality": "United States"}
item3 = {"bag": ["laptop", "usb", "food"], "pocket": [5.00,1.00,"gum"],
"reddi... |
from coopihczoo.eye.envs import ChenEyePointingTask
from coopihczoo.eye.users import ChenEye
from coopihczoo.eye.utils import eccentric_noise
from coopihc.bundle.Bundle import Bundle
from coopihc.space.State import State
import numpy
import matplotlib.pyplot as plt
fitts_W = 4e-2
fitts_D = 0.8
ocular_std = 0.09
swa... |
import pandas as pd
from collections import defaultdict
import sqlalchemy
from pickle import Unpickler
class IndiceJaccardUU():
usersPerItem = defaultdict(set)
itemsPerUser = defaultdict(set)
itemNames = {}
def __init__(self):
# Se cargan los conjuntos
pickled_file = open('jaccard_item_item.pickle', '... |
"""This file is part of DeepLens which is released under MIT License and
is copyrighted by the University of Chicago. This project is developed by
the database group (chidata).
background.py defines some background-foreground separation routines that
are useful for processing fixed camera videos.
"""
import cv2
impor... |
"""
https://edabit.com/challenge/e69u7eJYnSz3kiLAn
Hash Juggling
Create a function that:
Creates a sha256 hash from a list of strings.
Sort the hash string, alphas first digits second, maintaining the original order of alphas and digits (e.g. "7a2f7fdf31a4b" would be sorted as "affdfab727314").
Returns a new sha256 h... |
from cli import base
from core import data, container
import shutil
import os
import sys
import tarfile
from docker import Client
from urllib.request import urlretrieve
from cement.core.controller import CementBaseController, expose
class InstallController(CementBaseController):
class Meta:
label = 'instal... |
import torch
from torch.autograd import Variable
class State(object):
__slots__ = ['batch_first', 'hidden', 'inputs', 'outputs', 'context',
'attention', 'attention_score', 'mask']
def __init__(self, hidden=None, inputs=None, outputs=None, context=None, attention=None,
attent... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
get_ipython().run_line_magic('matplotlib', 'inline')
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime, date, time
from sklearn.metrics import r2_score
# In[ ]:
# data pre-processing
data = pd.read... |
#!/usr/bin/python3
# # -*- coding:utf-8 -*-
# # Author: daning
import os
user = os.environ.get('mysqlusername') or 'root'
passwd = os.environ.get('mysqlpasswd') or 'passwd'
SECRET_KEY = 'haskha214kNk**#Yilnf#$%*!&'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{}:{}@127.0.0.1:3306/dbname'.format(user, passwd)
SQ... |
from typing import Protocol
from .ISharepointGraphRequest import ISharepointGraphRequest
from .ISharepointSite import ISharepointSite
class ISharepointGraphClient(Protocol):
def sites(self, relative_site_uri:str) -> ISharepointSite:
""""""
def add_request(self, request:ISharepointGraphRequest):
... |
#!/usr/bin/env python
"""
Setup script for part_builder python library
custom module for use with our synth.py file
run the following to uninstall:
pip3 uninstall part_builder
"""
from setuptools import setup
with open('README.md') as readme:
long_desc = readme.read()
setup(
name='boot-syn... |
import typing
import os
import base64
import dataclasses
import uuid
import json
import cbor2
import binascii
import hashlib
import cryptography.hazmat.primitives.asymmetric.rsa
import cryptography.hazmat.primitives.asymmetric.ec
import cryptography.exceptions
from . import data, types, errors, utils, metadata, attest... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-22 19:53
from __future__ import unicode_literals
import dashboard.mixins.dashboard_mixin
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = Tru... |
def abreArquivo(nome):
try:
a = open(nome, 'rt')
a.close()
except:
print('arquivo nao encontrado')
else:
print('Arquivo encontrado com sucesso =)')
def primeiralista(nome):
a = open(nome, 'rt')
lista1 = []
for linha in a:
lista1.append(linha.replace... |
from .sum import sum
from ramda.private.asserts import assert_equal
def sum_test():
assert_equal(sum([1, 2, 3]), 6)
|
def display_inference_result(inference_result_df, customer_id, inference_type):
inference_result_df = inference_result_df.rename(
columns={"user_id": "CustomerID", "item_id": "StockCode", "score": "Recommendation Score"}
)
inference_result_df["StockCode"] = inference_result_df.StockCode.astype(str)
... |
class Solution:
def exclusiveTime(self, n, logs):
res, stack = [0] * n, []
for log in logs:
log = log.split(":")
if log[1] == "start":
stack.append([int(log[2]), 0])
else:
start = stack.pop()
time = int(log[2]) - sta... |
#!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... |
# Copyright 2013-2022 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)
from spack.package import *
class PyAsyncTimeout(PythonPackage):
"""asyncio-compatible timeout context manager."""
... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
import sims4.commands
from typing import Tuple, Any, Callab... |
"""Advent of Code Day 5 - Doesn't He Have Intern-Elves For This?"""
import re
with open('inputs/day_05.txt') as f:
strings = f.readlines()
# Answer One Regexes
naughty_regex = re.compile(r'ab|cd|pq|xy')
vowel_regex = re.compile(r'([aeiou].*){3,}')
double_regex = re.compile(r'(.)\1')
# Answer Two Regexes
repeated... |
"""
[Weekly #25] Escape the trolls
https://www.reddit.com/r/dailyprogrammer/comments/4vrb8n/weekly_25_escape_the_trolls/
#Description
We are going to create a mini game.
I'm going post updates with ideas, if you guys have them.
The goal of the game is to escape a maze and not get eaten by the trolls.
#Phases of the ... |
from django.apps import AppConfig
class AlquileresConfig(AppConfig):
name = 'alquileres'
|
import logging
import re
import typing
from asyncio import iscoroutinefunction
from ..dispatcher import data_
from ..dispatcher.rule import BaseRule
from ..dispatcher.rule import NamedRule
from vk import types
from vk.constants import JSON_LIBRARY
from vk.types.message import Action
logger = logging.getLogger(__name_... |
from pyomo.environ import Block, Expression, units as pyunits
from watertap3.utils import financials
from watertap3.wt_units.wt_unit import WT3UnitProcess
## REFERENCE:
module_name = 'surface_discharge'
basis_year = 2020
tpec_or_tic = 'TPEC'
class UnitProcess(WT3UnitProcess):
def fixed_cap(self, unit_params):
... |
#!/usr/bin/python3
"""Script to clean object files in GCC/Gollvm build dir libgo subdirs.
"""
import getopt
import os
import sys
import script_utils as u
# Dry run mode
flag_dryrun = False
# Echo commands mode
flag_echo = False
def docmd(cmd):
"""Execute a command."""
if flag_echo or flag_dryrun:
sys.std... |
import os
from magiclog import log
import py.path
from sh import chmod, Command, cp, mkdir
import uritools
from ..decorators import schemes
from ..err import Err
from .core import DiskLocal, onepath, oneurl, SourceURL, twopaths
from .tar import Tar
class File(DiskLocal, SourceURL):
"""Local files and directorie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.