text string | size int64 | token_count int64 |
|---|---|---|
budget = float(input())
nights = int(input())
price_night = float(input())
percent_extra = int(input())
if nights > 7:
price_night = price_night - (price_night * 0.05)
sum = nights * price_night
total_sum = sum + (budget * percent_extra / 100)
if total_sum <= budget:
print(f"Ivanovi will be left ... | 436 | 170 |
import sublime, sublime_plugin
import threading
class ProcessQueueManager():
__shared = {}
items = []
thread = None
# Current item details
messages = None
function = None
callback = None
# Progress Bar preferences
i = 0
size = 8
add = 1
def __new__(cls, *args, **kwargs):
inst = object.__new__(cls)
... | 2,573 | 950 |
import html
import json
import logging
import re
from abc import abstractmethod
from datetime import datetime, time
from typing import Optional
import requests
from moscow_routes_parser.model import Route, Timetable, Equipment, Timetable_builder
from moscow_routes_parser.model_impl import Timetable_builder_t_mos_ru
... | 10,199 | 3,048 |
from web.api import BaseAPI
from utils import mongo
import json
class DataApi(BaseAPI):
def __init__(self):
BaseAPI.__init__(self)
self._db = mongo.MongoInterface()
self.query = {}
self.fields = {
"donation_count": "$influences.electoral_commission.donation_count",
... | 6,762 | 1,957 |
# 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
# d... | 21,616 | 7,222 |
import idna
class AddressMismatch(ValueError):
'''
In order to set up reverse resolution correctly, the ENS name should first
point to the address. This exception is raised if the name does
not currently point to the address.
'''
pass
class InvalidName(idna.IDNAError):
'''
This excep... | 1,823 | 538 |
import mido
from socketer import MASM
inPort = None
doReadInput = False
def Start():
global inPort
try:
print(f"MIDI inputs: {mido.get_input_names()}")
inPort = mido.open_input()
print(f"MIDI input open: {inPort}")
except Exception as e:
inPort = None
print(f"Could not open MIDI input: {e}")
def Update(... | 1,082 | 482 |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Column(Component):
"""A Column component.
Row Column
Keyword arguments:
- children (list of a list of or a singular dash component, string or numbers | a list of or a singular dash component, strin... | 1,896 | 536 |
from typing import List
from typing import Optional
from typing import Union
from models.vps import VpsStatus
from schemas.base import APIModel
from schemas.base import BasePagination
from schemas.base import BaseSchema
from schemas.base import BaseSuccessfulResponseModel
class VpsSshKeySchema(APIModel):
name: s... | 2,221 | 742 |
import sigplot as sp
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.rcParams['toolbar'] = 'None'
plt.style.use('dark_background')
fig = plt.figure()
# seed = np.linspace(3, 7, 1000)
# a = (np.sin(2 * np.pi * seed))
# b = (np.cos(2 * np.pi * seed))
# sp.correlate(fig, b... | 672 | 339 |
# 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.
# Changes may ... | 149,429 | 47,506 |
import logging
import re
from pathlib import Path
from typing import Match
logger = logging.getLogger(__name__)
IMAGE_RE = re.compile(
r"/baseplate-py:(?P<version>[0-9.]+(\.[0-9]+)?)-py(?P<python>[23]\.[0-9]+)-(?P<distro>(bionic|buster))(?P<repo>-artifactory)?(?P<dev>-dev)?"
)
def upgrade_docker_image_refere... | 1,668 | 569 |
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from model.base import Base
class SWTZ_TY(Base):
__tablename__ = 'swtz_ty'
class_name = '商务团组-团员'
foreign_key = 'swtz_id'
export_docx = False
export_handle_file = ['identity']
field = [
'id', 'nickname', 'job', 'id_card... | 1,249 | 448 |
from django.urls import reverse
from consents.models import Consent, Term
from workshops.models import KnowledgeDomain, Person, Qualification
from workshops.tests.base import TestBase
class TestAutoUpdateProfile(TestBase):
def setUp(self):
self._setUpAirports()
self._setUpLessons()
self._... | 3,515 | 1,062 |
import numpy as np
import time
import cv2
import colorsys
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Activation, ReLU, Multiply
# Custom objects from backbones package https://github.com/david8862/keras-YOLOv3-model-set/tree/master/common/backbones
def mish(... | 4,823 | 1,716 |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import datetime
class TLClassifier(object):
def __init__(self):
PATH_TO_CKPT = "light_classification/frozen_inference_graph.pb"
self.graph = tf.Graph()
self.threshold = 0.5
with self.graph.as_default(... | 2,706 | 849 |
#Based off of http://wiki.wxpython.org/GLCanvas
#Lots of help from http://wiki.wxpython.org/Getting%20Started
from OpenGL.GL import *
import wx
from wx import glcanvas
from Primitives3D import *
from PolyMesh import *
from LaplacianMesh import *
from Geodesics import *
from PointCloud import *
from Cameras3D import *
... | 16,563 | 7,343 |
import matplotlib.pyplot as plt
import numpy as np
import pickle
# import csv
# from collections import namedtuple
# from mpl_toolkits.mplot3d import Axes3D
# import matplotlib.animation as animation
# import matplotlib.colors as mc
class FEModel:
def __init__(self, name=None, hist_data=None):
self.name =... | 17,382 | 7,652 |
#!/usr/bin/env python
import json
import sys
from gigamonkeys.spreadsheets import spreadsheets
spreadsheet_id = sys.argv[1]
ranges = sys.argv[2:]
data = spreadsheets().get(spreadsheet_id, include_grid_data=bool(ranges), ranges=ranges)
json.dump(data, sys.stdout, indent=2)
| 278 | 99 |
root_URL = "https://tr.wiktionary.org/wiki/Vikis%C3%B6zl%C3%BCk:S%C3%B6zc%C3%BCk_listesi_"
filepath = "words.csv"
#letters=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O",
# "P","R","S","T","U","V","Y","Z"] ##İ,Ç,Ö,Ş,Ü harfleri not work correctly
letters=["C"] | 282 | 148 |
from github3 import login
from github3.models import GitHubError
from celery import task
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from sow_generator.models import Repository, AuthToken
def _sync_repository(obj):
dirty = False
token = AuthToken.objects.get(id=1).to... | 1,374 | 432 |
import numpy as np
from sources import BaseSource
from sources.base import BaseSourceWrapper
from sources.preloaded import PreLoadedSource
import json
class WordsSource(BaseSource):
def __init__(self, source):
self._source = source
def __len__(self):
return len(self._source)
def _remove_... | 6,145 | 1,924 |
import random
import cv2
import numpy as np
import warnings
from PIL import Image
from gym.spaces import Box, Dict
from multiworld.core.multitask_env import MultitaskEnv
from multiworld.core.wrapper_env import ProxyEnv
from multiworld.envs.env_util import concatenate_box_spaces
from multiworld.envs.env_util import ge... | 10,956 | 3,402 |
#!/usr/bin/env python
import sys
import json
import logging
from math import exp
import requests as rq
import re
### For NLP post-processing
header={"Content-Type": "application/json"}
message='{"sample":"Hello bigdata"}'
api_url="http://192.168.1.197:11992/norm"
###
def NLP_process_output(pre_str):
try: ... | 2,546 | 808 |
from langdetect import detect
def detect_language(x):
#detect language of the article
try:
lang=detect(x['value'])
except:
lang="empty"
execute('SET', 'lang_article:' + x['key'], lang)
if lang!='en':
execute('SADD','titles_to_delete', x['key'])
gb = GB()
gb.foreach(detec... | 349 | 120 |
"""
Defines the basic objects for CORE emulation: the PyCoreObj base class, along with PyCoreNode,
PyCoreNet, and PyCoreNetIf.
"""
import os
import shutil
import socket
import threading
from socket import AF_INET
from socket import AF_INET6
from core.data import NodeData, LinkData
from core.enumerations import LinkTy... | 21,084 | 5,848 |
# 入力
N = int(input())
S, P = (
zip(*(
(s, int(p))
for s, p in (input().split() for _ in range(N))
)) if N else
((), ())
)
ans = '\n'.join(
str(i)
for _, _, i in sorted(
zip(
S,
P,
range(1, N + 1)
),
key=lambda t: (t[0], -t[... | 349 | 149 |
# External cracking script, part of https://github.com/mmmds/WirelessDiscoverCrackScan
import datetime
import subprocess
import os
### CONFIGURATION
HASHCAT_DIR = "C:\\hashcat-5.1.0"
HASHCAT_EXE = "hashcat64.exe"
LOG_FILE = "crack_log.txt"
DICT_DIR = "./dicts"
def load_dict_list():
for r,d,f in os.walk(DICT_DIR)... | 1,915 | 704 |
"""Copyright (c) 2010-2012 David Rio Vierra
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WA... | 46,013 | 14,286 |
# The MIT License (MIT)
#
# Copyright (c) 2016, Imperial College, London
#
# 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 t... | 5,200 | 1,528 |
"""
Keep track of which LBRY Files are downloading and store their LBRY File specific metadata
"""
import logging
import os
from twisted.enterprise import adbapi
from twisted.internet import defer, task, reactor
from twisted.python.failure import Failure
from lbrynet.reflector.reupload import reflect_stream
from lbr... | 13,463 | 4,124 |
import os
import sys
import re
import logging
p4_logger = logging.getLogger("Perforce")
# Import app specific utilities, maya opens scenes differently than nuke etc
# Are we in maya or nuke?
if re.match( "maya", os.path.basename( sys.executable ), re.I ):
p4_logger.info("Configuring for Maya")
from MayaU... | 623 | 212 |
#!/usr/bin/python3
#
# Copyright 2018 Google LLC
#
# 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 a... | 5,907 | 1,903 |
import json
import re
from django.conf import settings
import requests
from webui.exceptions import BadRequestException, UnauthorizedException, ServerErrorException, RedirectException, \
UnexpectedException, LocationHeaderNotFoundException, NotFoundException
def validate_response(response):
if 200 <= response... | 15,147 | 4,194 |
# Copyright 2021, Yahoo
# Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms
import time
from typing import Dict, List, Optional, Type
from pydantic import validate_arguments
from ...app_logger import AppLogger
from ...testplan import SystemState
from ...testplan.... | 8,305 | 2,166 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from vimeodl import __version__
from vimeodl.vimeo import VimeoLinkExtractor, VimeoDownloader
def test_version():
assert __version__ == '0.1.0'
def test_vimeo_link_extractor():
vm = VimeoLinkExtractor()
vm.extract()
| 277 | 108 |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import asyncio
import functools
import inspect
from contextlib import contextmanager
from typing import (
Any,
AsyncIterable,
Awaitable,
Callable,
Generic,
Iterator,
List,
Mapping,
Optional,
Sequence,... | 6,160 | 1,854 |
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([500, 500])
gameOn = True
x1 = 0
y1 = 100
x2 = 100
y2 = 0
while gameOn == True:
screen.fill([255,255,255])
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
... | 837 | 352 |
import numpy as np
import torch
import matplotlib.pyplot as plt
from torch import optim, nn
from pytorch.xor.multilayer_perceptron import MultilayerPerceptron
from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations
input_size = 2
output_size = len(set(LABELS))
num_hidd... | 3,198 | 1,180 |
import json
import mock
from django.core.urlresolvers import reverse
from pymongo.errors import ServerSelectionTimeoutError
from analytics.models import CourseReport
from core.common.mongo import c_onboarding_status, _conn
from core.common import onboarding
from ct.models import UnitLesson, StudentError
from ctms.t... | 8,157 | 2,689 |
# Django settings for signbank project.
import os
from signbank.settings.server_specific import *
from datetime import datetime
DEBUG = True
PROJECT_DIR = os.path.dirname(BASE_DIR)
MANAGERS = ADMINS
TIME_ZONE = 'Europe/Amsterdam'
LOCALE_PATHS = [BASE_DIR+'conf/locale']
# in the database, SITE_ID 1 is example.com
... | 8,934 | 2,968 |
"""
A module for all rook functionalities and abstractions.
This module has rook related classes, support for functionalities to work with
rook cluster. This works with assumptions that an OCP cluster is already
functional and proper configurations are made for interaction.
"""
import base64
import logging
import ran... | 50,042 | 15,814 |
# pylint: disable=line-too-long
r"""Default configs for COCO detection using DETR.
"""
# pylint: enable=line-too-long
import copy
import ml_collections
_COCO_TRAIN_SIZE = 118287
NUM_EPOCHS = 300
def get_config():
"""Returns the configuration for COCO detection using DETR."""
config = ml_collections.ConfigDict()... | 3,621 | 1,389 |
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
@pytest.fixture(scope="function")
def browser():
options = webdriver.ChromeOptions()
options.add_argument('ignore-certificate-errors')
options.add_argument("--headless")
options.add_argument('--no-san... | 581 | 165 |
from scale.dataset import read_mtx
from argparse import ArgumentParser
import pandas as pd
import numpy as np
import os
def parse_args():
parser = ArgumentParser('Preparing raw peaks from cicero pipeline')
parser.add_argument('--dataset_path', help='Path to Scale dataset: count, feature, barcode folder')
... | 2,105 | 703 |
from neo4jclient.AbsClient import AbstractClient
class CMSClient(AbstractClient):
def __init__(self, password, **kwargs):
super().__init__(password=password, **kwargs)
def get_domain_names(self):
"""
Gets all domain names from database.
:return: domain names in JSON-like form... | 2,335 | 699 |
import time
from datetime import date,datetime
from astral import LocationInfo
from astral.sun import sun
class CamLocation:
def __init__(self,lat,lon,info,country,timezone):
self.info = LocationInfo(info, country, timezone, lat, lon)
def is_night(self):
s = sun(self.info.observer, date=date.t... | 604 | 181 |
class Skidoo(object):
''' a mapping which claims to contain all keys, each with a value
of 23; item setting and deletion are no-ops; you can also call
an instance with arbitrary positional args, result is 23. '''
__metaclass__ = MetaInterfaceChecker
__implements__ = IMinimalMapping, ICallabl... | 545 | 165 |
import importlib
__all__ = ['mount_gdrive']
def mount_gdrive() -> str:
"""Mount Google Drive storage of the current Google account and return the root path.
Functionality only available in Google Colab Enviroment; otherwise, it raises a RuntimeError.
"""
if (importlib.util.find_spec("google.colab")... | 571 | 163 |
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import (
User,
)
from wasch.models import (
Appointment,
WashUser,
WashParameters,
# not models:
AppointmentError,
StatusRights,
)
from wasch import tvkutils, payment
class Wa... | 6,225 | 1,788 |
from typing import List
from collections import Counter
# class Solution:
# def isMajorityElement(self, nums: List[int], target: int) -> bool:
# d = Counter(nums)
# return d[target] > len(nums)//2
# class Solution:
# def isMajorityElement(self, nums: List[int], target: int) -> bool:
# ... | 1,040 | 338 |
"""
Advent of Code 2021 - Day 17
https://adventofcode.com/2021/day/17
"""
import re
from math import ceil, sqrt
from typing import List, Tuple
DAY = 17
FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt'
TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt'
def load_data(infile_path: str) -> Tuple[int,... | 2,018 | 873 |
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
Payload = Tuple[List['Literal'], 'Substitutions']
class Root:
def __init__(self):
self.children = set()
def notify(self, ground: 'Literal'):
for child in self.children:
child.not... | 4,235 | 1,288 |
import HandRankings as Hand
from deuces.deuces import Card, Evaluator
class GameData:
def __init__(self, name, opponent_name, stack_size, bb):
# match stats
self.name = name
self.opponent_name = opponent_name
self.starting_stack_size = int(stack_size)
self.num_hands = 0
... | 15,501 | 4,293 |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Todo(models.Model):
time_add = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=64)
detail = models.TextField(blank=True)
deadline = models.DateTimeField(blank=Tr... | 801 | 243 |
import os
from trame import change, update_state
from trame.layouts import SinglePageWithDrawer
from trame.html import vtk, vuetify, widgets
from vtkmodules.vtkCommonDataModel import vtkDataObject
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader
from ... | 20,377 | 6,164 |
# Copyright 1996-2021 Soft_illusion.
#
# 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 w... | 2,849 | 943 |
import mysql.connector
from mysql.connector import errorcode
config = {
'user': 'user',
'password': 'password',
'host': 'mysql_container',
'database': 'sample_db',
'port': '3306',
}
if __name__ == "__main__":
try:
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
... | 839 | 263 |
# criar um programa que pergunte as dimensões de uma parede, calcule sua área e informe quantos litros de tinta
# seriam necessários para a pintura, após perguntar o rendimento da tinta informado na lata
print('=' * 40)
print('{:^40}'.format('Assistente de pintura'))
print('=' * 40)
altura = float(input('Informe a al... | 920 | 332 |
from random import sample
from time import sleep
jogos = list()
print('-' * 20)
print(f'{"MEGA SENA":^20}')
print('-' * 20)
while True:
n = int(input("\nQuatos jogos você quer que eu sorteie? "))
if (n > 0):
break
print('\n[ERRO] Valor fora do intervalo')
print()
print('-=' * 3, e... | 591 | 269 |
from importlib import import_module
from unittest import TestCase as UnitTestCase
from django.contrib.auth.models import Group
from django.core.management import BaseCommand
from django.conf import settings
from django.test import TestCase
from django.views.generic import TemplateView
try:
from unittest.mock impor... | 49,475 | 15,654 |
'''
Favorite Files
Licensed under MIT
Copyright (c) 2012 Isaac Muse <isaacmuse@gmail.com>
'''
import sublime
import sublime_plugin
from os.path import join, exists, normpath
from favorites import Favorites
Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json'))
class Refresh:
dummy_f... | 13,892 | 3,703 |
from polyphony import testbench
def list03(x, y, z):
a = [1, 2, 3]
r0 = x
r1 = y
a[r0] = a[r1] + z
return a[r0]
@testbench
def test():
assert 4 == list03(0, 1 ,2)
assert 5 == list03(2, 1 ,3)
test()
| 229 | 118 |
#!/bin/env python3
from collections import Counter
from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
from django.db import models as dm
from django.shortcuts import get_object_or_404, render
from django.views.generic.list import BaseListView
from django.vie... | 4,361 | 1,402 |
from manimlib.constants import *
from manimlib.mobject.types.vectorized_mobject import VMobject
from manimlib.utils.config_ops import digest_config
from manimlib.utils.space_ops import get_norm
class ParametricCurve(VMobject):
CONFIG = {
"t_range": [0, 1, 0.1],
"min_samples": 10,
"epsilon"... | 2,313 | 804 |
#-*- coding: utf-8 -*-
#
# Copyright (c) 2012, ECSMate development team
# All rights reserved.
#
# ECSMate is distributed under the terms of the (new) BSD License.
# The full license can be found in 'LICENSE.txt'.
"""ECS SDK
"""
import time
import hmac
import base64
import hashlib
import urllib
import... | 9,704 | 3,145 |
# Copyright 2012 OpenStack Foundation.
# 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 req... | 4,002 | 1,154 |
"""
MIT License
Copyright (c) 2019 NinjaSnail1080
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, copy, modify, merge, publish... | 5,417 | 1,797 |
"""
create_ucs_sp_template.py
Purpose:
UCS Manager Create a UCS Service Profile Template
Author:
John McDonough (jomcdono@cisco.com) github: (@movinalot)
Cisco Systems, Inc.
"""
from ucsmsdk.ucshandle import UcsHandle
from ucsmsdk.mometa.ls.LsServer import LsServer
from ucsmsdk.mometa.org.OrgOrg import Or... | 765 | 329 |
# coding=utf-8
"""
Handles EPAB's config file
"""
import logging
import pathlib
import elib_config
CHANGELOG_DISABLE = elib_config.ConfigValueBool(
'changelog', 'disable', description='Disable changelog building', default=False
)
CHANGELOG_FILE_PATH = elib_config.ConfigValuePath(
'changelog', 'file_path', de... | 4,105 | 1,377 |
import os
import argparse
def check_for_pkg(pkg):
try:
exec("import " + pkg)
except:
os.system("pip3 install --user " + pkg)
def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoi... | 5,793 | 2,186 |
import os
import click
from flask import Flask
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
__version__ = (1, 0, 0, "dev")
db = SQLAlchemy()
def create_app(test_config=None):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__, instance_rel... | 1,835 | 591 |
import os, sys
fn = sys.argv[1]
if os.system('python compile.py %s __tmp.S' % fn) == 0:
os.system('python asm.py __tmp.S %s' % fn[:-2])
| 142 | 65 |
#!/usr/bin/env python
# coding: UTF-8
#
# @package Actor
# @author Ariadne Pinheiro
# @date 26/08/2020
#
# Actor class, which is the base class for Disease objects.
#
##
class Actor:
# Holds the value of the next "free" id.
__ID = 0
##
# Construct a new Actor object.
# - Sets the initial values of... | 3,806 | 1,189 |
"""Convert a Decimal Number to a Binary Number."""
def decimal_to_binary(num: int) -> str:
"""
Convert a Integer Decimal Number to a Binary Number as str.
>>> decimal_to_binary(0)
'0b0'
>>> decimal_to_binary(2)
'0b10'
>>> decimal_to_binary(7)
'0b111'
... | 1,516 | 490 |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import urllib.parse
import json
import base64
import requests
import logging
class Network():
LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li'
BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp'
COMMON_HERADERS = {
'Accept-Language': 'en-US',
... | 1,467 | 511 |
import libcst as cst
import libcst.matchers as m
from fixit import CstLintRule
from fixit import InvalidTestCase as Invalid
from fixit import ValidTestCase as Valid
class UseFstringRule(CstLintRule):
MESSAGE: str = (
"As mentioned in the [Contributing Guidelines]"
+ "(https://github.com/TheAlgori... | 1,725 | 533 |
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified).
__all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask']
# Cell
from typing import Dict, Tuple
from inspect import signature
import tensorflow as tf
import transform... | 15,634 | 4,570 |
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import math
from datetime import datetime
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.collections import LineCollection
from matplotlib import cm
from SiMon.simulation import Simulation
f... | 5,000 | 1,496 |
"""
Particle Size Models: Pure Oil Jet
===================================
Use the ``TAMOC`` `particle_size_models` module to simulate a laboratory
scale pure oil jet into water. This script demonstrates the typical steps
involved in using the `particle_size_models.PureJet` object, which requires
specification of all... | 3,700 | 1,278 |
import os.path
import tron.Misc
from tron import g, hub
from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder
from tron.Hub.Nub.SocketActorNub import SocketActorNub
from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder
name = 'hal'
def start(poller):
cfg = tron.Misc.cfg.get(g.... | 1,121 | 423 |
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Optional
from xsdata.models.datatype import XmlDate
@dataclass
class SizeType:
value: Optional[int] = field(
default=None,
metadata={
"required": True,
}
)
system: Optional[str] = fi... | 1,761 | 490 |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | 1,092 | 308 |
#!/usr/bin/python
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... | 7,392 | 2,081 |
"""https://en.cppreference.com/w/c/io
"""
from rbc import irutils
from llvmlite import ir
from rbc.targetinfo import TargetInfo
from numba.core import cgutils, extending
from numba.core import types as nb_types
from rbc.errors import NumbaTypeError # some errors are available for Numba >= 0.55
int32_t = ir.IntType(3... | 1,727 | 597 |
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert_file('README.md', 'rst', extra_args=())
except ImportError:
import codecs
long_description = codecs.open('README.md', encoding='utf-8').read()
long_description = '\n'.join(long_description.splitlines())
setup(
n... | 991 | 321 |
# The MIT License (MIT)
#
# Copyright (c) 2015 braindead
#
# 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, copy, modif... | 6,024 | 2,233 |
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import time
import datetime
from lib.common.out import *
from lib.common.objects import File
from lib.core.database import Database
from lib.core.investigation import __project__
class Session(ob... | 3,780 | 1,036 |
#coding: utf-8
import xlrd
from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument
from simple_report.xls.workbook import Workbook
from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS
class DocumentXLS(BaseDocument, SpreadsheetDocument):
"""
Обертка для отчетов в ... | 1,028 | 349 |
# Copyright 2019 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... | 3,810 | 1,139 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: cancel_build.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 google.protobu... | 4,796 | 1,795 |
'''
This is a sample class for a model. You may choose to use it as-is or make any changes to it.
This has been provided just to give you an idea of how to structure your model class.
'''
from openvino.inference_engine import IENetwork, IECore
import numpy as np
import os
import cv2
import sys
class Model_HeadPose:
... | 5,118 | 1,451 |
NAMES_SAML2_PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol"
NAMES_SAML2_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion"
NAMEID_FORMAT_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
... | 374 | 192 |
import math
def square(n):
tmp=round(math.sqrt(n))
if tmp*tmp==n:
return False
else:
return True
def semprime(n):
ch = 0
if square(n)==False:
return False
for i in range(2, int(math.sqrt(n)) + 1):
while n%i==0:
n//=i
ch+=1
if ch... | 833 | 315 |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='This repository hosts some work-in-progress experiments applying deep learning to predict age using tractometry data.',
author='Joanna Qiao',
license='BSD-3',
)
| 305 | 86 |
#!/usr/bin/env python3
import argparse
import os
import random
import requests
import sys
import tempfile
import uuid
from libs import colorprint
from libs.cli import run_command
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
# assume well-known lvm volume group on host
# ...later we'll figure out how to ... | 8,474 | 2,787 |
"""Criar uma função que retorne min e max de uma sequência numérica
aleatória.
Só pode usar if, comparações, recursão e funções que sejam de sua
autoria.
Se quiser usar laços também pode.
Deve informar via docstring qual é a complexidade de tempo e espaço da
sua solução
"""
from math import inf
def minimo_e_maxim... | 1,687 | 615 |
import dash_bootstrap_components as dbc
import dash_html_components as html
DBC_DOCS = (
"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/"
)
def make_subheading(label, link):
slug = label.replace(" ", "")
heading = html.H2(
html.Span(
[
label,... | 806 | 238 |
'''
The visualization class provides an easy access to some of the visdom functionalities
Accept as input a number that will be ploted over time or an image of type np.ndarray
'''
from visdom import Visdom
import numpy as np
import numbers
class VisdomLogger:
items_iterator = {}
items_to_visualize = {}
w... | 2,858 | 793 |
"""Analyze condition number of the network."""
import numpy as np
import matplotlib.pyplot as plt
# import model
def _get_sparse_mask(nx, ny, non, complex=False, nOR=50):
"""Generate a binary mask.
The mask will be of size (nx, ny)
For all the nx connections to each 1 of the ny units, only non connectio... | 2,683 | 1,273 |