text stringlengths 1 927k |
|---|
import pickle
from tqdm import tqdm
wikimap = {}
with open('page_ids_en.ttl', 'r') as filein:
for line in tqdm(filein, total=16000000):
try:
res, _, pageID, _ = [x.strip() for x in line.split(' ')]
pageID = int(pageID.split('^^')[0].strip('"'))
res = res.strip('<').strip('>')
wikimap[pageID] = res
exc... |
#!/usr/bin/env python3
# Copyright 2020 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Updates the python binaries that we cache s... |
from rest_framework import views
from accounts.api.views import *
from django.urls import path
from . import views
from accounts.api.serializer import RegisterSerializer
from accounts.views import RegisterView
app_name = 'accounts'
urlpatterns = [
path('register/', views.RegisterView.as_view(), name='auth_register... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import pytest
from unittest import mock
from aiogear import Worker, PacketType
@pytest.fixture(scope='function')
def worker():
w = Worker()
w.get_task = mock.Mock()
return w
def test_register_function_connected(worker):
written = None
def _write(data):
nonlocal written
written =... |
from django.db import models
# Create your models here.
class Headline(models.Model):
leaning = models.TextField()
title = models.TextField()
img = models.URLField(max_length=1000, null=True, blank=True)
mins_ago = models.IntegerField(default=1440)
time_ago_str = models.TextField(null=True)
url... |
from json import JSONEncoder
from PyQt6.QtGui import QIcon, QResizeEvent, QColor, QPainter, QBrush, QPen, QFont
from PyQt6.QtWidgets import QGridLayout, QWidget, QSizePolicy, QHBoxLayout, QGraphicsSimpleTextItem, QGraphicsRectItem, QGraphicsPixmapItem
from PyQt6.QtCore import Qt, pyqtSignal, QSize, QRect
from Assets i... |
from unittest import mock
from django.test import TestCase
from elasticsearch_django.index import (
_prune_hit,
bulk_actions,
create_index,
delete_index,
prune_index,
scan_index,
update_index,
)
from .models import ExampleModel, ExampleModelManager
class IndexFunctionTests(TestCase):
... |
# Generated by Django 2.2.7 on 2020-02-28 15:12
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('stories', '0002_auto_20200228_1551'),
]
operations = [
migrations.CreateModel(
name='Post',
... |
__author__ = 'Frank Sehnke, sehnke@in.tum.de'
from OpenGL.GL import * #@UnusedWildImport
from OpenGL.GLU import * #@UnusedWildImport
import math
class Objects3D:
def normale(self, vect, centerOfGrav):
vect = self.dumpVect(vect, 1.0 / 4.0)
norm = self.difVect(vect, centerOfGrav)
norm = sel... |
coins = list(range(2, 100))
result = [1] * 101
for i in coins:
for j in range(i, 101):
result[j] += result[j - i]
print(result[-1]) |
# ===========================================================================
# Copyright 2016-2017 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.o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import sys
# Постоянная Эйлера.
EULER = 0.5772156649015328606
# Точность вычислений.
EPS = 1e-10
if __name__ == '__main__':
x = float(input("Value of x? "))
if x == 0:
print("Illegal value of x", file=sys.stderr)
exit(1)
a = x
... |
#coding:utf-8
#
# id: bugs.core_3964
# title: It is not possible to create a ddl-trigger with "any DDL statement" clause
# decription:
# tracker_id: CORE-3964
# min_versions: ['3.0']
# versions: 3.0
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
# ver... |
"""Window object represented in layout."""
from bui.layout.attr import Attr
from bui.layout.component import Component
class Window(Component):
"""
Window tag, to encompass widget tags.
The window tag is the only one that is truly mandatory in your
[layout](../overview.md). It is used to describe b... |
"""
localhost
---------
"""
import socket, os
def get_localhostname():
if os.environ.get("DOC", False) == True:
return socket.gethostname()
else:
return "sphinx-doc"
def get_ip_adress():
if os.environ.get("DOC", False) == True:
try:
s = socket.socket(socket.AF_INET, s... |
from brain import Brain
from flask import Flask, request, render_template
from pprint import pprint
app = Flask(__name__, static_url_path="/static")
brain = Brain()
@app.route("/")
def index():
return render_template("index.html")
@app.route("/team/<string:team>")
def team(team):
return render_template("te... |
import functools
import logging
import traceback
import hashlib
import orjson
from cached_property import cached_property
from nlabel.io.json.group import split_data
from nlabel.nlp.nlp import NLP as CoreNLP, Text as CoreText
from nlabel.io.carenero.schema import Tagger, Tag, TagInstances, Text, Vector, Vectors, Resu... |
"""
Graphical model (GM)-based optimization algorithm using Theano
"""
from past.utils import old_div
import logging
import time
import numpy as np
from scipy.special import erf
from . import pyll
from .pyll import scope
from .pyll.stochastic import implicit_stochastic
from .base import miscs_to_idxs_vals
from .base ... |
from ete3 import Tree
import sys
t = Tree(sys.argv[1])
total = 0
for node in t.traverse():
loop = node.dist
total = total + loop
print (total) |
import math as m
def calc_discharge(b, h, k_st, m_bank, S):
A=h*0*5*(b+B).
P=b+2h(m**2+1)**0*5.
Q=k_st*R(2**3).sqrt*A
return Q
def interpolate_h(*args, **kwargs):
pass m
if __name__ == '__main__':
# input parameters
Q = 15.5 # discharge in (m3/s)
b = 5.1 # bottom cha... |
from backend.models.postgis.task_annotation import TaskAnnotation
from backend.models.postgis.utils import timestamp
class TaskAnnotationsService:
@staticmethod
def add_or_update_annotation(annotation, project_id, annotation_type):
""" Takes a json of tasks and create annotations in the db """
... |
# 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 u... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 logging
import ailment
from .atoms import Register, Tmp, MemoryLocation
from .constants import OP_BEFORE, OP_AFTER
from .dataset import DataSet
from .external_codeloc import ExternalCodeLocation
from .undefined import Undefined
from ...engines.light import SimEngineLightAIL, RegisterOffset, SpOffset
from ...er... |
# -*- coding: utf-8 -*-
#
# Gateway to Cookies documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration va... |
import json
from pathlib import Path
import torch
import numpy as np
from PIL import Image
from torch.utils.data import Dataset, TensorDataset
from tfrecord.torch.dataset import MultiTFRecordDataset
from uncertainty_eval.datasets.tabular import TabularDataset
from uncertainty_eval.datasets.abstract_datasplit import D... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, Qt... |
import os
import re
import logging
from abc import abstractmethod
from collections import Counter
from pathlib import Path
from typing import List, Union, Dict
import gensim
import numpy as np
import torch
from bpemb import BPEmb
from deprecated import deprecated
from pytorch_pretrained_bert import (
BertTokenize... |
# 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 setuptools import setup, find_packages
import re
import os
BASEDIR = os.path.dirname(os.path.abspath(__file__))
VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''')
def get_version():
init = open(os.path.join(BASEDIR, 'classroom_simulation', '__init__.py')).read()
return VERSION_RE.search(ini... |
""" test fancy indexing & misc """
from datetime import datetime
import re
import weakref
import numpy as np
import pytest
from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
import pandas as pd
from pandas import DataFrame, Index, NaT, Series
import pandas._testing as tm
from pandas.core.indexin... |
import torch
## 실험용 입니다
# x = torch.randint(10,size=(1,4,2,2))
# print(x)
# print(x.size())
# factor =2
# s = x.size()
# x = x.view(-1, s[1], s[2], 1, s[3], 1) # (-1, 4, 2, 1, 2, 1)
# print(x.size())
# # print(x)
# x = x.expand(-1, s[1], s[2], factor, s[3], factor) # (-1, 4,2,2,2,2)
# print(x.size())
# # print(x)
# ... |
#!/usr/bin/env python3
# Copyright 2018 Canonical Ltd.
#
# 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 la... |
def possible_moves(current_word, words_list):
answer_set = set()
for word in words_list:
if word.startswith(current_word):
answer_set.add(word[len(current_word)])
return answer_set
def rec(words_list, current_word=''):
if current_word in words_list:
return {current_word,}
... |
#!/usr/bin/python
import os
import sys
import time
import six
if sys.version[0] == '2':
from ConfigParser import ConfigParser
from cStringIO import StringIO
elif sys.version[0] == '3':
from configparser import ConfigParser
from io import StringIO
from larch.utils import OrderedDict
conf_sects = {'... |
# Copyright 2018 The TensorFlow Probability 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 applicable law o... |
from sgrna_modeler import features as fe
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from tensorflow import keras as k
import pandas as pd
import os
from joblib import load
import sgrna_modeler.enzymes as en
def curr_path():
return os.path.dirname(__file__)
def get_deepcpf1_w... |
import json
from pywps import Process, LiteralInput, ComplexOutput, Format
class TestJson(Process):
def __init__(self):
inputs = [LiteralInput('name', 'Input name', data_type='string')]
outputs = [ComplexOutput('output', 'Referenced Output',
supported_formats=[Format('application... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
__author__ = "Apache PredictionIO"
__email__ = "user@predictionio.apache.org"
__copyright__ = "Copyright 2017 The Apache Software Foundation"
__license__ = "Apache License, Version 2.0"
setup(
name='PredictionIO',
v... |
from __future__ import print_function
import pytest
from functools import partial
import codecs
import os
from odo import odo, resource, URL, discover, CSV, TextFile, convert
from odo.backends.url import sample
from odo.temp import _Temp, Temp
from odo.utils import tmpfile, raises
import datashape
try:
from ur... |
#!/usr/bin/python
import ConfigParser as cp
# Module named configparser in Python 3; ConfigParser in Python 2
config = cp.RawConfigParser()
config.read("..\passcodes.cfg")
passcodes= config.get("Main","passcodes").lower().split(",")
old_passcodes= []
total = len(passcodes)
if config.get("Main", "bronze"):
bro... |
# 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! ***
# Export this package's modules as members:
from .get_private_zone import *
from .get_record_set import *
from .get_virtual_network_link import *
from ... |
# -*- coding: utf-8 -*-
'''
Installing of mac pkg files
===========================
Install any kind of pkg, dmg or app file on macOS:
.. code-block:: yaml
/mnt/test.pkg:
macpackage.installed:
- store: True
/mnt/test.dmg:
macpackage.installed:
- dmg: True
/mnt/xcode.dmg:
... |
# Generated by Django 3.0.5 on 2020-05-05 15:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(aut... |
from .nondet import Nondet |
class Teammy:
def __init__(self):
self.name = 'T3ammy'
self.lastname = 'Sit_Uncle_Engineer'
self.nickname = 'teammy'
def WhoIAM(self):
'''
นี่คือฟังชั่่นที่ใช้ในการแสดงชื่อของคราสนี้
'''
print('My name is: {}'.format(self.name))
print('My lastna... |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,... |
#!/usr/bin/env python3
# Script by Ben Limmer
# https://github.com/l1m5
#
# This Python script will combine all the host files you provide
# as sources into one, unique host file to keep your internet browsing happy.
import argparse
import fnmatch
import json
import locale
import os
import platform
import re
import s... |
# Copyright 2014 Rackspace
# Copyright 2016 Blue Box, an IBM Company
# Copyright 2017 Walmart Stores 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://... |
# A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,... Faça um programa capaz de gerar a série até
# que o valor seja maior que 500
fibonnaci = []
limite = True
n = 0
while limite:
for n in range(1, 10000):
if n <= 1:
valor = n
fibonnaci.append(valor)
... |
from django.test import TestCase
from .models import Profile
import datetime as dt
from django.contrib.auth.models import User
# Create your tests here.
class ProfileTestClass(TestCase):
# Set up method
def setUp(self):
# Creating a new location and saving it
self.new_user= User(username='den... |
from ... import options as opts
from ...charts.chart import Chart
from ...commons.types import Numeric, Optional, Sequence, Union
from ...globals import ChartType
class Map(Chart):
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def __init__(self, init_opts: op... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_create_system_user'),
]
operations = [
migrations.AlterModelOptions(
name='user',
o... |
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-mcq-6/problem
# Difficulty: Easy
# Max Score: 10
# Language: Python
# Multiple Choice Question - No code required but checked with code
# ========================
# Solution
# ===... |
30 mtime=1365496689.486878593
30 atime=1440176559.453245606
30 ctime=1440177384.833299751 |
from django.contrib import admin
from catalog.models import Author, Genre, Book, BookInstance, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
admin.site.register(Language)
# admin.site.register(BookInstance)
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
... |
"""Devices queries for logbook."""
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime as dt
from sqlalchemy import lambda_stmt, select
from sqlalchemy.orm import Query
from sqlalchemy.sql.elements import ClauseList
from sqlalchemy.sql.lambdas import StatementLambdaEl... |
# Copyright 2019-2020 Not Just A Toy Corp.
#
# 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... |
from __future__ import division, absolute_import, print_function
__all__ = ["common", "chart", "data", "dateutils", "interest", "learn", "pf", "tech"]
from . import common
from .common import *
from . import chart
from . import data
from . import dateutils
from . import interest
from . import learn
from . import pf
f... |
import typing
import numpy as np
import numba as nb
@nb.njit
def find_divisors(
n: int,
) -> np.array:
i = np.arange(int(n ** .5))
i += 1
i = i[n % i == 0]
i = np.hstack((i, n // i))
return np.unique(i)
@nb.njit
def gpf(
n: int = 1 << 20,
) -> np.array:
s = np.arange(n)
s[:2] = -1
i = 0
whi... |
"""Extensions to the 'distutils' for large or complex distributions"""
import os
import functools
import distutils.core
import distutils.filelist
from distutils.util import convert_path
from fnmatch import fnmatchcase
from setuptools.extern.six.moves import filter, map
import setuptools.version
from setuptools.exten... |
names = set()
for _ in range(int(input())):
name = input()
if name not in names:
names.add(name)
[print(name) for name in names] |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
"Lists of blobs."
import flask
import blobserver.user
from blobserver import constants
from blobserver import utils
blueprint = flask.Blueprint("blobs", __name__)
@blueprint.route("/all")
def all():
"List of all blobs."
cursor = flask.g.db.cursor()
rows = cursor.execute("SELECT * FROM blobs")
blobs ... |
from pathlib import Path
import click
from . import functions as f
current_directory = Path(__file__).absolute().parent
default_data_directory = current_directory.joinpath('..', '..', 'data')
@click.command()
@click.option('--data-path', default=None, help='Directory for the CSV files')
@click.option('--submission... |
import io
import subprocess
import sys
import traceback
global cl
class Colorizer(object):
RED = "\033[31;1m"
GREEN = "\033[32;1m"
YELLOW = "\033[33;1m"
CYAN = "\033[36;1m"
RESET = "\033[0m"
NEWLINE = "\n"
@classmethod
def _colorize(cls, string, color):
return getattr(cls, co... |
from __future__ import absolute_import
import responses
import six
from six.moves.urllib.parse import parse_qs, urlencode, urlparse
from sentry.integrations.slack import SlackIntegration
from sentry.models import Identity, IdentityProvider, IdentityStatus, Integration, OrganizationIntegration
from sentry.testutils i... |
from logging import Logger
from pathlib import Path
from unittest.mock import Mock
import pytest
from tesliper.extraction import Soxhlet
from tesliper.glassware import Conformers, SingleSpectrum, Spectra
from tesliper.glassware import arrays as ar
from tesliper.writing.txt_writer import TxtWriter
@pytest.fixture
de... |
"""Wrapper around two RPI and the multi channel switch.
It relies on the use of the Multi_Adapter_Board_2Channel_uc444 for switching camera via the I2C and GPIO control.
See https://github.com/ArduCAM/RaspberryPi/tree/master/Multi_Camera_Adapter/Multi_Adapter_Board_2Channel_uc444
"""
import time
import cv2 as cv
f... |
from flask import current_app
from pystmark import (send, send_batch, get_delivery_stats, get_bounces,
get_bounce, get_bounce_dump, get_bounce_tags,
activate_bounce, Message as _Message)
from __about__ import __version__, __title__, __description__
__all__ = ['__version__', ... |
#!/usr/bin/python
from __future__ import division
import sys
import math
import cmath
import numpy as np
from numpy import genfromtxt
import csv
from decimal import Decimal
import os
import random
# BEATLES: Bundle of Essential and Assistive Tools Library for Electronic Structure
# A tribute to the Beatles
#... |
"""
This code is automatically generated. Never edit it manually.
For details of generating the code see `rubi_parsing_guide.md` in `parsetools`.
"""
from sympy.external import import_module
matchpy = import_module("matchpy")
if matchpy:
from matchpy import Pattern, ReplacementRule, CustomConstraint, is_match
... |
from flask import Blueprint
from google.cloud import firestore
application = Blueprint('task', __name__)
@application.route("/task")
def index():
return 'this is task directory'
@application.route("/task/sample")
def sample():
db = firestore.Client()
novels = db.collection(u'novels').order_by(u'novel_i... |
import pywps
import pywps.validator.mode
import natcap.invest.routing.routedem
import tempfile
import os.path
import logging
import sys
class invest(pywps.Process):
def __init__(self):
inputs = [pywps.LiteralInput("calculate_downstream_distance",
"Calculate Downstream... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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, inc... |
import io
import os
from pathlib import Path
from setuptools import find_packages, setup
# Package meta-data.
NAME = 'fen2pil'
DESCRIPTION = 'Convert Forsyth–Edwards Notation (FEN) to a 2D chessboard PIL image'
URL = 'https://github.com/elbuco1/fen2pil'
EMAIL = 'lrtboucaud@gmail.com'
AUTHOR = "Laurent Boucaud"
REQUIR... |
from django.db import migrations
class Migration(migrations.Migration):
replaces = [
("migrations", "3_auto"),
("migrations", "4_auto"),
("migrations", "5_auto"),
]
dependencies = [("migrations", "2_auto")]
operations = [migrations.RunPython(migrations.RunPython.noop)] |
import numpy as np
import os
import time
import sys
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.
abspath(__file__))))
if path not in sys.path:
sys.path.append(path)
import CM_intern.CEDM.modules.cyf.create_density_map as CDM
import CM_i... |
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import base64
import os
import re # noqa
import sys
from datetime import timedelta
# global settings
from django.conf import global_settings
# Update this module's local settings from the global settings module.
this_module = sys.modules[__name__]
for settin... |
# type: ignore
# MIT License
#
# Copyright (c) 2018-2019 Red Hat, Inc.
# 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 limitation the rights
# to use, ... |
from tartiflette.types.builtins.scalars import GraphQLBoolean, GraphQLFloat, \
GraphQLID, GraphQLInt, GraphQLString |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from flask import Flask,render_template, flash, redirect , url_for , session ,request, logging
from flask_mysqldb import MySQL
from wtforms import Form, StringField , TextAreaField ,PasswordField , validators
from passlib.hash import sha256_crypt
from functools import wraps
app = Flask(__name__)
app.debug = True
#C... |
import datetime
import email
import email.parser
import glob
import mailbox
import os
import re
import subprocess
import time
import urllib
import warnings
from email.header import Header
from email.message import Message
from email.mime.text import MIMEText
from typing import Dict, List, Optional, Tuple, Union
import... |
# -*- coding: utf-8 -*-
import re
import ply.lex as lex
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
class InterfaceStatusLexer(object):
states = (
('if', 'exclusive'),
('lo', 'exclusive'),
('vlan', 'exclusiv... |
from collections import Counter
from itertools import groupby
from math import log2
import numpy as np
def segments_start(array):
return [i for i in range(len(array)) if i == 0 or array[i] != array[i-1]]
def split_sequences(array, start):
end = start[1:] + [len(array)]
return [array[s:e] for s, e in zip... |
'''
Desenvolva um programa que pergunte a distância de uma viagem em Km.
Calcule o preço da passagem, obrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas.
'''
dist = float(input('\033[1;33mInforme a distância da viagem desejada:\033[m '))
if dist <= 200:
print(('O valor da sua viagem s... |
# -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd/m/Y'
TIME_FORMAT = 'P'
DATETIME... |
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import sys
import gzip
import os
class Record(object):
"""Represents a record."""
class Respondent(Record):
"... |
from selenium import webdriver
import datetime
import random
import time
from webdriver_manager.chrome import ChromeDriverManager #1st changer
driver = webdriver.Chrome(ChromeDriverManager().install()) #2nd change
driver.get('https://www.instagram.com')
time.sleep(1)
#auto login information
def login():
driver.f... |
#!/usr/bin/env python3
import datetime
import os
import time
from pathlib import Path
from typing import Dict, Optional, Tuple
from collections import namedtuple, OrderedDict
import psutil
from smbus2 import SMBus
import cereal.messaging as messaging
from cereal import log
from common.filter_simple import FirstOrderF... |
"""Implement the model in real time."""
# Third party modules
import matplotlib.pyplot as plt
import numpy as np
import sounddevice as sd
from pydub import AudioSegment
from pydub.playback import play
class Realtime:
"""Implement the modle in real time."""
def __init__(self, settings):
"""Intiallise ... |
"""
warmup.py contains classes for warm up stream operations.
"""
import numpy as np
from iqt.feed.core.base import Stream, T
class WarmUp(Stream[T]):
"""A stream operator for warming up a given stream.
Parameters
----------
periods : int
Number of periods to warm up.
"""
def __ini... |
"""
Copyright 2020 RPANBot
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
distrib... |
from django.test import TestCase
# Create your tests here.
import datetime
from polls.models import Question
from django.utils import timezone
from django.urls import reverse
#creating tests for Question model
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
... |
import json
import numpy as np
import numpy.random as rnd
import os
class parameter_storage(object):
"""
This class contains the simulation parameters in a dictionary called params.
"""
def __init__(self, params_fn=None):
"""
If a filename is given, it loads the json file and returns t... |
from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_mak... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from django import forms
class SystemImporterFileCsvForm(forms.Form):
# file upload field (variable is used in request object)
systemcsv = forms.FileField(
label = 'CSV with systems (*)',
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.