content stringlengths 5 1.05M |
|---|
import hashlib
import inspect
import sys
import random
import re
from functools import partial
from types import GeneratorType, MethodType
try:
Pattern = re.Pattern
except AttributeError:
# < Python 3.7
Pattern = re._pattern_type
def alternative_hash(value):
"""Quick way of doing a hash.
This use... |
import numpy
import chainer
from chainer import functions
from chainer_pointnet.models.conv_block import ConvBlock
from chainer_pointnet.utils.grouping import query_ball_by_diff
from chainer_pointnet.utils.sampling import farthest_point_sampling
class SetAbstractionModule(chainer.Chain):
def __init__(self, k, ... |
#=========================================================================
# assertion_helpers.py
#=========================================================================
# Functions for dumping assertion checking scripts
#
# Author : Christopher Torng
# Date : March 13, 2020
#
import os
import re
import stat
fro... |
# -*- coding: utf-8 -*-
"""
Module pyelegantsdds.tools.sddsutils
=================================================================
A module containing a list of sdds comamnds.
"""
import os
import subprocess
import time
from itertools import product
import numpy as np
import pandas as pd
from dask import dataframe ... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
# Copyright 2017 The TensorFlow 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 applica... |
import pandas as pd
import numpy as np
import pickle
import time
import os
import yaml
import json
import argparse
import FIDDLE.config as FIDDLE_config
import FIDDLE.steps as FIDDLE_steps
def main():
######
# User arguments
######
parser = argparse.ArgumentParser(description='')
# Files
pars... |
class PynderError(Exception):
pass
class RequestError(PynderError):
pass
class InitializationError(PynderError):
pass
|
import itertools
import random
import bisect
class Solution:
def __init__(self, w):
"""
:type w: List[int]
"""
self.presum = list(itertools.accumulate(w))
def pickIndex(self):
"""
:rtype: int
"""
return bisect.bisect_left(self.presum, random.rand... |
import os
import sys
import traceback
from typing import Union, List, Optional
from ..request import Request
from ..request.control import ControlRequest
from ..request.data import DataRequest
from ... import __version__, __proto_version__
from ...enums import CompressAlgo
from ...excepts import MismatchedVersion
from... |
#!/usr/bin/python3
"""Solution for day 21 of Advent of Code 2016.
Each operation has an entry in the ops dictionary, which mangles arguments and does pre-processing before handing off
to one of the main methods to perform the actual transformation.
For part two, the reverse_ops dictionary maps most operations to a r... |
import os
import sys
from ctypes import *
from contextlib import contextmanager
import pyaudio
from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *
script_dir = os.path.dirname(os.path.realpath(__file__))
model_dir = "/home/akhil/Desktop/sphinx-source/pocketsphinx/model/en-us"
hmm = os.path.jo... |
# pylint: disable=R0902,R0904,R0914
from __future__ import annotations
from typing import TYPE_CHECKING
from pyNastran.bdf.cards.nodes import SPOINT, EPOINT
if TYPE_CHECKING: # pragma: no cover
from pyNastran.bdf.bdf import (
BDF,
CYAX, CYJOIN, AXIF,
TOPVAR, MPCAX, CORD3G,
SESUPORT,... |
from PIL import Image
import time
from opensfm import features
import numpy as np
import os
from collections import OrderedDict
import json
from matplotlib.image import _rgb_to_rgba
class Database:
def __init__(self, seqs, path, preload_images=True):
self.points = OrderedDict()
self.seqs = seqs
... |
# Copyright (2017) CoderMe.com
def make_range(frames_count, hosts_count):
if frames_count < 1 or hosts_count < 1:
return []
# make frames_count divisible if its not already
origin_count = frames_count
while frames_count % hosts_count != 0:
frames_count += 1
per_host = frames_coun... |
# Copyright 2015 Dietrich Epp.
# This file is part of SGGL. SGGL is licensed under the terms of the
# 2-clause BSD license. For more information, see LICENSE.txt.
import argparse
import os
import platform
import sys
from . import Registry, API_LIST, parse_version, parse_api
def die(msg):
"""Show an error message... |
#!/usr/bin/env python
import pickle
import subprocess
import os
import sys
if not os.path.exists('.instanceIDlist.txt'):
print '\nCannot terminate instance - could not find file .instanceIDlist.txt. Did you launch RELION on AWS from this directory?\n'
sys.exit()
if not os.path.exists('.instanceIPlist.txt'):
... |
from turtle import *
screen = Screen()
turtles = []
t = 10
for x in range(t):
turtle = Turtle()
r = (360/t) * x
turtle.right(r)
turtles.append(turtle)
for turtle in turtles:
turtle.forward(100)
turtle.left(10)
turtle.back(20)
turtle.left(10)
turtle.forward(40)
screen.exitonclick... |
from . import purge_path
from .version import __version__
|
import argparse
import torch
torch.backends.cudnn.benchmark = True
import yaml
from trainer import Trainer
def make_flags(args,config_file):
if config_file:
config = yaml.load(open(config_file))
dic = vars(args)
all(map(dic.pop, config))
dic.update(config)
return args
parser ... |
from galaxy import model
from galaxy.util.odict import odict
def build_collection( type, dataset_instances ):
"""
Build DatasetCollection with populated DatasetcollectionElement objects
corresponding to the supplied dataset instances or throw exception if
this is not a valid collection of the specifie... |
from attrdict import AttrDict
AccountType = AttrDict(dict(
BUSINESS='Business',
INCOMPLETE='Incomplete',
PERSONAL='Personal'
))
ApprovalStatus = AttrDict(dict(
APPROVED='Approved',
PENDING='Pending',
IGNORED='Ignored'
))
AttachmentType = AttrDict(dict(
EXTERNAL_INVOICE='ExternalInvoice',
... |
"""run this to see if the swhlab your interpreter is using lives in this
folder, or if it's installed on the system. For developing, I recommend
having it not installed on the system, but rather adding the ../ path to
your PYTHONPATH just for the python session you're debugging in."""
import os
def test_importing():
... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Vegetation/Biomass'},
{'abbr': 1, 'code': 1, 'title': 'Agri-/aquacultural Special Products'},
{'abbr': 2, 'code': 2, 'title': 'Transportation-related Products'},
{'abbr': 3, 'code': 3, 'title': 'Soil Products'},
{'... |
import webbrowser
import wikipedia
import requests
def yt_search(search: str):
webbrowser.open_new_tab(f"https://www.youtube.com/results?search_query={search}")
def google_search(search: str):
webbrowser.open_new_tab(f"https://www.google.com/search?q={search}")
def bing_search(search: str):
webbrowser.op... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from glob import iglob
import os
# pip install winshell
import winshell
path_desktop_lnk = os.path.expanduser(r'~\Desktop\Пройти\*.lnk')
need_disc = "E:"
paths = []
for file_name in iglob(path_desktop_lnk):
shortcut = winshell.shortcut(f... |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
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 res... |
""" 配置 """
from pathlib import Path
from typing import Dict
from nonebot import get_driver, require
from pydantic import BaseModel, Extra, root_validator
require("nonebot_plugin_localstore")
from nonebot_plugin_localstore import get_cache_dir, get_config_dir, get_data_dir
# 默认目录
BASE_CACHE_DIR: Path = Path(get_cache... |
#!/usr/bin/env python3
import semanticpingback
sp = semanticpingback.SemanticPingbackReceiver()
links = sp.receivePing("http://resource.feedback.aksw.org/dda9890831d7f16b598eb7f854afeb71-resource", "http://mmoon.org/lang/heb/inventory/oh/Lexeme_אֱגוֹז")
print(links.serialize(format="nt").decode("utf-8"))
|
from faker import Faker
from pytest_bdd import scenarios, when, then, parsers
from selenium.webdriver.support.select import Select
from ui_tests.exporter.pages.add_member import AddMemberPage
from ui_tests.exporter.pages.member_page import MemberPage
from ui_tests.exporter.pages.members_page import MembersPage
from ui... |
from . import BaseMessage
class SendTextMessage(BaseMessage):
def create_request_body(self) -> dict:
activity_id = self.options.get('activity_id')
user_id = self.options.get('user_id')
text = self.options.get('text')
return {
"type": "message",
"serviceU... |
from .base import *
from direct.interval.IntervalGlobal import (LerpPosInterval, LerpQuatInterval,
LerpScaleInterval, LerpQuatScaleInterval, Parallel)
class ViewManager:
def __init__(self):
GD.set_default("view", "persp")
self._lerp_interval = None
self._transition_done = True
... |
import sys
sys.path.append('../')
import unittest
from cog_abm.core.agent import *
class TestMetrics(unittest.TestCase):
def setUp(self):
pass
|
from datetime import datetime
from django.db import models
from django.utils.deconstruct import deconstructible
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFit
import os
from apps.utils.models import TimestampUserMeta
# TODO: Convert ID fields to UUID
@deconstructible
clas... |
import os
from typing import Union
from yt.config import ytcfg
_envvar = "YTGEOTOOLSDIR"
def join_then_check_path(filename: str, dirname: str) -> Union[str, None]:
newname = os.path.join(dirname, filename)
if os.path.isfile(newname):
return newname
return None
class DataManager:
def __init... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from unittest import TestCase
import uw_coda
POL_S_LABEL = "2014-winter-POL%20S-201-A"
POL_S_AA_LABEL = "2014-winter-POL%20S-201-AA"
class TestEndpoints(TestCase):
def test_fail_rate(self):
fail_rate = uw_coda.get_f... |
from typing import List, Optional, Union
from uuid import UUID
import yara
from pydantic import Field, validator
from app.schemas.base import APIModel
from app.schemas.search import BaseSearchResults
from app.schemas.snapshot import BaseRule, Rule
from app.schemas.types import TargetTypes
class CreateRulePayload(Ba... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2016, Nigel Small
#
# 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
#
# Unle... |
get_red()
Retrieves the color intensity of red.
Returns
Type
:
integer (a positive or negative whole number, including 0)
Values
:
0 to 1024
Errors
RuntimeError
The sensor has been disconnected from the Port. |
import math
from ._builtin import Page, WaitPage
from datetime import timedelta
from operator import concat
from functools import reduce
from .models import parse_config
class Introduction(Page):
def is_displayed(self):
return self.round_number == 1
class GenderPage(Page):
form_model = 'player'
... |
# @Author: Abdellah OUlahyane
# @Date: 2021-03-25 01:03:59
# @Last Modified by: Abdellah Oulahyane
# @Last Modified time: 2021-03-29 01:31:15
import sys
import os
from Model.book import Book
from .controller import Controller
class bookController(Controller):
def add(self,*args):
"""AI is creating s... |
##############################
## COVID_county.py ##
## Chieh-An Lin ##
## Version 2021.07.30 ##
##############################
import os
import sys
import warnings
import datetime as dtt
import numpy as np
import scipy as sp
import scipy.signal as signal
import pandas ... |
# Copyright 2016 Intel 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
#
# Unless required by applicable law or agreed t... |
import math
import os
import shutil
from KOMORANPy.common.dictionary import Dictionary
from KOMORANPy.common.grammar import Grammar
from KOMORANPy.common.irregular.irregular_node import IrregularNode
from KOMORANPy.common.irregular.irregular_trie import IrregularTrie
from KOMORANPy.constant import SYMBOL, FILENAME
fr... |
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivymd.app import MDApp
from kivymd.theming import ThemableBehavior
from kivymd.uix.list import OneLineIconListItem, MDList
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ... |
a = 0
b = 10
c = 20
|
#!/usr/bin/env python
import sys, os, re
from cachetools import cached
import subprocess
import zipfile
import shutil
import random
import strbalance
num_re = r'\[([0-9]+.?END[0-9]*)\]'
image_postfix = '[Twine.image]'
formats = shutil.get_unpack_formats()
valid_zip_extensions = []
for f in formats:
valid_zip_extens... |
"""This module defines utility functions for solving eigenvalues."""
import numpy as np
from .misctools import importLA, div0
from .logger import LOGGER
__all__ = ['solveEig', 'ZERO']
ZERO = 1e-6
def solveEig(M, n_modes=None, zeros=False, turbo=True, expct_n_zeros=None, reverse=False):
linalg = importLA()
d... |
from flask import Flask
# from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# db = SQLAlchemy(app)
@app.route('/')
def hello():
return "Hello World!"
@app.route('/echo/<arg>')
def echo(arg):
return "Echo: {}!".format(arg)
if __name__ == '__main__':
app.run()
|
import os
VERSION = "1.0"
MODEL_NAME = os.path.basename(os.path.dirname(__file__))
DOCKERHUB_REPO = f"danieldeutsch/{MODEL_NAME}"
DEFAULT_IMAGE = f"{DOCKERHUB_REPO}:{VERSION}"
AUTOMATICALLY_PUBLISH = True
from repro.models.dou2021.dataset_reader import Dou2021DatasetReader
from repro.models.dou2021.models import Orac... |
"""Include ZipfFromDir class."""
from .zipf_from_dir import ZipfFromDir
__all__ = ['ZipfFromDir']
|
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from django.contrib.auth.models import Group
from meiduo_admin.pages import MyPage
from meiduo_admin.serializers.group_serializer import *
from meiduo_admin.serializers.perm_serializer import *
class GroupViewSet(ModelVie... |
#! /usr/bin/env python
#
# 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 requ... |
#!C:/anaconda3/python.exe
# -*- coding: utf-8 -*-
import io
import sys
import requests
import bs4
import urllib.parse
import numpy as np
import json
import re
# 出力コーデック指定 文字化け対策
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
#定数宣言
YAHOO_AUCTION = "YAHOO_AUCTION"
AMAZON = "AMAZON"
YEN = "円"
NULL_J... |
#!/usr/bin/env python
import rospy
import sys
import cv2
import numpy as np
from std_msgs.msg import String
from std_msgs.msg import Float64MultiArray
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from mbzirc_comm_objs.msg import ObjectDetection
from mbzirc_comm_objs.msg import ObjectD... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-02 04:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Questio... |
# Generated by Django 2.2.13 on 2020-10-29 23:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('origins', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='site',
name='location_remarks',
... |
from hoverset.ui.widgets import Window
class BaseTool:
"""
Base tool for Tools. Subclass this class to implement a studio tool
"""
name = ''
icon = 'blank'
@classmethod
def get_menu(cls, studio):
"""
Override this method to return menu template for your tool
Set up... |
import json
import logging
import math
import os
import re
import socket
from collections import defaultdict, Counter
from datetime import datetime
from os import mkdir, makedirs, getpid
from time import perf_counter
import h5py
import torch
from numbers import Number
from os.path import join, exists, dirname
from typ... |
n=int(input())
import math
for i in range(n):
a=input()
l=len(a)
s=0
if(l==1):
print(int(a))
else:
for i in range(l-1):
s+=9
if(int(a)==int(math.pow(10,l-1))):
print(s)
else:
c=0
s+=int(a[0])-1
for i in range(l-1):
if(a[i]<a[i+1]):
... |
import numpy as np
import pandas as pd
import sympy as sp
import matplotlib.pyplot as plt
import pytest
import sys
from examples.seismic import Model, TimeAxis, RickerSource, Receiver
from devito import TimeFunction, Eq, Operator, NODE, ConditionalDimension, \
Function, Le
from devitoboundary import BoundaryCondit... |
import pickle
import os
import numpy as np
import torch
import torch.utils.data as data
import torch.nn as nn
from torch.optim import Adam
import torch.nn.functional as F
from torch.nn import Module
import argparse
class Dataset(data.Dataset):
def __init__(self, imsize, datapath='../../data', dataset='birds'):
... |
"""Edge-Weighted Directed Graph: Directed Edge"""
class DirectedEdge:
__slots__ = 'frm', 'to', 'weight'
def __init__(self, v, w, weight):
"""DirectedEdge constructor.
:param v: Vertex 1
:type v: int
:param w: Vertex 2
:type w: int
:param weight: Edge weight
... |
from __future__ import absolute_import
import six
from django.core.urlresolvers import reverse
from sentry.models import User, UserOption
from sentry.testutils import APITestCase
class UserDetailsTest(APITestCase):
# TODO(dcramer): theres currently no way to look up other users
# def test_simple(self):
... |
import turtle
ted = turtle.Turtle()
ted.shape("turtle")
ted.color("black")
ted.penup()
ted.goto(-100,80)
ted.fillcolor("yellow")
ted.begin_fill()
ted.circle(50)
ted.end_fill()
ted.color("brown")
ted.goto(0,-180)
ted.pendown()
ted.forward(100)
ted.left(90)
ted.forward(100)
ted.left(90)
ted.forward(100)
ted.left(90)
t... |
import unittest
import xr
class TestBool(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_bool(self):
self.assertTrue(True)
self.assertFalse(False)
self.assertTrue(xr.TRUE)
self.assertFalse(xr.FALSE)
self.assertTrue(xr.B... |
import os
import sys
import uuid
import tempfile
from io import StringIO
import re
import numpy as np
from copy import deepcopy
# from pyobb.obb import OBB
try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_re... |
import numpy as np
import torch
def relative_to_abs(rel_traj, start_pos):
"""
Inputs:
- rel_traj: pytorch tensor of shape (seq_len, batch, 2)
- start_pos: pytorch tensor of shape (batch, 2)
Outputs:
- abs_traj: pytorch tensor of shape (seq_len, batch, 2)
"""
# batch, seq_len, 2
rel... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import unittest
import vnc_api
from vnc_api import Subnet, IpVer
from vnc_api import SGPeerType, SGPeer, SGDir, SGAction, SGApp, SGAppType
from vnc_api import PortParam, SGRule
from vnc_api import PeEndPt, PeEndPtType, PeAppType, PeAction,... |
import abc
import enum
from dataclasses import dataclass
from typing import Optional, Tuple, Union
from great_expectations.exceptions import ProfilerConfigurationError
@dataclass
class CardinalityLimit(abc.ABC):
name: str
@dataclass
class RelativeCardinalityLimit(CardinalityLimit):
max_proportion_unique: f... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2004-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
from collections import OrderedDict
import numpy as np
from gym import GoalEnv, spaces
class BitFlippingEnv(GoalEnv):
def __init__(
self, n_bits=10, continuous=False, max_steps=None, discrete_obs_space=False
):
super(BitFlippingEnv, self).__init__()
if discrete_obs_space:
... |
"""This module is an inherited class of workspace.
Libraries/Modules:
Workspace\n
numpy\n
Field\n
"""
import numpy as np
from bin.Field import Field, max
from bin.Workspace import Workspace
from bin.Field import copy, isfinite, norm
class CellCenterWS(Workspace):
"""Implements a Worksp... |
import numpy as np
import matplotlib.pyplot as plt
from uncertainties import ufloat
import uncertainties.unumpy as unp
from scipy import optimize
import scipy.constants as const
from scipy import stats
from scipy.stats import sem
from pylab import fill
h = const.Planck
c = const.speed_of_light
q = const.elementary_cha... |
from pathlib import Path
from aws_cdk import aws_glue as glue, core, aws_s3_deployment
from aws_cdk import aws_iam as iam
from datajob import logger
from datajob.datajob_base import DataJobBase
from datajob.datajob_context import DatajobContext
from datajob.stepfunctions import stepfunctions_workflow
@stepfunctions... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
import speech_sample
import intent_sample
import translation_sample
import speech_synthesis_sample
from collections import Orde... |
from pygame import mixer
mixer.init()
mixer.music.load('ex21.mp3')
mixer.music.play()
input('Agora vc escuta a música')
|
from win10toast import ToastNotifier
from pygame import mixer
import schedule
import requests
import json
API_URL = "https://api.coindesk.com/v1/bpi/currentprice/{}.json"
PRICE_INCREASED = "Bitcoin Price Increased!"
PRICE_DECREASED = "Bitcoin Price Decreased!"
CURRENT_PRICE = 0.0
CURRENCY = "USD"
TOASTER = ... |
#
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""
ISO domain configuration plugin.
"""
import datetime
import gettext
import hashlib
import os
import re
import uuid
from otopi import constants as otopicons
from otopi import filetransaction
from ot... |
# Copyright 2017-2020 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
from setuptools import setup
from codecs import open
from os import path
from hatchet import __version__
here = path.abspath(path.dirname... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import re
import rapidsms
from rapidsms.parsers import Matcher
from persistance.models import *
from locations.models import *
from models import *
from i18n.app import InternationalApp
class App(rapidsms.App, InternationalApp):
#kw = Keyworder()
def _d... |
"""
Created on Apr. 27, 2021
@author: Heng-Sheng (Hanson) Chang
"""
from __future__ import division
from __future__ import print_function
from collections import defaultdict
from numba import njit
from numpy.core.shape_base import block
from tqdm import tqdm
import numpy as np
import pickle
import matplotlib.pyplo... |
import requests
def exists(url):
try:
response = requests.get(url)
return True
except requests.ConnectionError:
return False
except requests.exceptions.MissingSchema:
pass
def begins_with_http(url):
if len(url) < 7:
return False
if (( (url[0], url[1], ur... |
"""
Projeto: Funcao jogador
"""
name = input('Digite o nome do jagador: ')
goals = input('Digite o número de gols: ')
if name.isalpha() == False:
name = "<desconhecido>"
if goals.isnumeric():
goals = int(goals)
else:
goals = 0
def Player(playerName = "<desconhecido>", numberGoals = 0):
return f'O joga... |
#!/usr/bin/env python
"""strip outputs from an IPython Notebook
Opens a notebook, strips its output, and writes the outputless version to the original file.
Useful mainly as a git filter or pre-commit hook for users who don't want to track output in VCS.
This does mostly the same thing as the `Clear All Output` command... |
from walls import *
import robot
from sensors import *
from agents import *
def basic_collectball_map_static(width=600, height=600):
my_robot = robot.Robot(circle_radius=20, name="lovely_robot", color=(0, 0, 0), circle_position=[200, 200])
my_robot.add_sensors(Sensors(sensor_coverage=180, num_rays=9, color=(0, ... |
x = int(input())
for _ in range(x):
origin = []
after = []
push_origin = origin.append
push_after = after.append
a, b = [int(x) for x in input().split()]
for _ in range(a):
t = input().split()
push_origin(t)
push_after(t[::-1])
if origin == after[::-1]:
print(... |
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# This is an EXUDYN example
#
# Details: Test model for rigid bodies sliding on cables
#
# Author: Andreas Zwölfer, Johannes Gerstmayr
# Date: 2019-12-18
#
# Copyright:This file is part of Exudyn. Exudyn is free software. You can redi... |
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# Time complexity: O(n)
# Space complexity: O(1)
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
i = 1
odd_dummy_head... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
# Error-handling here is to allow package to be built w/o README included
try:
readme = open(os.path.join(
os.path.dirname(__file__), 'README.rst' )).read()
except IOError: readme = ''
setup(
name = 'sht-sensor',... |
"""
Script to update citation.cff file and validate it then draft a release note.
"""
import argparse
from datetime import datetime
def read_from_file(infile):
with open(infile, "r", encoding="utf8") as fid:
return fid.readlines()
def int_to_version(major, minor, tiny):
return f"{major}.{minor}.{tiny}... |
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.exceptions import APIException
from rest_framework.decorators import action
from .models import Endpoint
from .serializers import EndpointSerializer
from .models import MLAlgorithm
from .seria... |
import csv
import os
import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
host = "smtp.gmail.com"
port = 465
class MailManager():
def __init__(self,finalData):
self.finalData = finalData
... |
from .faiss_indexes import Extract_Index
|
#!/usr/bin/env python3
#
# tidy.py
# Copyright (c) 2017 Dylan Brown. All rights reserved.
#
# NOTES
# Use Python 3. Run from the `build/` directory.
# A wrapper which calls the run-clang-tidy.py tool from the LLVM project.
import os
import sys
# Comma separated list of check flags.
# For example, "-*,readablity-*"... |
"""encrypt.py
This allows plaintext messages to be encrypted and ecrpyted using an
affine cipher. The affine cipher encryption uses a = 9 and b = 8.
"""
import re
def encrypt(msg: str) -> str:
"""Encrypts a plaintext message.
Parameters:
-----------
msg:
string: The plaintext message to be e... |
#!/usr/bin/python
import pypresenter.slide
class slide13(pypresenter.slide):
def __init__(self):
super(self.__class__, self).__init__('left')
def content(self, window=None):
return "// merge.xcconfig\n"\
"PODS_BUILD_DIR = $BUILD_DIR\n\n"\
"PODS_CONFIGURATION_BUILD... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-03 04:24
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependenc... |
# Copyright 2016 Intel 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
#
# Unless required by applicable law or agreed to in wri... |
# -*- coding: utf-8 -*-
"""
Preprocessors.
"""
import re
import numpy as np
from allennlp.modules.elmo import Elmo, batch_to_ids
from sklearn.base import BaseEstimator, TransformerMixin
import joblib
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.sequence import pad_sequences
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.