content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import numpy as np
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button #, RadioButtons
import scipy.signal as ss
from binary_file_options import Ui_MainWindow
def get_raw_data_from_binary_file(fname,offset_samples,duration_samples,bit_de... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ve... | python |
from goolabs import GoolabsAPI
import time
def name_check(api_id, text_list):
"""固有表現抽出器で名前と判断された語のリストを取得
Parameters
----------
api_id : str
text_list : list[str]
ツイッターの文章のリスト
Returns
-------
name_list : list[str]
名前と判断された語(重複あり)
"""
n_list = ["鬼太郎", "ぬらりひょん",... | python |
from django.contrib import admin
from .models import HeaderCTA, BlogEmbeddedCTA
# Register your models here.
admin.site.register(HeaderCTA)
admin.site.register(BlogEmbeddedCTA) | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 21:08:15 2019
@author: Olivier
"""
#####prévoir le résultat avant d'exécuter le code#######
a=3
def test0():
"""None->None
affiche a, variable non déclarée dans la fonction"""
print("valeur de a dans test0",a)
test0() #attention, si a n... | python |
import socket
from unittest import TestCase
from tempfile import NamedTemporaryFile
from mock import patch, Mock
from oasislmf.utils.conf import load_ini_file, replace_in_file
from oasislmf.utils.exceptions import OasisException
class LoadInIFile(TestCase):
def test_values_are_bool___values_are_correctly_conve... | python |
n = int(input())
ratings = [int(input()) for _ in range(n)]
candies = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i-1]:
candies[i] = candies[i-1] + 1
#print (candies)
for i in reversed(range(1, n)):
if ratings[i] < ratings[i-1]:
candies[i-1] = max(candies[i-1], candies[i]+1)... | python |
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
VERSION = '2.0.1'
setup(
name='usabilla-api',
version=VERSION,
description="Python client for Usabilla API",
license='MIT',
install_requires=['urllib3', 'requests'],
packages=find_pack... | python |
import os
from shutil import copyfile
import lxml.etree as etree
os.chdir("../")
operating_system = 'Linux'
target_level_path = '../level_variations/generated_levels/fourth generation'
origin_level_path = '../buildgame/{}/9001_Data/StreamingAssets/Levels/novelty_level_1/type1/Levels/'.format(operating_system)
game_lev... | python |
from random import randint
number = randint(1, 100)
print("Guess a number between 1 and 100")
#print(number)
while True:
guess = int(input("Enter guess:"))
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
break
print("Correct!") | python |
# DESCRIPTION
# You are a product manager and currently leading a team to develop a new product.
# Unfortunately, the latest version of your product fails the quality check.
# Since each version is developed based on the previous version, all the versions after a bad version are also bad.
# Suppose you have n versions ... | python |
"""
Description: This script calibrate result from LP solution.
Probablistically select ASYMPs.
Then, compute metric features from those.
"""
from utils.networkx_operations import *
from utils.pandas_operations import *
from utils.time_operations import *
from tqdm import tqdm
import pandas as pd
import numpy as np
im... | python |
import rubrik_cdm
rubrik = rubrik_cdm.Connect()
username = "python-sdk-read-only"
read_only_permission = rubrik.read_only_authorization(username)
| python |
import torch
import torch.nn as nn
import numpy as np
class AttentionGate(nn.Module):
def __init__(self, x_ch, g_ch, mid_ch, scale):
super(AttentionGate, self).__init__()
self.scale = scale
self.conv_g = nn.Conv2d(in_channels=g_ch, out_channels=mid_ch, kernel_size=1, bias=True)
sel... | python |
"""
Loader and Parser for the txt format.
Version: 0.01-beta
"""
from konbata.Data.Data import DataNode, DataTree
from konbata.Formats.Format import Format
def txt_toTree(file, delimiter=None, options=None):
"""
Function transforms a txt file into a DataTree.
Parameters
----------
file... | python |
from __future__ import print_function
from recon.core.module import BaseModule
import os
import subprocess
from libs.pentestlymodule import PentestlyModule
from libs.misc import parse_mimikatz, Colors
class Module(PentestlyModule):
meta = {
'name': 'Execute Mimikatz',
'author': 'Cory Duplantis (... | python |
if __name__ == "__main__":
if __package__ is None:
# add parent dir to allow relative import
from pathlib import Path
import sys
top = Path(__file__).resolve().parents[1]
sys.path.append(str(top))
# PEP 0366
__package__ = "lvscharts"
__import__(__pa... | python |
from .toolbar_controller import ToolbarController
| python |
from unittest import TestCase
import unittest
from rengine.config import TIME_BASED_CONDITIONS, ExerciseType, MuscleGroup
from rengine.exercises import pick_random_exercise
import dataframe_image as dfi
from rengine.workouts import AutoGeneratedWorkout, BaseWorkout, LowerBodyWorkout, UpperBodyWorkout, dictionary_additi... | python |
from sklearn.linear_model import RidgeClassifierCV, RidgeClassifier
from eye_detector.train.models.find import find_params
from eye_detector.train.models.decorator import ModelDecorator
def ridge(x, y, shape):
grid = RidgeClassifierCV(alphas=[1e-3, 1e-2, 1e-1, 1])
alpha = find_params(grid, x, y, attr="alpha_"... | python |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import pandas as pd
import plotly.graph_objects as go
import numpy as np
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"... | python |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RStatnetCommon(RPackage):
"""Non-statistical utilities used by the software developed by t... | python |
# Grupo: Gabriel Macaúbas Melo, Louise Fernandes Caetano, Maria Eduarda de Almeida Vitorino e Fernando Luiz Castro Seixas
# Importando Funções
from functions import *
# Programa Principal
num = iniciar()
cartelas = criar_cartela(num)
sorteio(cartelas)
| python |
import os
from sklearn import datasets
import xgboost as xgb
from xgboost_ray import RayDMatrix, predict
import numpy as np
def main():
if not os.path.exists("simple.xgb"):
raise ValueError(f"Model file not found: `simple.xgb`"
f"\nFIX THIS by running `python `simple.py` first ... | python |
# FP involving global variables modified in a different scope
i = 0
def update_i():
global i
i = i + 1
update_i()
if i > 0:
print("i is greater than 0") # FP: This is reachable
| python |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from functools import wraps
from common import Logging
from common.Logging import get_generic_logger
from common.YamlConfig import AppConfig
from lib.bottle import Bottle, request, response
from ..AppRunner import AppRunner
from ..RemoteServerApi import get_server_config, ge... | python |
# utils
from .rfb_utils import object_utils
from .rfb_utils import transform_utils
from .rfb_utils import texture_utils
from .rfb_utils import scene_utils
from .rfb_utils import shadergraph_utils
from .rfb_logger import rfb_log
from .rman_sg_nodes.rman_sg_lightfilter import RmanSgLightFilter
from . import rman_consta... | python |
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
#TODO1: Create the turtle and move it with keypress
player = Player()
screen.listen()
screen.onkey(player.go_up... | python |
s = list(input('Escriba el string: '))
s[0] = s[0].upper()
print(''.join(s))
| python |
# -*- coding: utf-8 -*-
"""Charge logging script
This script will download the get_vehicle_status every 5 minutes
and log them locally. Based on the Charge Off-Peak script.
This script is independent from visualization script in order to run it on different computers
"""
import jlrpy
import threading
import datetim... | python |
from time import sleep
from jumpscale import j
from .VirtualboxClient import VirtualboxClient
JSBASE = j.application.jsbase_get_class()
class VirtualboxFactory(JSBASE):
def __init__(self):
self.__jslocation__ = "j.clients.virtualbox"
JSBASE.__init__(self)
self.logger_enable()
s... | python |
from PIL import ImageFont
class Letter:
""" letter class- each letter is one of these objects, and is rendered in order. """
def __init__(self,char,size,font,color = (255,255,255,255),b=False,i=False,u=False):
"""
char: character.
size: size of letter.
font: PIL truetype font obj... | python |
#TODO: Add datadump | python |
# -*- coding: utf-8 -*-
from . import helpers
import os
import shutil
import json
import logging
import sys
import face_recognition
from ringFace.ringUtils import commons
def processUnencoded(imageDir):
"""
Processes any unencoded image in the new-images subdir of a person, and moves it into encoded-ima... | python |
from os import path
import click
from glob import glob
from pathlib import Path
from app.newAnimeEpisodes import *
@click.command()
@click.option('--source', required=True, type=str, help='Enter absolute path of directory to move from')
@click.option('--destination', required=True, type=str, help='Enter absolute path ... | python |
""" A test action set. """
# Enthought library imports.
from envisage.ui.action.api import Action, Group, Menu, ToolBar
from envisage.ui.workbench.api import WorkbenchActionSet
class TestActionSet(WorkbenchActionSet):
""" An action test useful for testing. """
#### 'ActionSet' interface ###################... | python |
"""This module provide the builder for the zlib library."""
import logging
from nvp.components.build import BuildManager
from nvp.nvp_builder import NVPBuilder
logger = logging.getLogger(__name__)
def register_builder(bman: BuildManager):
"""Register the build function"""
bman.register_builder('zlib', Bui... | python |
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animale_array(xm,fname,lbls=None,cmap='gray',figsize=(7,7),fps=25,vmin=None,vmax=None):
'''
This function helps to make an animation from a (2+1+1)d array (xy+t+c)
'''
# from IPy... | python |
import asyncio
import json
import logging
import random
import time
import uuid
import websockets
from common import Client, ClientReport, OffsetTransform, Position, Rotation
logging.basicConfig(level=logging.INFO)
TIME_BETWEEN_UPDATES = 0.0166
LOW_POSITION = -3.0
HIGH_POSITION = 3.0
LOW_ROTATION = 0.0
HIGH_ROTATION... | python |
import logging
import os
from pathlib import Path
from flatpaksync.commands.command import command
from flatpaksync.configs.write import write as writeconfig
from flatpaksync.structs.app import app
from flatpaksync.structs.settings import settings
from flatpaksync.actions.app import app as appaction
from flatpaksync.... | python |
"""generatedata
Function that collects the transmutation data and
prepares the transmutation matrix required for depletion or decay
calculations.
The following reactions are considered:
- Radiative capture
- Capture to ground state
- Capture to metastable
- n, 2n
- n, 3n
- Fission
- n, alp... | python |
import pandas as pd
from sklearn.metrics import r2_score
from sklearn.svm import SVR
MAX_AGE = 71
MAX_PCLASS = 3
def process_df(df):
df = df[['pclass', 'survived', 'age', 'sex']]
df = df.dropna()
df['pclass'] = df['pclass'].map(lambda x: float(x[:-2]) / MAX_PCLASS) # drop sufix
df['age'] = df['age... | python |
import datetime
import calendar
from posixpath import dirname
import os
import pytz
import lockfile
import pycountry
import geoip2.errors
from flask.ext.babel import lazy_gettext
from flask import url_for
from flask.helpers import find_package
import rfk
def now():
return pytz.utc.localize(datetime.datetime.... | python |
from typing import List, Iterator, Dict
from pyot.conf.model import models
from pyot.core.functional import cache_indexes, lazy_property
from pyot.core.exceptions import NotFound
from pyot.utils.tft.cdragon import abs_url, join_set_data
from pyot.utils.lol.cdragon import sanitize
from .base import PyotCore, PyotStatic... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Authors: Olexa Bilaniuk
# Imports.
import sys; sys.path += [".", ".."]
import argparse as Ap
import logging as L
import numpy as np
import os, pdb, sys
import time
import tensorflow.c... | python |
from django.db import models
from django_handleref.models import HandleRefModel
class Org(HandleRefModel):
name = models.CharField(max_length=255, unique=True)
website = models.URLField(blank=True)
notes = models.TextField(blank=True)
class HandleRef:
tag = 'org'
delete_cascade = ["s... | python |
import os
import pickle
import yaml
import numpy as np
import pandas as pd
import pyprind
from stats.plot_utils import get_dn_rn_info, load_best_rl
from stats.thresholds import th
rng = np.random.RandomState(123)
ROOT_DIR = os.path.abspath(".")
RAW = False # True == num patients ; False == percentage
# Make plots d... | python |
from setuptools import setup, find_packages
with open("requirements.txt") as f:
install_requires = f.read().strip().split("\n")
# get version from __version__ variable in erptn/__init__.py
from erptn import __version__ as version
setup(
name="erptn",
version=version,
description="adaption of erpnext in the tunis... | python |
# Generated by Django 3.2.3 on 2021-08-12 05:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20210811_1941'),
]
operations = [
migrations.RenameField(
model_name='vehicle',
old_name='size',
... | python |
num = int(input('Insira um número: '))
if num % 3 == 0:
print(f'O número {num} é divisível por 3.')
else:
print(f'O número {num} não é divisível por 3.')
if num % 7 == 0:
print(f'O número {num} é divisível por 7.')
else:
print(f'O número {num} não é divisível por 7.')
| python |
from flask import Flask, render_template, url_for
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '23630345ae74e203656e76a7cab735a7'
posts = [
{
'author': 'Name',
'title': 'Blog post 1',
'content': 'First blog post',
'date_posted': 'A... | python |
import time
import fitlog
def random_tmp_name():
#random is useless for seed has been fixed
a = (time.time() * 1000) % 19260817
return "tmp_%d.txt" % a
| python |
import numpy as np
import myrand
import scipy.stats
import sys
import random
import pytest
class TestRandoms( ):
@classmethod
@pytest.fixture(scope="class")
def setUpClass(cls):
print("Doing setUpClass")
cls.numVals = 10000
#print(vars(self))
#print(self)
@pytest.fixtu... | python |
"""Proxy objects for sending commands to transports"""
import logging
# We need to offset the pin numbers to CR and LF which are control characters to us
# NOTE: this *must* be same as in ardubus.h
# TODO: Use hex encoded values everywhere to avoid this
IDX_OFFSET = 32
LOGGER = logging.getLogger(__name__)
def idx2by... | python |
import numpy as np
import itertools as itr
import os as os
import sys as sys
import matplotlib.pyplot as plt
class GridTopology:
r"""
Control the layout/connectivity of the lattice the models are based on.
This can be used as a parent class for other topologies.
Here sites are assigned unique indice... | python |
# -*- coding: utf-8 -*-
import unittest
from mcfly.models import DeepConvLSTM
from test_modelgen import get_default
class DeepConvLSTMSuite(unittest.TestCase):
"""
Tests cases for DeepconvLSTM models.
"""
def test_deepconvlstm_batchnorm_dim(self):
"""The output shape of the batchnorm should be... | python |
from collections import namedtuple
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial.distance import cosine
import scipy.optimize as opt
__all__ = ['CPTC... | python |
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord
from imephu.annotation.general import CircleAnnotation, RectangleAnnotation
from imephu.finder_chart import FinderChart
def test_rectangle_annotation(fits_file, check_finder):
"""Test rectangle annotations."""
finder_chart ... | python |
#!/usr/bin/env python
# This file should be available from
# http://www.pobox.com/~asl2/software/Pinefs
# and is licensed under the X Consortium license:
# Copyright (c) 2003, Aaron S. Lav, asl2@pobox.com
# All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this ... | python |
#!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from std_msgs.msg import Float64MultiArray, UInt8
from std_srvs.srv import Trigger, TriggerResponse
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from scipy import optimize
import time
class linear_controller(object):
... | python |
#!/bin/python
import datetime
YAHOO_ENDPOINT = 'https://fantasysports.yahooapis.com/fantasy/v2'
class YHandler:
"""Class that constructs the APIs to send to Yahoo"""
def __init__(self, sc):
self.sc = sc
def __getattribute__(self, attr):
cred = super(YHandler, self).__getattribute__(att... | python |
#!/usr/bin/env python3
import os
import time
import math
import atexit
import numpy as np
import threading
import random
import cereal.messaging as messaging
import argparse
from common.params import Params
from common.realtime import Ratekeeper
import queue
import requests
import cereal.messaging.messaging_pyx as mess... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('... | python |
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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... | python |
# -*- coding: utf-8 -*-
# Licensed to Anthony Shaw (anthonyshaw@apache.org) 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 "Li... | python |
from datetime import datetime
from caselawclient.Client import api_client
from requests_toolbelt.multipart import decoder
from .models import SearchResults
def format_date(date):
if date == "" or date is None:
return None
time = datetime.strptime(date, "%Y-%m-%d")
return time.strftime("%d-%m-%Y... | python |
""" https://adventofcode.com/2018/day/6 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
lines = [line[:-1].split(", ") for line in f.readlines()]
return [Point(int(line[0]), int(line[1])) for line in lines]
class Point:
n = 0
def __init__(self, x, y):
... | python |
import os
from helpers import dist_init, getData, getLossFun, getModel
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.optim as optim
import fairscale
from fairscale.nn.model_parallel import initialize_model_parallel
DEVICE = "cuda" if torch.cuda.is_available() else "cpu... | python |
###############################################################################
# Copyright (c) 2021, Milan Neubert (milan.neuber@gmail.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. ... | python |
from typing import Optional
from datetime import datetime
BETFAIR_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)
# will attempt to use C/Rust libraries if installed
try:
import orjson as json
except ImportError:
import json
try:
imp... | python |
from random import random
from matplotlib import pyplot as plt
import numpy as np
def discrete(a):
t = sum(a)*random()
subtotal = 0.0
for j in range(len(a)):
subtotal += a[j]
if subtotal > t:
return j
def tabler():
n, *m = map(int, input().split(' '))
... | python |
import pygame as pg
import sys
import time
from pygame.locals import *
# Setting up few properties
XO = 'x'
winner = None
draw = None
width = 500
height = 450
white = (255, 255, 255)
line_color = (130, 0, 0)
board = [[None]*3, [None]*3, [None]*3]
pg.init()
fps = 30
CLOCK = pg.time.Clock()
screen = pg.display.s... | python |
import os
from datetime import timedelta
DEBUG = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
PROPAGATE_EXCEPTIONS = True
JWT_BLACK_LIST_ENABLED = True
UPLOADED_IMAGES_DEST = os.path.join("static", "images")
JWT_BLACK_LIST_TOKEN_CHECKS = ["access", "refresh"]
JWT_SECRET_KEY = os.environ["JWT_SECRET_KEY"]
JWT_ACCESS_TOK... | python |
import os
from tqdm import tqdm
import subprocess
def alphafold(path):
# run alphafold
print("Running for path {}...".format(path))
subprocess.run(['bash', '/opt/alphafold/run.sh', '-d /lambda_stor/data/hsyoo/AlphaFoldData',
'-o ~/mutate_msa/folding_results/',
'-f {... | python |
# -*- coding: utf-8 -*-
import unittest
import random
from pygorithm.data_structures import (
stack,
queue,
linked_list,
tree,
graph,
heap,
trie,
quadtree,
)
from pygorithm.geometry import vector2, rect2
class TestStack(unittest.TestCase):
def test_stack(self):
myStack = ... | python |
# coding: utf-8
# # Projects markdown generator for academicpages
#
# Takes a TSV of projects with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook, with the core python code in projects.py. Run either from the `markdown_generator` fo... | python |
from six.moves.urllib.parse import urljoin
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.ex... | python |
import click
from django.conf import settings
from django.contrib.sites.models import Site
def setup_current_site(site_name=None, domain=None):
'''
Sets up the user with the current site.
'''
site_id = settings.SITE_ID
click.secho('\nA site has not been configured for this CMS. Please answer the q... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/12 17:00
# @Author : Iydon
# @File : matlab.py
# `matlab -nodesktop' -> `from matlab import *'
# tic, toc, disp
import time
def tic(): globals()['TIC+TIME'] = time.time()
toc = lambda :time.time()-globals()['TIC+TIME']
disp = print
tic()
# numpy
i... | python |
import base64
import numpy as np
import os
import pathlib
import re
import shutil
from urllib.request import urlopen
raw = urlopen("https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Algorithm.QCAlgorithm").read().decode("utf-8") \
.replace("true", "True") \
.replace("false", "False") \
.r... | python |
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn as sns
import pandas as pd
import numpy as np
import math
import os
from scipy.cluster.hierarchy import dendrogram
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap
from matp... | python |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#data_file='file.csv' # path for the file
data=np.genfromtxt(path, delimiter=",", skip_header=1)
#print("\nData: \n\n", data)
#print("\nType of data: \n\n", type(data))
#New record
new... | python |
# -*- coding: utf-8 -*-
import pandas as pd
import requests
from zvdata.api import df_to_db
from zvdata.recorder import Recorder
from zvt.api.common import china_stock_code_to_id
from zvt.api.quote import get_entities
from zvt.domain import StockIndex, StockCategory
from zvt.domain.stock_meta import Index
from zvdata.... | python |
import json
import re
import string
try: # ST3
from .elm_plugin import *
from .elm_project import ElmProject
except: # ST2
from elm_plugin import *
from elm_project import ElmProject
default_exec = import_module('Default.exec')
@replace_base_class('Highlight Build Errors.HighlightBuildErrors.Exec... | python |
import numpy as np
import matplotlib.pyplot as plt
def get_steps_colors(values):
values = 1 / values
_range = np.max(values) - np.min(values)
_values = (values - np.min(values)) / _range
colors_data = plt.cm.Wistia(_values)
return colors_data
def paint_table(df, title_cols, title_text, result_pa... | python |
import binascii
import logging
from lbrynet.core.cryptoutils import get_lbry_hash_obj, verify_signature
from twisted.internet import defer, threads
from lbrynet.core.Error import DuplicateStreamHashError, InvalidStreamDescriptorError
from lbrynet.lbrylive.LiveBlob import LiveBlobInfo
from lbrynet.interfaces import IStr... | python |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JdZhilianItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
companyname = scrapy.Field()
jobl... | python |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from django_plotly_dash import DjangoDash
import dash_table
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import plotly.express as px
import random
import json
... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Lien(pulumi.CustomResource):
def __init__(__self__, __n... | python |
from glob import glob
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def main():
file = "./cpp/tests/bin/Distribution_bucket_0_15_08_2021.dat"
df = pd.read_csv(
file, delim_whitespace=True, header=None, names=["id", "x", "px", "y", "py", "t", "delta"]
)
df["turn"]... | python |
dividendo=int(input("Dividendo es: "))
divisor=int(input("Divisor es: "))
if dividendo>0 and divisor>0:
coc=0
residuo=dividendo
while (residuo>=divisor):
residuo-=divisor
coc+=1
print(residuo)
print(coc) | python |
from __future__ import unicode_literals
from sideboard.lib import mainloop
if __name__ == '__main__':
mainloop()
| python |
import json
from helper import OuraModel, from_json
class UserInfo(OuraModel):
_KEYS = ['age', 'weight', 'gender', 'email']
if __name__ == '__main__':
test = """
{
"age": 27,
"weight": 80,
"email": "john.doe@the.domain",
"surprise" : "wow this is new"
}"""
u = from_json(test, UserInfo)
... | python |
# Date: 05/10/2018
# Author: Pure-L0G1C
# Description: Wrapper for gimme object
from .gimme import Gimme
class Wrapper(object):
def __init__(self, kwargs):
self.gimme = Gimme(kwargs)
@property
def start(self):
self.gimme.start()
@property
def stop(self):
self.gimme.stop()
@property
def get(self):
... | python |
def implode(lst):
s = ""
for e in lst:
s = s+e
return s
print(implode(['h', 'e', 'l', 'l', 'o']))
| python |
# Generated by Django 3.2.3 on 2021-05-21 21:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cities', '0002_phone'),
]
operations = [
migrations.RenameField(
model_name='phone',
old_name='phone_model',
new... | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
import warnings
import shutil
import json
import tests.test_helpers as th
import submission_validator
class TestSubmissionValidatorValidateDetections(th.ExtendedTestCase):
def test_errors_for_missing_label_probs(s... | python |
import requests
use_paragraphs = True
def main():
url = "http://0.0.0.0:8100/model"
if use_paragraphs:
request_data = [
{
"human_sentences": ["Who played Sheldon Cooper in The Big Bang Theory?"],
"dialog_history": ["Who played Sheldon Cooper in The Big Bang... | python |
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import platform
from subprocess import run
def is_macos():
"""
:return: True if system is MacOS, False otherwise
"""
return platform.system() == 'Darwin'
def is_windows():
"""
:return: True if system is Windows, False otherwise
... | python |
from django.db import models
# Create your models here.
class SigninModel(models.Model):
username = models.CharField(max_length=10)
password = models.CharField(max_length=50)
class BookTicketModel(models.Model):
post = models.CharField(max_length=10)
class AdjustTicketModel(models.Model):
post = mode... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.