content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
from __future__ import division
import serial
import struct
import time
"""Pololu driver module for motor controllers using pyserial
This module handles the lower level logic of writing to a pololu motor
controller using python.
Serial reference: https://www.pololu.com/docs/0J44/6.2.1
Get Variable... |
class Node():
def __init__(self, data):
self.left = None
self.right = None
self.data = data
class BinarySearchTree():
def __init__(self):
self.root = None
def insert(self, data):
new_node = Node(data)
if self.root == None:
self.root = new_node
return
else:
current_node = self.root
while T... |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... |
"""
Generated API Documentation for Server API using server_doc_gen.py."""
doc = {
"@context": {
"ApiDocumentation": "hydra:ApiDocumentation",
"description": "hydra:description",
"domain": {
"@id": "rdfs:domain",
"@type": "@id"
},
"expects": {
... |
# imports
import django
from elasticsearch import Elasticsearch
import json
import os
import re
import sys
# import Row from pyspark
try:
from pyspark.sql import Row
from pyspark.sql.types import StringType, IntegerType
from pyspark.sql.functions import udf, lit
except:
pass
# pylint: disable=wrong-im... |
import rosbag
import numpy as np
import scipy.io
import os
bag = rosbag.Bag(os.path.expanduser("~/Desktop/2017-10-06-18-21-06.bag"))
topics = bag.get_type_and_topic_info()[1].keys()
types = []
for i in range(0,len(bag.get_type_and_topic_info()[1].values())):
types.append(bag.get_type_and_topic_info()[1].values()[i... |
#!/usr/bin/env python3
import os
import csv
import cv2
import sys
import time
import yaml
import pygame
import numpy as np
# Custom libraries
from keyboard import keyboard
from fonts import lato
import colors
with open("config.yaml") as file:
dictionary = yaml.load(file)
usr = dictionary["usr"]
app = dictionary[... |
import numpy as np
import rospy
from geometry_msgs.msg import Vector3Stamped
class Vector3Handler(object):
"""
Handler for ROS topics of type: geometry_msgs/Vector3Stamped
Args:
topic_name: Name of ROS topic to be subscribed
buffer_size: Variable buffer, depend on frame rate of topic, defa... |
"""
Cache yo.
"""
import datetime
from . import exceptions
class NotSet(object):
pass
class Enable(object):
def __init__(self, cache, new_value):
self.cache = cache
self.new_value = new_value
self.previous_value = self.cache.enabled
def __enter__(self):
self.cache.enable... |
'''
Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, mostrando
os 10 primeiros termos da progressão usando a estrutura while.
'''
# fórmula do termo geral: an = a1 + (n-1) * r
p = int(input('Primeiro termo: '))
r = int(input('Razão: '))
# cálculo do último termo
u = p + (10 - 1) * r
n = p
while n ... |
import json
from pathlib import Path
import pytest
from bs4 import BeautifulSoup
from app.api.business.respirator import RespiratorExtractor
from app.model.respirator import ApprovalCertificate, Respirator
def mocked_extract_approval_certificate(self: RespiratorExtractor, ac_real: int, ac_candidate: str, _: str = N... |
from django.forms.formsets import BaseFormSet, formset_factory
from django.utils.translation import ugettext_lazy as _, ugettext
from dockit.forms.forms import DocumentForm, documentform_factory
class BaseDocumentFormSet(BaseFormSet):
"""
A ``FormSet`` for editing a queryset and/or adding new objects to it.
... |
import typing as tp
from loguru import logger
from robonomicsinterface import Account, Datalog
from typed_getenv import getenv
DATALOG_ENABLED: bool = getenv("ROBONOMICS_ENABLE_DATALOG", var_type=bool, default=False)
ROBONOMICS_ACCOUNT: tp.Optional[Account] = None
DATALOG_CLIENT: tp.Optional[Datalog] = None
if DATAL... |
# -*- coding: utf-8 -*-
"""
Script to generate a csv with summary files from a roi
timeseries csv file. Output format will be:
date,year,doy,image_count,midday_filename,midday_r,midday_g,midday_b,midday_gcc,midday_rcc,
r_mean,r_std,g_mean,g_std,b_mean,b_std,gcc_mean,gcc_std,gcc_50,gcc_75,gcc_90,rcc_mean,
rcc_std,rcc... |
#Config file for kaltweet#
#API Keys found at developer.twitter.com
#Must create new app to generate keys
#App and website url can be called whatever you want
consumer_key1 = 'ENTER API KEY'
consumer_secret1 = 'ENTER SECRET KEY'
access_token1 = 'ENTER ACCESS TOKEN KEY'
access_token_secret1 = 'ENTER ACCESS ... |
##################################################################################################################
# Web Scrape information on author and affiliations for Nature
#
# Scrape the website: https://www.nature.com/nature/volumes
# Check first the website: https://www.nature.com/robot... |
import datetime
import re
from html.parser import HTMLParser
_STATUS_SEARCHING = 0
_STATUS_LINE_FOUND = 1
_STATUS_TITTLE_FOUND = 2
_STATUS_URL_FOUND = 3
_STATUS_IMG_FOUND = 4
DATE_STR_PATTERN = re.compile(r"^\d{8}$", flags=0)
class PageAdviser(object):
def __init__(self, config):
self.dates: [datetime.d... |
# DON'T EDIT! This file is generated by MetaTools/buildTableList.py.
def _moduleFinderHint():
"""Dummy function to let modulefinder know what tables may be
dynamically imported. Generated by MetaTools/buildTableList.py.
"""
import B_A_S_E_
import C_F_F_
import D_S_I_G_
import G_D_E_F_
import G_M_A_P_
import G_... |
import re
import numpy as np
def read_file_to_list(filename):
"""Read file to map"""
rows = []
file = open(filename, "r")
for line in file:
m = re.search(r'^mask\s+=\s+([01X]+)$', line)
if m:
rows.append({"type" : "mask" , "mask": m.group(1)})
... |
#!/usr/bin/env python3
# Copyright (c) 2021 Elliot Powell
# SPDX-License-Identifier: MIT
import sys, os, re, datetime, getopt
# REGEX FILE EXTENSTIONS FOR /*...*/ FORMATED COPYRIGHT
headerOneFiles = ["\.c", "\.h", "\.keymap", "\.dts", "\.overlay", "\.dtsi"]
# REGEX STRINGS FOR ANY FILES WHICH SHOULD BE IGNORED FROM CH... |
from django.urls import path
from . import views
app_name = "students"
urlpatterns = [
path("", views.StudentIndexView.as_view(), name="index"),
path("create/", views.StudentCreateView.as_view(), name="create"),
path(
"<uuid:uuid>/courses/<uuid:course_uuid>/",
views.StudentCourseView.as_vi... |
# -*- encoding=utf8 -*-
__author__ = "pscly"
from airtest.core.api import *
auto_setup(__file__) |
#!/usr/bin/env python
if __name__ == '__main__':
from argparse import ArgumentParser
from io import StringIO
import sys
arg_parser = ArgumentParser(description='I/O test')
arg_parser.add_argument('-o', dest='output', help='output file')
options = arg_parser.parse_args()
str_io = StringIO()
... |
import cv2
import os
import numpy as np
from PIL import Image
def main():
average_img_3()
def average_img_3():
# Alternative method using numpy mean function
dim_x = 280
dim_y = 100
pos_x = 100
pos_y = 130
samples_per_file = 500
path = '..\\data\\balanced\\session-{}.npy'
file... |
# Generated by Django 3.2.7 on 2021-09-26 00:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("forms", "0004_alter_hackathonapplicant_status"),
]
operations = [
migrations.AddField(
model_name="formresponse",
na... |
# coding: utf-8
#
# Copyright (C) Zoltán Máté 2021.
# Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
from django.db import models
class Wallet(models.Model):
currency = models.CharField(max_length=3, help_text='three-letter acronym, such as “BTC” or “ETH”')
addre... |
import logging
from typing import Any, Optional
import matplotlib.pyplot as plt
import seaborn as sns
from bender.evaluator.interface import Evaluator
from bender.exporter.exporter import Exporter
from bender.split_strategy.split_strategy import TrainingDataSet
from bender.trained_model.interface import TrainedModel,... |
from omnilingual import LanguageCode
from aether.ontology.geography import Location
class Cawa(Location):
def __init__(self):
super().__init__()
self.orthography.update(
{LanguageCode.Xian: "Ka’•ua", LanguageCode.English: "Cáwa"}
)
|
#
# Marvelous Morse Mentor
# Copyright 2021-2022 Leandro Motta Barros
# Licensed under the Apache License 2.0 (see the LICENSE file for details)
#
import time
import state_manager
import menu_state
class WelcomeState(state_manager.State):
def on_enter(self, hw):
hw.display("Marvelous Morse",
... |
# -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limi... |
# Copyright (c) 2021 Xiaomi Corporation (authors: Wei Kang)
import k2
import torch
def get_best_matching_stats(keys: k2.Nbest, queries: k2.Nbest,
max_order: int) -> torch.Tensor:
'''Get best matching stats on query positions.
Args:
keys:
The nbest after doing seco... |
# date: 2021.03.30
# author: Han Tran htran@know-center.at
DATA_ID = 61
PORT_ADDRESS = '8061'
PORT_ADDRESS_CLASSIFIER = '8062' |
#!/usr/bin/env python
#coding:utf-8
# 检测球的相关接口
import math
import rospy
import geometry_msgs.msg as g_msgs
from robot_state_pkg import get_robot_position
from basketball_msgs.srv import robot_rotate, visionDate
from robot_state_class.start_position import *
class find_ball(object):
def __init__(self, Type):
... |
#!/usr/bin/env python3
# testZMQ.py
import unittest
import zmq
# from upax.ftlog import LogEntry
CONTEXT = zmq.Context.instance()
class TestZMQ(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_constructor(self):
# XXX STUB
pass
if __name__ ... |
try:
import subprocess
except:
print "You have to use Python 2.4 or higher"
sys.exit(0)
from optparse import OptionParser
import os
files = []
directories = []
SEbase = 'srm://lcgse02.phy.bris.ac.uk:8444/srm/managerv2?SFN=/cms/'
gpfsBase = '/gpfs_phys/storm/cms/'
def delete(file):
output = subproces... |
DRB1_1130_9 = {0: {'A': -999.0, 'E': -999.0, 'D': -999.0, 'G': -999.0, 'F': -0.004754, 'I': -0.99525, 'H': -999.0, 'K': -999.0, 'M': -0.99525, 'L': -0.99525, 'N': -999.0, 'Q': -999.0, 'P': -999.0, 'S': -999.0, 'R': -999.0, 'T': -999.0, 'W': -0.004754, 'V': -0.99525, 'Y': -0.004754}, 1: {'A': 0.0, 'E': 0.1, 'D': -1.3, '... |
#
# 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
# "License"); you may not... |
import pytest
from .example import app
@pytest.fixture
def test_app():
return app.test_client()
|
#!/usr/bin/env python
# coding: utf-8
# In[7]:
import pandas as pd
import urllib
import numpy as np
import json
from tqdm.autonotebook import tqdm
import re
# %matplotlib inline
tqdm.pandas()
import jellyfish#88942
import dask.dataframe as dd
from dask.multiprocessing import get
from dask.diagnostics impor... |
# coding:utf-8
"""
Function decoration for pacing calls to an old man
This module provides function decorators which can be used to wrap a
function such that it will be paced to given rate.
For examples and full documentation see the README at
https://github.com/mkeshav/pace-maker
"""
from ._decorator import pace_me
_... |
import streamlit as st
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
def make_plots(player, data, season):
"""
Make plots to display for a given player based on their position.
Inputs:
- Player: Player name
- data: Dataframe
- seas... |
#!/usr/bin/env python
# -*- Coding: UTF-8 -*-
# ---------------------------------------------------------------------------
# Open Asset Import Library (ASSIMP)
# ---------------------------------------------------------------------------
#
# Copyright (c) 2006-2020, ASSIMP Development Team
#
# All rights res... |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import math
import random
from typing import Dict, List, Optional, Set, Tuple
from shared.operand import (OperandType, EnumOperandType,
ImmOper... |
from django.shortcuts import render
from django.shortcuts import get_list_or_404
from django.http import Http404
from news.models import Article
from projects.models import ProjectArticle
from banners.models import Banner
def home(request):
try:
latest_news = Article.objects.filter(display=True).order_by('-pub_date... |
from hero import views
from django.conf.urls import url
app_name = 'hero'
urlpatterns = [
url(r'^$', views.HeroView.as_view(), name='home'),
]
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 10:39:26 2019
cvrptw_plot
带容量约束和时间窗的vrp问题
@author: Administrator
"""
import os
import numpy as np
from matplotlib import pyplot as plt
from collections import namedtuple
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums... |
from .Conversion import Conversion
|
# Ow = [x, y, z], quat = [w, x, y, z]
def Ow_quat_wxyz___to___Rt(Ow, quat_wxyz):
R = transforms3d.quaternions.quat2mat(quat_wxyz)
t = -R.dot(Ow)
return [R, t]
def from_R_t(R, t):
return np.hstack((np.copy(R), np.copy(t).reshape(3, 1)))
def from_T(T):
R = T[:3, :3]
t = T[:, 3]
return [R, ... |
# coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class LayerNorm(nn.Module):
#ref: https://github.com/pytorch/pytorch/issues/1959
# :https://arxiv.org/pdf/1607.06450.pdf
def __init__(... |
"""A threading based handler.
The :class:`SequentialThreadingHandler` is intended for regular Python
environments that use threads.
.. warning::
Do not use :class:`SequentialThreadingHandler` with applications
using asynchronous event loops (like gevent). Use the
:class:`~kazoo.handlers.gevent.Sequential... |
"""
GPU Stats Monitor
====================
Monitor and logs GPU stats during training.
"""
import os
import shutil
import subprocess
import time
from pytorch_lightning.callbacks.base import Callback
from pytorch_lightning.utilities import rank_zero_only, rank_zero_warn
from pytorch_lightning.utilities.exceptions im... |
# -*- coding: utf-8 -*-
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
import numpy as np
import cv2
from agentspace import Agent, Space
class NavigatorAgent(Agent):
def __init__(self,gpsName,goalName,headingName,forwardName,turnName):
self.gpsName = gpsName
self.goalName = goalName
self.headingName = headingName
self.forwardName = forwardName
... |
"""Set count server_defaults
Revision ID: d000d000beef
Revises: deadbeefcafe
Create Date: 2018-09-22 13:55:16.188388
"""
# revision identifiers, used by Alembic.
revision = 'd000d000beef'
down_revision = 'deadbeefcafe'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('songs', 'favo... |
DATA_ID = 40678
|
#Condicionais
tempo = int(input('Quantos anos tem o seu carro? '))
if tempo<=3:
print('Carro novo')
else:
print('Carro velho')
print('FIM') #Todo comando que não estiver indentado vai ser executado sempre. |
# Generated by Django 3.1.6 on 2021-02-15 11:57
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0003_auto_20210122_1426'),
]
operations ... |
import enum
import sys
from dataclasses import is_dataclass
from typing import Callable, Any, Optional, Dict
import types
from pedantic.env_var_logic import is_enabled
from pedantic.constants import TYPE_VAR_ATTR_NAME, TYPE_VAR_METHOD_NAME, F, C
from pedantic.type_checking_logic.check_generic_classes import check_inst... |
import unittest, time, sys
sys.path.extend(['.','..','../..','py'])
import h2o
import time
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
def test_Cloud(self):
ports_per_node = 2
for trials in range(0,5):
for tryNodes in range(3,6):
... |
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from app.dependencies import get_db
from app.models.tenant import Tenant
async def get_tenant(tenant_id: int = None, db_session: Session = Depends(get_db)):
"""Get the tenant id from the url."""
if not tenant_id:
... |
#!/usr/bin/python
from parsers.baseparser import BaseParser
from parsers.common.items import parse_item
class ItemParser(BaseParser):
"""Parser for item data.
Expects 'items' and 'dict' in the raw data.
Optional data include either 'recipe_f' or 'recipe_m'.
"""
required_data = ['items', 'dict'... |
"""
Parse command line and store result in params
Model : DMM
"""
import argparse,copy
from collections import OrderedDict
p = argparse.ArgumentParser(description="Arguments for variational autoencoder")
parser = argparse.ArgumentParser()
parser.add_argument('-dset','--dataset', action='store',default = 'mm', help='Dat... |
"""
This configuration file contains data required for testing
scientific pygaps functions on real or model data.
In this file there are:
- references to sample isotherm files
- pre-calculated values for each isotherm on various
characterisation tests.
Explanation of parameters:
'bet_area': ... |
#
# 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 "License"); you may not us... |
from sklearn.model_selection import KFold
import numpy as np
from datasets import load_dataset
import datasets
kf = KFold(n_splits=5)
dataset = load_dataset('csv', data_files={'train': '/home/lbony/projects/albatros/scripts/data/train.csv'})
indices: np.ndarray = np.arange(len(dataset['train']))
for fold_id, (train_... |
# Internal Library
import aepp
from dataclasses import dataclass
from aepp import connector
from copy import deepcopy
from typing import Union
import time
import logging
json_extend = [
{
"op": "replace",
"path": "/meta:intendedToExtend",
"value": [
"https://ns.adobe.com/xdm/con... |
#!/usr/bin/env python3
#coding: utf-8
import sys
import numpy as np
from optparse import OptionParser
from antlr4 import *
from GCodeLexer import GCodeLexer
from GCodeParser import GCodeParser
from GCodeInterpreter import GCodeInterpreter
class GCodeScad(GCodeInterpreter):
def __init__(self, toolScad):
G... |
import unittest
from calendar import timegm
from datetime import datetime, timedelta
import time
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from django import get_version
from django.test import TestCase
from django.test.utils import override_sett... |
"""
Afterglow Core: image cropping job schemas
"""
from typing import List as TList
from marshmallow.fields import Integer, List, Nested
from .... import AfterglowSchema, Boolean
from ..job import JobSchema, JobResultSchema
__all__ = ['CroppingSettingsSchema', 'CroppingJobResultSchema',
'CroppingJobSche... |
"""
Problem statement:
Write a function that returns the string "something" joined with a space " " and the given argument a.
Examples
give_me_something("is better than nothing") ➞ "something is better than nothing"
give_me_something("Bob Jane") ➞ "something Bob Jane"
give_me_something("something") ➞ "something some... |
# Generated by Django 3.0.11 on 2020-11-29 02:23
from django.db import migrations, models
import src.apps.runs.models.run
class Migration(migrations.Migration):
dependencies = [
('runs', '0007_auto_20200920_2128'),
]
operations = [
migrations.AddField(
model_name='run',
... |
import re
import os
# import shutil
import sys
import tempfile
import hashlib
# import sys
import json
from operator import itemgetter
from bdscan import classComponent, classNugetComponent, classNpmComponent, classMavenComponent, classPyPiComponent, \
classConanComponent, classCargoComponent, classHexComponent, c... |
from os import path
def get_logfile_name():
dir_name = path.dirname(path.abspath(__file__))
log_dir = path.normpath(path.join(dir_name, '../../../'))
return path.join(log_dir, 'debug.log')
class Logger:
PRODUCTION = False
handler = open(get_logfile_name(), "a")
@classmethod
def log(cl... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.viewIndex, name='forumindex'),
path('create/', views.createPost.as_view(), name='createpost'),
path('<int:pk>/', views.viewPost, name='viewpost'),
]
|
import json
leap_dir = "/home/stolet/Documents/MSC/leap"
def create_sitealgo_config():
config = {"ip_port": "",
"connector_ip_port": "",
"csv_true": "0",
"site_id": 0,
"secure_with_tls": "y",
"cert": "../certs/sitealgo0.crt",
"ke... |
import pytest
import os
import pickle
from darwinian_shift.statistics import *
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
@pytest.fixture
def exp_values():
np.random.seed(0)
return np.random.random(1000)
@pytest.fixture
def mut_rates():
np.random.seed(1)
return np.random.random(1000)
@py... |
players = input()
team_a_players = players.split('0')
team_b_players = players.split('1')
if len(max(team_a_players, key = len)) >= 7 or len(max(team_b_players, key = len)) >= 7:
print('YES')
else:
print('NO') |
"""Download datasets and train transformer-based models."""
import argparse
import logging
import batching
import datasets
def main():
"""The main entry point to transformers-sota."""
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_directory',
default='/tmp/translation_... |
#
# shikiml
#
# Copyright (c) 2017 Yuichiro MORIGUCHI
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
#
from docutils import nodes
from docutils.parsers.rst import Directive
import subprocess
class shiki(nodes.General, nodes.Element):
pass
class ShikiDirective(Di... |
class hello:
message = "test_message"
def __init__(self):
pass
def set(self, message):
self.message = message
def show(self):
print(self.message)
def test_hello_world():
h = hello()
h.set("test")
assert h.message == "test"
|
class Solution:
def longestConsecutive(self, nums) -> int:
if len(nums) == 0:
return 0
max_long = 0
helper_set = set(nums)
for i in helper_set:
if i - 1 not in helper_set:
cur_num = i
cur_long = 1
while cur_num +... |
# Extra information about nyuv2
import numpy as np
# Number of classes:
n_classes = 13
# set 0 to first label
# weights=np.ones(1, n_classes)
weights=np.append([0.0], np.ones(n_classes))
colors=[
[ 0, 0, 0],
[ 0, 0, 255],
[232, 88, 47],
[ 0, 217, 0],
[148, 0, 240],
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** Thomas Larsson
**Copyright(c):** MakeHuman Team 2001-2017
**Licensing:** ... |
# https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/time-calculator
# https://replit.com/@harmonify/time-calculator#time_calculator.py
def add_time(base: str, addon: str, dow: str = "") -> str:
DAYS_OF_WEEK = ("Monday", "Tuesday", "Wednesday",
... |
from typing import List
# 232. 用栈实现队列, Easy
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.elements = []
# self.size = 0
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
... |
products = []
class Product:
def __init__(
self, productName,
price, category,
stockBalance
):
self.productName = productName
self.price = price
self.id = len(products)+1
self.category = category
self.stockBalance = stockBalance
def save(sel... |
# coding: utf-8
import os
import sys
import click
from .dygod.core import DyGod
CONTEXT_SETTINGS = dict(
help_option_names=['-h', '--help'],
ignore_unknown_options=True,
)
DEFAULT_HOST = 'https://www.dygod.net'
def show_movie(movies, pager=None):
for name, movie in movies.iteritems():
if page... |
from pathlib import Path
import json
import pandas as pd
from typing import Callable, Dict
import tweepy
from tweepy import OAuthHandler
class TweetScraper(object):
# adapted from https://github.com/smacawi/twitter-scraper
def __init__(self, auth_dict: dict, on_status_fn: Callable[[Dict], Dict]):
sel... |
import logging
import ast
from cStringIO import StringIO
from teuthology import misc
from .config import config
log = logging.getLogger(__name__)
'''
Map 'generic' package name to 'flavor-specific' package name.
If entry is None, either the package isn't known here, or
it's known but should not be installed on remo... |
"""
Namespaces associated with the moves api work.
"""
from rdflib.namespace import Namespace
# This provides a means of creating urns for each of the segments. The urn should be generated by providing the
# startTime value for the segment to the end of this namespace.
MOVES_SEGMENT = Namespace('urn:moves-app.com:seg... |
# coding=utf-8
# Copyright 2019 The Google AI Language Team Authors.
#
# 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 ... |
# -*- coding: utf-8 -*-
#
# LICENCE MIT
#
# DESCRIPTION Callgraph helpers for ast nodes.
#
# AUTHOR Michal Bukovsky <michal.bukovsky@trilogic.cz>
#
class VariablesScope(object):
def __init__(self, ctx):
self.ctx, self.var_names = ctx, ctx.var_names.copy()
def __enter__(self):
re... |
'''
Created on 24.09.2015
@author: michi
'''
from mathx import formula
from mathx import ast
from copy import deepcopy
import os
import logging
log = logging.getLogger('mathx.gleichungslöser')
#handler = logging.StreamHandler(open('/dev/stderr', 'w'))
#formatter = logging.Formatter( '%(asctime)s %(levelname)s %(mes... |
from osgeo import osr
WGS84_WKT = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,' \
'298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0]' \
',AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY[' \
'"EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHO... |
#Um programa com duas fonções, uma sorteia números e outra soma os valores pares sorteados e os aloca em listas
from time import sleep
from random import randint
def sort(valor):
lista = []
for c in range(0, valor):
lista.append(randint(0, 10))
print(f'Sorteando {valor} valores da lista: ', end=''... |
import logging
from pathlib import Path
import keras
import numpy as np
from keras.callbacks import LearningRateScheduler
from keras.layers import Dense, Activation
from keras.models import Sequential
from examples.gridworld.exceptions.CannotCloneWeightsOfDifferentModelException import \
CannotCloneWeightsOfDiffe... |
import os
import unittest
from bot.debug_helpers import calling_function, last_record
class HelpersTest(unittest.TestCase):
"""Tests for `debug helpers folder`."""
def test_calling_function(self):
self.fake_calling_function()
self.assertTrue('fake_calling_function' in last_record.get_record()... |
import gym
import torch.nn as nn
from .resnet18_nav_base import Resnet18NavBaseConfig
from .pointnav_base import PointNavBaseConfig, PointNavTask
from projects.pointnav_baselines.models.point_nav_models import (
ResnetTensorPointNavActorCritic,
)
class Resnet18PointNavExperimentConfig(PointNavBaseConfig, Resnet1... |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="pluralizefr",
description="pluralize for french language",
long_description=open("README.rst").read(),
version="0.0.1",
url="https://github.com/sblondon/pluralizefr",
packages=[
"pluralizefr",... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import tempfile
import time
# tmpfile = tempfile.NamedTemporaryFile('w', suffix='running',
# prefix='test', dir='/workspace/python/learn/base/tmpfile')
# # 名字还是随机的
# print(tmpfile.name)
def test():
tmpfile = tempfile.NamedTemporaryFile(suffix='.png')
print(t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.