content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import requests
import re
class MyCrawler:
def __init__(self, filename):
self.filename = filename
self.headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Mobile Safari/537.36'
}
def ... | python |
'''
The purpose of this package is to provide asynchronous variants of
the builtin `input` and `print` functions. `print` is known to be
relatively slow compared to other operations. `input` is even slower
because it has to wait for user input. While these slow IO
operations are being ran, code using `asyncio` should b... | python |
'''
Banner endpoint handler (defined in swagger.yaml)
'''
from app import metrics
import os
from PIL import Image,ImageFilter
import subprocess
from dataclasses import dataclass
import logging
from connexion.lifecycle import ConnexionResponse
from connexion import NoContent
from prometheus_client import Counter
from ... | python |
#!/usr/bin/env python
# Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module is responsible for the management of the sumo simulation. """... | python |
import os
import httpx
CAST_SERVICE_HOST_URL = 'http://localhost:8002/api/v1/casts/'
url = os.environ.get('CAST_SERVICE_HOST_URL') or CAST_SERVICE_HOST_URL
def is_cast_present(cast_id: int):
r = httpx.get(f'{url}{cast_id}')
return True if r.status_code == 200 else False | python |
# Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2013 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above... | python |
from urllib.parse import urljoin
from scrapy import Request
from product_spider.items import RawData
from product_spider.utils.spider_mixin import BaseSpider
class AcanthusSpider(BaseSpider):
name = "acanthus"
allowd_domains = ["acanthusresearch.com"]
start_urls = ["http://acanthusresearch.com/products/... | python |
import sys
import shlex
sys.path.append('..')
bamsnap_prog = "src/bamsnap.py"
from src import bamsnap
# import bamsnap
# bamsnap_prog = "bamsnap"
cmdlist = []
cmdlist.append("""
-bam ./data/test_SV1_softclipped_1.bam \
-title "Clipped read" \
-pos chr1:37775740 chr1:37775780 chr1:37775783 chr1:3777578... | python |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... | python |
# Copyright (c) 2010 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable la... | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# ----------------------------------------------------------------------------
# Port Scanner
# Copyright (c) 2015 brainelectronics.de
# Scharpf, Jonas
#
# All rights reserved.
#
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRE... | python |
from unittest import TestCase
from approvaltests import approvals
class TestSubdirectories(TestCase):
def test_subdirectory(self) -> None:
approvals.verify("xxx")
| python |
import isdhic
import numpy as np
from isdhic import utils
from isdhic.core import take_time
from isdhic.model import Likelihood
from scipy import optimize
from test_params import random_pairs
class Logistic(isdhic.Logistic):
"""Logistic
Python implementation of Logistic likelihood.
"""
def log_prob... | python |
import os
import numpy as np
from PIL import Image
# import util
import cv2
import random
import torchvision.transforms as transforms
import torch
import torch.utils.data
import pyclipper
import Polygon as plg
from yacs.config import CfgNode as CN
from .bounding_box import BoxList
# from __main__ import op... | python |
# TODO: set first card in the pile
# Check for illegal move on the client side itself.
from Cards import Card, cards
import random
class Game:
def __init__(self, id):
# Which player's turn is it? Initially player 1
self.turn = 0
# Are both players connected?
self.ready = False
# game ID
sel... | python |
import sys, os
from tqdm import tqdm
import numpy as np
import sys, os
sys.path.append('../')
from torch.utils.data import Dataset
import pandas as pd
from hateXplain.Preprocess.dataCollect import collect_data,set_name
from sklearn.model_selection import train_test_split
from os import path
from gensim.models import Ke... | python |
#!/usr/bin/env python
segments = 200
r = 30000
for x in range(-r/2, r/2, r / segments):
if x < -r/4 or x > r/4:
y = r / 2
else:
y = -r / 2
print(str(x) + " " + str(y)) | python |
def func(*args, **kwargs):
print(args)
print(kwargs)
idade = kwargs.get('idade')
if idade != None:
print(idade)
else:
print('Não foi possível encontrar a idade.')
lista = [1, 2, 3, 4, 5]
lista2 = [10, 20, 30, 40, 50]
func(*lista, *lista2, nome='Luiz', sobrenome = 'Miranda')
| python |
import discord
import datetime
import random
import os
import re
import sys
import time
import asyncio
import json
import hashlib
import sqlite3
import struct
from urllib.request import *
from urllib.error import *
current_time_min = lambda: int(round(time.time() / 60))
SELF_BOT_MEMBER = None
SELF_BOT_SERVER = None
db... | python |
"""
Ibutsu API
A system to store and query test results # noqa: E501
The version of the OpenAPI document: 1.13.4
Generated by: https://openapi-generator.tech
"""
import unittest
import ibutsu_client
from ibutsu_client.api.login_api import LoginApi # noqa: E501
class TestLoginApi(unittest.TestCa... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-01 17:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_auto_20161128_0904'),
]
operations = [
migrations.AddField(
... | python |
from testwatch.report import Report
def report_to_tsv(report: Report) -> str:
rows: list[tuple[str, str, str]] = []
start_row = ("start", str(report.start_time), str(report.start_time))
rows.append(start_row)
for task in report.tasks:
task_row = (task.name, str(task.start_time), str(task.end... | python |
# Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license.
# See LICENSE.txt in the project root for license information
from setuptools import setup
setup(
name='dfx-apiv2-client',
version='0.8.0',
packages=['dfx_apiv2_client'],
install_requires=[
'aiohttp[speedups]',
... | python |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsFieldValidator.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""... | python |
from flask import abort, Flask, jsonify, request
from flask_restful import Resource, Api
from translation_engine import decode, encode
app = Flask(__name__)
api = Api(app)
class Encoder(Resource):
def post(self):
if not request.json or not 'message' in request.json:
abort(400)
msg = ... | python |
from neural_network import neural_network
import numpy as np
from sklearn import preprocessing
from sklearn.datasets import fetch_mldata
# Retrieve MNIST data and prep valid/test set
size_training_data = 5500
size_validation_data = 500
mnist = fetch_mldata('MNIST original')
input_data = preprocessing.scale(np.c_[mnist... | python |
from django.db import models
from transactions import constant
class Transaction(models.Model):
transaction_id = models.IntegerField(unique=True)
brief_description = models.CharField(max_length=255, null=False)
description = models.CharField(max_length=255)
amount = models.FloatField(default=0.0)
... | python |
class NonGameScreen:
def __init__(self, screen):
self.screen = screen
def draw_text(self, text, font, color, cntr):
phrase = font.render(text, 0, color)
phrase_rect = phrase.get_rect(center=cntr)
self.screen.blit(phrase, phrase_rect)
| python |
while True:
n = int(input())
if n == 0:
break
cards = []
for i in range(n):
cards.append(i + 1)
discarded_cards = []
while len(cards) > 1:
x = cards.pop(0)
y = cards.pop(0)
discarded_cards.append(x)
cards.append(y)
print("Disca... | python |
import random
import pytest
from app.utils import graph as m
from tests.utils.utils import random_lower_string
class TestYmirNode:
def test_create_ymir_node(self):
d = {
"id": random.randint(1000, 2000),
"name": random_lower_string(10),
"hash": random_lower_string(10)... | python |
import unittest
import os
from simian.config import Configuration
class ConfigTest(unittest.TestCase):
def setUp(self):
dirname = os.path.dirname(__file__)
self.config_file_path = os.path.join(dirname, 'config/config.ini')
self.config = Configuration(self.config_file_path)
self.tes... | python |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import logging
import socket
from typing import Dict, Tuple, List, Union
from volatility.framework import exceptions
from volatilit... | python |
from datetime import datetime
import json
from typing import Type
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, or_, and_, inspect, Table, MetaData, Column
from iupdatable.util.weixin.models import Article
from iupdatable import Sta... | python |
# coding: utf-8
##############################################################################
# Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries.
#
# Subject to your compliance with these terms, you may use Microchip software
# and any derivatives exclusively with Microchip products. It is your
# resp... | python |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Script name: ShpToZip
#
# Description: A Python module to automate the conversion of .shp files to .zip
# archives.
#
# Shp_to_Zip_README file includes the following information:
# Projec... | python |
'''
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The n... | python |
import urllib
import time
import urllib.request
import json
from src.games.player import Player
import numpy as np
from src.config import *
class ReversiRandomPlayer(Player):
"""
随机AI
"""
def play(self, board):
legal_moves_np = self.game.get_legal_moves(1, board) # 获取可行动的位置
legal_mov... | python |
import numpy as np
def assert_array_shape(a, ndim=None, shape=None, dims={}):
if not type(a) is np.ndarray:
raise TypeError("Provided object type (%s) is not nunpy.array." % str(type(a)))
if ndim is not None:
if not a.ndim == ndim:
raise ValueError("Provided array dimensions (... | python |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'new/(?P<item_id>[\d]+)/$', 'reviewclone.views.create_review',
name='create_review'),
url(r'relations/$', 'reviewclone.views.relations_list',
name='relations'),
url(r'relations/new/$', 'reviewclone.views.create_relati... | python |
from typing import Any, Optional
from pydantic import BaseModel, StrictBool, validator
from app.db.session import Base
class UserBase(BaseModel):
username: str
profile: str
email: str
disabled: StrictBool = False
class UserCreate(UserBase):
password: str
@validator("username")
def val... | python |
def palindrome (kata, h, z):
if h == z//2 :
return 'Yes, it is a palindrome'
elif z % 2 == 0:
if kata[z//2 - h - 1] == kata[z//2 + h]:
return palindrome (kata, h + 1, z)
else:
return 'No, it is not a palindrome'
else:
if kata[z//2 - h - 1] == kata[z//2... | python |
import subprocess
import json
import time
import urllib.request
import os
pem="scripts/Vertx.pem"
jar_file="target/WebChatVertxMaven-0.1.0-fat.jar"
groupName="VertxCluster"
count=1
def url_is_alive(dns):
"""
Checks that a given URL is reachable.
:param url: A URL
:rtype: bool
"""
request = url... | python |
from django.core.urlresolvers import reverse_lazy
from django.utils.text import slugify
def generate_article_link(title, url=None):
if url is None:
url = reverse_lazy('article-detail', kwargs={'slug': slugify(title)})
return "[{0}]({1})".format(title, url)
| python |
#!/usr/bin/env python3
"""
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
Algorithm class: Convert a ProjectScene from one type to another.
"""
from copy import deepcopy
fro... | python |
# From http://www.scipy-lectures.org/intro/scipy.html#finding-the-minimum-of-a-scalar-function
from scipy import optimize
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 + 10 * np.sin(x)
x = np.arange(-10, 10, 0.1)
plt.plot(x, f(x))
plt.show()
result = optimize.minimize(f, x0=0)
print... | python |
import planckStyle as s
from pylab import *
g=s.getSinglePlotter()
roots = ['base_omegak_planck_lowl_lowLike_highL','base_omegak_planck_lowl_lowLike_highL_lensing','base_omegak_planck_lowl_lowLike_highL_lensing_post_BAO']
params = g.get_param_array(roots[0], ['omegam', 'omegal', 'H0'])
g.setAxes(params, lims=[0, 1,... | python |
# coding: utf-8
import logging
from marshmallow import Schema, fields, pre_load, post_dump, validate, ValidationError
from src.exceptions import InvalidUsage
from flask import jsonify
import json
class LoginSchema(Schema):
email = fields.Email(required=True)
password = fields.Str(load_only=True, validate=vali... | python |
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import *
from django.conf import settings
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from rest_framework import viewsets
from .serializers import *
class ReactTemplateView(TemplateView)... | python |
import datetime
import cloudscraper
import colorama
from termcolor import colored
import time
import json
import random
import pickle
from cryptography import fernet
import os
import bs4
import sys
import shutil
import requests, uuid, hashlib, hmac, urllib, string
from pathlib import Path
from colorama i... | python |
import floobits
# code run after our own by other plugins can not pollute the floobits namespace
__globals = globals()
for k, v in floobits.__dict__.items():
__globals[k] = v
# Vim essentially runs python by concating the python string into a single python file and running it.
# Before we did this, the following ... | python |
# -*- coding: utf-8 -*-
"""OAuth Token views."""
from __future__ import absolute_import, division, print_function, unicode_literals
from flask import Blueprint, abort, flash, redirect, render_template, url_for
from flask_babel import lazy_gettext as _
from flask_login import current_user, login_required
from .models... | python |
# Copyright 2019 VMware, Inc.
# SPDX-License-Identifier: BSD-2-Clause
import argparse
import os
import network_insight_sdk_generic_datasources.common.yaml_utilities as yaml_utilities
from network_insight_sdk_generic_datasources.archive.zip_archiver import ZipArchiver
from network_insight_sdk_generic_datasources.commo... | python |
class Solution:
"""
@param nums: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, nums):
# write your code here
if not nums: return [[]]
nums = sorted(nums)
res = []
self.helper(res, [], nums, 0)
return res
... | python |
if __name__ =='__main__':
N = int(input("Enter Number of Commands "))
L =[]
for i in range(0,N):
tokens = input("Enter command ").split()
if tokens[0] == "insert":
L.insert(int(tokens[1]), int(tokens[2]))
elif tokens[0] == "print":
print(L)
elif tokens[0] == 'remove':
... | python |
#execute: python3 script_path image_path min_wavelet_level max_wavelet_level erosion_times R_script_path output0 output1
import numpy as np
import pandas as pd
import pywt,cv2,sys,subprocess,homcloud,os
import matplotlib.pyplot as plt
args = sys.argv
image_path = args[1] #jpg file
min_wavelet_level = args[2] #int
max... | python |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | python |
import os
import pandas as pd
import pytest
import clustereval as ce
@pytest.fixture
def data():
return pd.read_csv('clustereval/data/testdata.csv.gz')
def test_vanilla_cluster_louvain(data):
ce.cluster.run_full_experiment(reduction = data,
alg = 'louvain',
... | python |
import re
from django.contrib.auth.backends import ModelBackend
from .models import User
def jwt_response_payload_handler(token, user=None, request=None):
"""
由于我们的jwt 响应的数据只有token
当时我们需要用户名和id所以我们需要让django框架取认识我们自定义的响应
自定义状态保持的响应内容
:param token: token
:param user: 用户名
:param request: 请求... | python |
import re
from functools import reduce
from django.template import Template, Context
from django_grapesjs.settings import NAME_RENDER_TAG
__all__ = ('ApplyRenderTag', )
REGEX_RENDER_TAG = '<%s>(.*?)</%s>' % (NAME_RENDER_TAG, NAME_RENDER_TAG)
class ApplyRenderTag(object):
def apply_tag_init(self, string):
... | python |
import rdkit
import rdkit.Chem as Chem
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
from collections import defaultdict
from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions
from vocab import Vocab
def get_mol(smiles):
mol = Che... | python |
# -*- coding: utf-8 -*-
from datafield import DataFieldForm, NamedDataFieldForm
from dataset import DataSetForm
from robot import RobotForm
from urlsource import URLSourceForm
| python |
from operator import itemgetter
def isPlayerWon(board, champ):
if (board[0] == champ and board[1] == champ and board[2] == champ or
board[3] == champ and board[4] == champ and board[5] == champ or
board[6] == champ and board[7] == champ and board[8] == champ or
board[0] == champ and board... | python |
# -*- coding: utf-8 -*-
from django_jinja.base import Library
import jinja2
register = Library()
@register.filter
@jinja2.contextfilter
def datetimeformat(ctx, value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
@register.global_context
def hello(name):
return "Hello" + name
| python |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from common_functions import load_data
if __name__ == '__main__':
X, y = load_data('ex2data1.txt')
x1, x2 = X.T
f_y = y.ravel()
plt.plot(x1[f_y==0], x2[f_y==0], 'yo')
plt.plot(x1[f_y... | python |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
KNearestConcaveHull.py
----------------------
Date : November 2014
Copyright : (C) 2014 by Detlev Neumann
Dr. Neumann Consulting - Geospatial Ser... | python |
# date: 2021.03.29
# author: Han Tran (htran@know-center.at)
import os
import re
import openml as oml
#####################################################################
'''
*** Function: write a proto file with a given regconized ID in OpenML
*** Input: dataID from OpenML, name and location for the output file
**... | python |
#!/usr/bin/env python
import os.path
from django.db import models
from django.utils.timezone import now
from panda.models.user_proxy import UserProxy
class BaseUpload(models.Model):
"""
Base class for any file uploaded to PANDA.
"""
filename = models.CharField(max_length=256,
help_text='Fil... | python |
import numpy as np
import matplotlib.pyplot as plt
filepath = '/home/jp/opensourcecode/OpenSourceORBVIO/tmp/';
biasa = np.loadtxt(filepath+'biasa.txt');
plt.figure(1);
p11, =plt.plot(biasa[:,0]-biasa[0,0],biasa[:,1]);
p12, =plt.plot(biasa[:,0]-biasa[0,0],biasa[:,2]);
p13, =plt.plot(biasa[:,0]-biasa[0,0],biasa[:,3]);
... | python |
from . import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from datetime import datetime
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class Pitch(db.Model):
__tablename__ = 'pitches'
pit... | python |
from sls.completion.item import CompletionItem, CompletionItemKind
from .argument import Argument
class Event(CompletionItem):
"""
An individual service event with its arguments.
"""
def __init__(self, name, description, args):
self._name = name
self._description = description
... | python |
from setuptools import setup
setup(
name='nzpaye',
version='0.1.1',
description='NZ Paye Summary',
long_description="""Calculate the NZ Paye Summary based on the hourly rate and the number of hours worked.""",
url='https://github.com/anuj-ssharma/NZPaye',
author='Anuj Sharma',
author_email=... | python |
from agent import Agent
import random
class SimpleAgent(Agent):
def __init__(self, config):
super().__init__(config)
def name(self):
return "Simple"
def move(self, board):
op_piece = self.piece % 2 + 1
valid_moves = self.valid_moves(board)
if len(valid_moves) == 0... | python |
from matplotlib import pyplot as plt
from matplotlib.patches import Wedge
import numpy as np
from config_space_angular_constraints import plot_config_space
def path_figure(theta_matrix, robot_arm, show=True):
"""
Arguments:
theta_matrix - A set of theta column vectors
robot_arm - An object of the Robo... | python |
#!/usr/bin/python3
'''jump_player.py'''
import pgzrun
SPEED = 6
WIDTH = 800
HEIGHT = 300
PLAYER_XPOS, PLAYER_YPOS = 75, HEIGHT-60
ANI_SPEED = 4
JUMP = 18
GRAVITY = 1.0
PLAYER_IMG = 'bot'
bg = []
bg.append(Actor('ground', anchor=('left', 'bottom')))
bg.append(Actor('ground', anchor=('left', 'bottom')))
p... | python |
from celery import shared_task
from grandchallenge.archives.models import Archive
from grandchallenge.cases.models import Image
@shared_task
def add_images_to_archive(*, upload_session_pk, archive_pk):
images = Image.objects.filter(origin_id=upload_session_pk)
archive = Archive.objects.get(pk=archive_pk)
... | python |
from markdown import markdown
def yup():
return markdown('A **long** time ago in a galaxy far, **far** away...') | python |
#twitterclient
import twitter
from configuration import configuration
class twitterclient:
def __init__(self):
config = configuration("config.ini")
self.api = twitter.Api(consumer_key=config.getTwitterConsumerKey(),
consumer_secret=config.getTwitterConsumerSecret(),
... | python |
from datetime import datetime, timedelta
import airflow
from airflow import DAG
from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator
# Task arguments
task_args = {
"depends_on_past": False,
"email_on_failure": True,
"owner": "filippoberio",
"email": ["philip.dent2@digital... | python |
""" Inference demo """
import numpy as np
from bcipy.signal.model.inference import inference
from bcipy.signal.model.mach_learning.train_model import train_pca_rda_kde_model
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pylab as plt
dim_x = 5
num_ch = 1
num_x_p = 100
num_x_n = 900
mean_pos = .8
var_p... | python |
import pub.settings as s
import json, requests
import pub.response.wrap as wrapper
import pub.response.error as e
import pub.client.auth_handler as auth_handler
import re
auth_url = 'https://github.com/login/oauth/authorize?client_id=' \
+ s.GITHUB_CLIENT_ID + '&state='
access_token_url = 'https://github.c... | python |
from django.shortcuts import render ,redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed
from .models import UserDetail ,Profile ,HotelDetail
import os
from django.conf import settings... | python |
from decimal import Decimal
class BaseSymbolDTO(object):
def __init__(self, symbol: str):
self.symbol = symbol
@property
def symbol(self) -> str:
return self._symbol
@symbol.setter
def symbol(self, value: str):
self._symbol = value
class BaseOrder(BaseSymbolDTO):
de... | python |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | python |
import datetime, random, requests
import pytz
data={
"tempInternal" : random.randint(40,100),
"humInternal" : random.randint(0,100),
"tempCab" : random.randint(40,100),
"humCab" : random.randint(0,100),
"batteryV" : ra... | python |
import torch
import torch.distributed as dist
from .pairwise import PairwiseCommTrainer
class GossipingSGDPullTrainer(PairwiseCommTrainer):
""" Gossiping SGD - pull variant. """
def __init__(self, *args, **kwargs):
super(GossipingSGDPullTrainer, self).__init__(*args, **kwargs)
def compute_comm_u... | python |
import os
import json
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(__location__, 'para_whitelist.json')) as data_file:
whitelist = json.load(data_file)
| python |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
@Description:
@Author: Zpp
@Date: 2019-09-02 16:04:11
@LastEditTime: 2019-09-12 11:27:19
@LastEditors: Zpp
'''
| python |
"""Test speed initialization by a map of speeds and their corresponding ratios."""
import numpy as np
from flatland.envs.rail_env import RailEnv
from flatland.envs.rail_generators import complex_rail_generator
from flatland.envs.schedule_generators import speed_initialization_helper, complex_schedule_generator
def t... | python |
from aqt import mw
from aqt.utils import showInfo, showWarning
from PyQt5.QtWidgets import QAction, QMenu
from aqt.qt import *
from sqlite3 import connect
from os.path import dirname, join, realpath
import webbrowser
from .Ui import start_main
all_data = ""
this_version = "v2.2"
###MENU###
def Abou... | python |
import orio.main.tuner.search.search
from orio.main.util.globals import *
import time
import itertools
import math
class Direct(orio.main.tuner.search.search.Search):
def __init__(self, params):
orio.main.tuner.search.search.Search.__init__(self, params)
# rate-of-change
self.K_roc = .5
... | python |
import uuid
from django.db import models
FLAVOR_TYPES = (
('ovh.ssd.eg', 'ovh.ssd.eg'),
('ovh.ssd.cpu', 'ovh.ssd.cpu'),
('ovh.ceph.eg', 'ovh.ceph.eg'),
('ovh.cpu', 'ovh.cpu'),
('ovh.ssd.ram', 'ovh.ssd.ram'),
('ovh.vps-ssd', 'ovh.vps-ssd'),
('ovh.ram', 'ovh.ram'),
)
OS_TYPES = (
('linux'... | python |
# -*- coding: utf-8 -*-
import scrapy
from scrapy_rss import RssItem
class SomeSpider(scrapy.Spider):
name = 'second_spider'
start_urls = ['https://woxcab.github.io/scrapy_rss/']
custom_settings = {
'FEED_TITLE': 'New shop categories',
'FEED_FILE': 'feed2.rss'
}
def parse(self, r... | python |
# -*- coding: utf-8 -*-
# @Author: Chieh-Han Lee
# @Date: 2015-08-05 19:40:44
# @Last Modified by: Chieh-Han Lee
# @Last Modified time: 2016-10-31 23:26:00
# -*- coding: utf-8 -*-
'''
Created on 2012/4/11
@author: KSJ
'''
import numpy as np
from scipy.spatial import cKDTree as KDTree
from scipy.spatial.distance ... | python |
# -*- coding: utf-8 -*-
"""
Test metering and floating behaviors of DRM Library.
"""
from time import sleep
from random import randint
from datetime import datetime, timedelta
from re import search
import pytest
@pytest.mark.minimum
def test_metered_start_stop_short_time(accelize_drm, conf_json, cred_json, async_hand... | python |
"""An uncomplicated implementation of single-linked lists."""
from __future__ import annotations
from itertools import chain
from typing import List, Optional, Union, Iterator, Reversible, Final, Any
from csbasics.datastructure import DataStructure, ValueT, RefT
MAX_LENGTH_DISPLAY_LIST = 10
class _EOL:
pass
... | python |
import argparse
import os
from os import path
import glob
from google.cloud import storage
def copy_local_directory_to_gcs(local_path, bucket, gcs_path):
for local_file in glob.glob(local_path + '/**'):
if not os.path.isfile(local_file):
continue
remote_path = os.path.join(g... | python |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import yfinance as yf
from talib import RSI, BBANDS
start = '2022-01-22'
end = '2022-04-21'
symbol = 'TSLA'
max_holding = 100
price = web.DataReader(name=symbol, data_source='quandl', start=start, end=end, api_... | python |
def julian_is_leap(year):
return year % 4 == 0
def gregorian_is_leap(year):
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def solve(year):
month = '09'
day = '13'
if year <= 1917:
is_leap_year = julian_is_leap(year)
elif year == 1918:
day = '26'
is_le... | python |
import random
class BotPlayer:
""" Your custom player code goes here, but should implement
all of these functions. You are welcome to implement
additional helper functions. You may wish to look at board.py
to see what functions are available to you.
"""
def __init__(self, gui... | python |
import base64
from email.mime.text import MIMEText
import httplib2
from django.core.mail import EmailMessage
from django.core.mail.backends.base import BaseEmailBackend
from django.conf import settings
from googleapiclient import errors
class GMail(BaseEmailBackend):
def send_messages(self, email_messages):
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.