content stringlengths 5 1.05M |
|---|
# Project : The Boredless Tourist
# Date : Sun 14 Jun 2020 05:28:59 AM IST
destinations = ["Paris, France", "Shanghai, China", "Los Angeles, USA", "São Paulo, Brazil", "Cairo, Egypt"]
# Retrieve the index of the traveler
def get_destination_index(destination):
destination_index = destinations.index(destinati... |
#!/usr/bin/env python
from distutils.core import setup
import setuptools
setup(name='matrix',
version='1.5',
description='Geometry operations',
author='Nicolas Reyland',
author_email='nicolas@reyland.net',
url='https://github.com/Nicolas-Reyland/Snake-Environment',
packages=setuptoo... |
from __future__ import unicode_literals, division, absolute_import
import logging
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import plugin
from flexget.event import event
try:
# NOTE: Importing other plugins is discouraged!
from flexget.plugins.filter import ... |
#Apple and Orange
#https://www.hackerrank.com/challenges/apple-and-orange/problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
apple_total = [1 for x in apples if (x+a)>=s and... |
# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Create list areas
areas = [hall, kit, liv, bed, bath]
# Print areas
print(areas)
|
from unittest import TestCase
from twofa import app, db
class BaseTestCase(TestCase):
render_templates = False
def setUp(self):
self.client = app.test_client()
app.app_context().push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-19 04:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('movies', '0002_auto_20161019_0449'),
]
operations ... |
# Copyright 2016 The FilterForward Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
from __future__ import annotations
from typing import TYPE_CHECKING
from itertools import chain
from dataclasses import dataclass
from py_rete.common import V
if TYPE_CHECKING: # pragma: no cover
from typing import List
from typing import Union
from typing import Tuple
from typing import Callable
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=2 sw=2 et sts=2 ai:
#
# Copyright 2009 Google 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/l... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import ListView
from exam.models import Exam, Question, Choice, Answer, Mark
from user.models import Student
from user.forms import LoginForm
from math import ceil
#Headers to generate pdf ReportLab
from dja... |
# -*- coding: utf-8 -*-
from imma_formats import TABLE_C0
# import struct
def pack(value):
return str(value)
# if type(value) == int:
# return struct.pack('d', value)
# elif type(value) == float:
# return struct.pack('f', value)
# elif type(value) == str:
# return value
# else:
#... |
import sys
sys.path.append('/home/jwalker/dynamics/python/atmos-tools')
sys.path.append('/home/jwalker/dynamics/python/atmos-read')
import numpy as np
import xray
import atmos as atm
import merra
# ----------------------------------------------------------------------
# Daily vertically integrated moisture transport... |
# -*- coding: utf-8 -*-
# ===========================================
# author: Quentin Ducasse
# email: quentin.ducasse@ensta-bretagne.org
# github: https://github.com/QDucasse
# ===========================================
# Command Line Interface: Command-line arguments parser and routine.
import argpars... |
import unittest
from ndk.objects import ServiceGroup
from ndk.stack import Stack
class ServiceGroupTestCase(unittest.TestCase):
def setUp(self):
self.stack = Stack('ServiceGroupTesting')
def test_contact_group(self):
cg = ServiceGroup(self.stack, servicegroup_name='Foo')
assert cg.p... |
# -*- coding: utf-8 -*-
"""
The actual implementation of the SQLAlchemy data layer.
:copyright: (c) 2013 by Andrew Mleczko and Tomasz Jezierski (Tefnet)
:license: BSD, see LICENSE for more details.
"""
from __future__ import unicode_literals
import collections
from copy import copy
import flask_sqlalchem... |
"""
miOSQP interface to solve MIQP problems
"""
import miosqp
from mathprogbasepy.quadprog.results import QuadprogResults
from mathprogbasepy.quadprog.solvers.solver import Solver
class MIOSQP(Solver):
"""
An interface for the MIOSQP solver.
"""
def solve(self, p):
model = miosqp.MIOSQP()
... |
import pygeonlp
ma = pygeonlp.MA()
print(ma.parse("沖縄県の南海上で台風が発生しました。"))
|
from pkg_resources import resource_stream
try:
from configparser import SafeConfigParser
except ImportError:
from ConfigParser import SafeConfigParser
import os.path, sys
class ReferenceTable(dict):
def __init__(self,iniFile=None):
if not iniFile:
iniFile = [ s.decode('utf8') for s in ... |
# https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[len(nums) - k]
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
#Quick Select
#this works... |
import subprocess
import unittest
import cricket
from cricket.unittest import discoverer
from cricket.unittest import executor
class TestCollection(unittest.TestCase):
def test_testCollection(self):
'''
Confirm that the pytest discovery mechanism is capable of
finding this test
'... |
"""This module tests GlusterFS helper."""
__author__ = "Bartek Kryza"
__copyright__ = """(C) 2017 ACK CYFRONET AGH,
This software is released under the MIT license cited in 'LICENSE.txt'."""
import os
import sys
import md5
import pytest
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.... |
#!/usr/bin/env python3
from letterswitcher import LetterSwitcher
from enum import Enum
#define an enumeration for the different types of Reflector
#that are currently supported
#TODO: support thin reflectors
class ReflectorType(Enum):
B = 0
C = 1
#class for an Enigma reflector
#reflectors are used to 'ref... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
"""
Exercise table creation
"""
def test():
import pyre.db
# declare a simple table
class TypeFest(pyre.db.table, id="typefest"):
"""
Exercise the type declarations... |
#!/usr/bin/env python
# encoding: utf-8
from flask import render_template
from flask import redirect
from flask import session
from flask import url_for
from manage import app
from .. import demo
from ..models import User
from core.response import SuccessResponse
from core.base import JsonSerialize
@demo.route('/', ... |
# web_app/__init__.py
from flask import Flask
from web_app.models import db, migrate
from web_app.routes.home_routes import home_routes
from web_app.routes.tweet_routes import tweet_routes
from web_app.routes.twitter_routes import twitter_routes
from web_app.routes.stats_routes import stats_routes
import os
from dot... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
from conversationinsights.events import SetSlot, ExecutedAction
from conversationinsights.training_utils import create_stories_from_file
import logging
logger... |
import os
import shutil
import requests
import zipfile
DATA_PATH = 'data'
if os.path.exists(DATA_PATH):
shutil.rmtree(DATA_PATH)
os.mkdir(DATA_PATH)
print('Downloading...')
url = 'https://weisslab.cs.ucl.ac.uk/WEISSTeaching/datasets/-/raw/jigsaws/video-meta.zip'
r = requests.get(url,allow_redirects=True)
zip... |
import itertools
import random
import sys
#random.seed(42)
fh = open("string.vcf", "w")
header = ("""##fileformat=VCFv4.2
##FILTER=<ID=PASS,Description="All filters passed">
##FILTER=<ID=FAIL,Description="All filters passed">
##FILTER=<ID=OTHER,Description="All filters passed">
##INFO=<ID=num,Number=1,Type=Integer,... |
import logging
import os
import sys
from urllib.request import urlopen
from xml.etree.ElementTree import fromstring
import pandas as pd
import requests
import xlrd
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.management.color import no_style
from django.db impo... |
"""
Tests for CSVProcessor
"""
import io
from unittest import mock
import ddt
from django.contrib.auth import get_user_model
# could use BytesIO, but this adds a size attribute
from django.core.files.base import ContentFile
from django.test import TestCase
from super_csv import csv_processor, models
class DummyPro... |
#!/usr/bin/env python
import time
import asyncio
import logging
import ujson
import websockets
import hummingbot.connector.exchange.exmo.exmo_constants as CONSTANTS
from typing import Optional, List, AsyncIterable, Any, Dict
from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSo... |
#
# Copyright (C) 2018 The Android Open Source Project
# Copyright (C) 2020 Samsung Electronics Co., Ltd. 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://w... |
class Solution:
def __init__(self):
self.lessThan20 = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
self.tens = ["","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eig... |
import sys
import argparse
def str2bool(v):
'''
used to create special type for argparse
'''
return v.lower() in ('yes', 'true', 't', '1')
class Parameters():
'''
Keeps all the variables related to the present run of the experiment -
which are usually set up with flags.
'''
def __init__(s... |
from distutils.core import setup
setup(
name='gravispy',
description='Gravitational simulations using vispy',
long_description=open('README.md').read(),
url='https://github.com/cjayross/gravispy',
version='0.1-dev',
packages=['gravispy',],
install_requires=['nump... |
from argparse import ArgumentParser
import torch
from benchmark_for_transformers.benchmark import Benchmark
def main():
parser = ArgumentParser()
parser.add_argument("--run_args_file", help="Path to the args json file", type=str)
parser.add_argument("-v", "--verbose", help="increase output verbosity", a... |
"""
This file contains all of the actuall low-level datalink interfaces for
CATAN
(c) 2015 Massachusetts Institute of Technology
"""
# Native
import socket
import logging
import time
import IN
logger = logging.getLogger(__name__)
# CATAN
import catan.globals as G
from catan.data import NodeMessage
... |
import logging
import os
import re
import time
import sys
import traceback
try:
from kick.graphite.graphite import publish_kick_metric
except ImportError:
from kick.metrics.metrics import publish_kick_metric
from ..actions.statemachine import WmStateMachine
from ...kp.actions import Kp, KpLine
from ...kp.actio... |
PORT = 9914
try:
try:
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("localhost", PORT), Handler)
httpd.serve_forever()
except ImportError:
from http.server import HTTPServer, SimpleHTTPRequestHandler
... |
from bokeh.palettes import Category20
from bokeh.embed import json_item
from bokeh.plotting import figure
from bokeh.models import FactorRange, ColumnDataSource, HoverTool, NumeralTickFormatter
from django.http import JsonResponse
from .helpers import *
def _get_plot_data(_data_type, _top_n, _exclude_states):
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 by Gustavo Narea <http://gustavonarea.net/>.
#
# This file is part of Booleano <http://code.gustavonarea.net/booleano/>.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),... |
# All functions to improve Python interaction with shells must be placed here.
#
# Author: Vitor Santos <vitorhgsantos90@gmail.com>
import subprocess, sys, platform, shutil, stat, errno, re, os, distutils.dir_util, glob, getpass, zipfile, filecmp
###################### SHELL INTERACTION ######################
# P... |
import logging
from pathlib import Path
from io import StringIO
from jinjafy import YmdReader, Pandoc
doc = """
---
title: My title
author: Author, My
content: |-
** Emphatic content **
...
# {{title}}
{{ author }}
{{content*key2}}
---
key2: 2
...
## Subheadings
Subinfo
"""
def str_test():
meta, content =... |
# Copyright Collab 2015-2016
# See LICENSE for details.
import os
import glob
import codecs
from json import dumps, loads
from datetime import datetime
from django.conf import settings
from django.core.management.base import CommandError
import polib
from babel.dates import format_datetime
#: License header for c... |
import time
import math
import sys
sys.path.append('./VREP_remoteAPIs')
''' Inverse kinematics '''
def chassisInverseKinematics(vx, vy, omega, wheel_R, a, b):
omega_1 = (vy - vx + (a+b)*omega)/wheel_R
omega_2 = (vy + vx - (a+b)*omega)/wheel_R
omega_3 = (vy - vx - (a+b)*omega)/wheel_R
omega_4 = (vy + vx... |
import tkinter as tk
import random
import colors as c
class Game(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
self.grid()
self.master.title('2048')
self.main_grid = tk.Frame(
self, bg=c.GRID_COLOR, bd=3, width=400, height=400)
self.main_grid.grid(pady... |
"""
This example show the basic usage of graphs (pyframe.Graph)
Note that the graph are for now not very well optimized.
On my PC :
average of 1100 fps when graph is hidden
average of 400 fps when graph is shown
Press F1 to show/hide the graph
"""
import pygame,pyframe,sys,os # Importing modules
size = (5... |
import os
import pandas as pd
from xml.sax import ContentHandler, parse
# Reference https://goo.gl/KaOBG3
class ExcelHandler(ContentHandler):
def __init__(self):
self.chars = [ ]
self.cells = [ ]
self.rows = [ ]
self.tables = [ ]
def characters(self, content):
sel... |
import src.merge_sort as ms
class TestMyMergeSort:
def test_merge(self):
cases = [[5, 9, 45, 36], [-95, -65, 38, -1, 0]]
assert ms.merge_sort(cases[0]) == [5, 9, 36, 45]
assert ms.merge_sort(cases[1]) == [-95, -65, -1, 0, 38]
|
# import math
# print(math)
# # <module 'math' ... >
#
# math.pi
# # 3.141
# math.e
# # 2.718
#
# math.sin(math.pi)
# # 1.2246467991473532e-16
# math.cos(math.pi)
# # -1.0
# math.log(1024)
# # 6.931471805599453
#
# import random
# random.random()
# # 0.6659832639132849
# random.random()
# # 0.5013513891044694
#
# r... |
import numpy as np
import pandas as pd
'''
#############################################################################
DESCRIPTION INITIALIZATION.PY
Author: Jonas Grundler (University of Edinburgh)
initialization.py is a purely functional package and only used for initializing different data frames
that are requir... |
import sys, os.path, csv, plotly, scipy.stats
import plotly.graph_objs as go
stats_file = "result.csv"
tools = ["base","nullaway","eradicate","checkerframework"]
colors = ['#7f7f7f','#2ca02c','#1f77b4','#ff7f0e']
def make_series(records, key, keyi=1, xi=0, yi=2):
series_recs = list(filter(lambda r: r[keyi]==key, rec... |
from fakturoid.api import *
from fakturoid.models import *
|
#!/usr/bin/env python3
##
## This is a Python script that will power off all VSIs and BareMetal servers in an IBM Cloud account. An API Key with the appropriate permissions on the account is required
## Currently supports: Classic VSIs, Classic BareMetal
##
## License: MIT License
## Author: Chris Sciarrino
## Version... |
#!/usr/bin/env python
from absl import app
# pylint: disable=unused-import
from grr_response_client.vfs_handlers.ntfs_test_lib import NTFSNativeWindowsTest
from grr_response_client.vfs_handlers.ntfs_test_lib import NTFSTest
# pylint: enable=unused-import
from grr.test_lib import test_lib
def main(argv):
test_lib.m... |
'''
Created on Jan 28, 2016
@author: jason
'''
import numpy as np
from pyearth._qr import UpdatingQT
from scipy.linalg import lstsq
def test_updating_qt():
np.random.seed(0)
m = 10
n = 3
X = np.random.normal(size=(n, m)).T
u = UpdatingQT.alloc(m, n, 1e-14)
# u2 = UpdatingQT(m, n)
Q = np.... |
'''
Utility functions for the monitoring and log generation.
'''
import time
import logging
def init_logger():
'''
Initialise the logger.
Returns:
logger (Logger): Logger to use for the monitoring.
'''
log_format = '%(asctime)s %(levelname)s %(message)s'
logger = logging.getLogger(... |
# coding=utf-8
from itertools import count
from typing import Iterable
from oeis.registry import registry
from oeis.utils import is_semiperfect
@registry.register("A005835")
def semiperfect() -> Iterable[int]:
"""Semiperfect numbers."""
for n in count(start=1):
if is_semiperfect(n):
yield... |
import logging
import math
from pathlib import Path
from ray_tracer.canvas import canvas_to_png
from ray_tracer.camera import Camera
from ray_tracer.clipped_shape import ClippedShape
from ray_tracer.colors import Color, BLUE, WHITE
from ray_tracer.lights import point_light
from ray_tracer.material import Material
from... |
import jax
import jax.numpy as jnp
from functools import partial, reduce
from .util import amap, _cumsum
from operator import mul
def _flatten_tensors(x, axes):
shape = x.shape
start = _cumsum((0,) + axes[:-1])
_prod = lambda x: reduce(mul, x, 1)
def _f(il):
i, l = il
return _prod(s... |
import time
import sys
for x in range(0, 100):
print(x)
time.sleep(1)
sys.stdout.flush()
logger = logging.getLogger('beats-logger')
total_lines = 1000
lines_per_file = 10
# Each line should have the same length + line ending
# Some spare capacity is added to make sure all events are presisted
line_lengt... |
class CallbackContext():
#REPRESENTS THE INPUT TO THE CALLBACK, NOTICE, SOME VALUES MIGHT BE NONE, DEPENDING ON THE PHASE/STATE OF THE CALLBACK
def __init__(self, trainer):
self.epoch = trainer.epoch
self.sample_count = trainer.sample_count
self.sample_count_in_epoch = trainer.sample_cou... |
"""
blizz – be blizzful.
"""
import logging as __logging
import os as __os
from ._bootstrapping import relation_from_dataframe
from ._constants import ALL_FIELDS
from ._primitives import Relation, Field
__version__ = "0.2.4"
__DEFAULT_LOG_LEVEL = __os.environ.get("BLIZZ_LOG_LEVEL", __logging.INFO)
__logging.basicC... |
N, K = map(int, input().split())
bit = 0
while(N >= K**bit):
bit += 1
print(bit) |
# -*- coding: utf-8 -*-
# 15/6/8
# create by: snower
from .version import version, version_info
from . import config
from .plan import Plan
from .action.action import Action
from .store.store import Store
from .extension import Extension
from .clients import ThriftClient, TorThriftClient |
from abc import ABC, abstractclassmethod
import numpy as np
import torch.nn as nn
class exp_interface(ABC):
def prepare_model(self)->nn.Module:
raise NotImplementedError
def generate_data(self)->dict:
raise NotImplementedError
def get_algorithm(self):
raise NotImplementedError |
import os
import cv2
from dirsetup import IMAGES_DIR
lena = os.path.join(IMAGES_DIR, 'lena.jpg')
img = cv2.imread(lena)
h, w, _ = img.shape
from cr.vision.core.scaling import resize_outside
print(img.shape)
img2 = resize_outside(img, 512, 200)
print(img2.shape)
img2 = resize_outside(img, 200, 512)
print(img2.sh... |
"""
Layout: Basic search committee info
"""
# Third party imports
import dash_bootstrap_components as dbc
import dash_html_components as html
search_info = html.Div(
[
dbc.Row([
dbc.Col(
[
html.Span('Department: '),
html.Span(children=''... |
import os
import urllib.parse
import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import util
from util import logger
from zhihu import Zhihu
def generate_archive_md(searches, questsions, videos):
"""生成归档readme
"""
def search(item)... |
import torch
from mmdet.datasets import build_dataloader, DATASETS
from mmdet.models import clip
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
from mmcv.ops import roi_align
import argparse
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat... |
import re
import sublime
from ..view import MdeViewEventListener
HEADINGS_RE = re.compile(
r"""
^( [ \t]* ) # leading whitespace
(?:
( \#{1,6} ) [ \t]+ ( [^\n]+ ) # ATX headings
| ( [^-=#\s][^|\n]* ) \n \1 ( -{3,} | ={3,} ) # SETEXT headings
) ... |
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
t=(int)(input())
for absda in range(t):
s,n,m,k=raw_input().split()
s=int(s)-1
n=int(n)-1
m=int(m)-1
k=int(k)
if s<=k:
print "0.000000"
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 18:07:00 2021
@author: 알파제로를 분석하며 배우는 인공지능
"""
#%%
# 이전 코드들
# 틱택토 생성
import random
# 게임 상태
class State:
# 초기화
def __init__(self, pieces=None, enemy_pieces=None):
# 돌 배치
self.pieces = pieces if pieces != None else [0]*9
self.enemy_pie... |
# --------------------------------------------------------------
# SNIPER: Efficient Multi-Scale Training
# Licensed under The Apache-2.0 License [see LICENSE for details]
# SNIPER demo
# by Mahyar Najibi
# --------------------------------------------------------------
import init
import matplotlib
matplotlib.u... |
# coding: utf-8
# Remove a specific group entry from database
# Created by James Raphael Tiovalen (2021)
import slack
import ast
import settings
import config
from slackers.hooks import commands
conv_db = config.conv_handler
@commands.on("deletegroup")
def deletegroup(payload):
return
|
from pathlib import Path
import numpy as np
import typing as T
import logging
from struct import pack, unpack
def getRawInd(fn: Path, finf: T.Dict[str, int]) -> T.Tuple[int, int]:
if not isinstance(finf["nmetadata"], int):
raise TypeError(finf["nmetadata"])
if finf["nmetadata"] < 1: # no header, onl... |
# generate action labels for training the network
# matlab code:
# https://github.com/hellbell/ADNet/blob/master/utils/gen_action_labels.m
import numpy as np
import numpy.matlib
from options.general import opts
from utils.overlap_ratio import overlap_ratio
def gen_action_labels(num_actions, opts, bb_samples, gt_bbox... |
import numpy as np
import matplotlib.pyplot as plt
from starry_process import StarryProcess
import theano
import theano.tensor as tt
from tqdm import tqdm
import os
import time
# Compile the function to compute the likelihood
def get_loglike_function(ydeg, marginalize_over_inclination=False):
t = tt.dvector()
... |
def main():
num = int(input("Enter the number"))
print(f"{num} square is {num**2}")
if __name__ == "__main__":
main()
|
# get tasks from openml
import openml
import pandas as pd
# List of dataset IDs used for the NIPS experiment.
dataset_ids = [1000, 1002, 1018, 1019, 1020, 1021, 1036, 1040, 1041, 1049, 1050, 1053,
1056, 1067, 1068, 1069, 1111, 1112, 1114, 1116, 1119, 1120, 1128, 1130,
1134, 1138, 1139, 1... |
import requests as req
from bs4 import BeautifulSoup as bs
DATA = {}
def seasonal_fetch(page_id, start, end):
for i in range(start, end + 1):
url = f'https://www.imdb.com/title/{page_id}/episodes?season={str(i)}'
resp = req.get(url)
if resp.status_code == 200:
souped(resp.cont... |
import matplotlib.pyplot as plt
import numpy as np
from ...const import wo_month, show_dict
import csv
import os
class Math:
@classmethod
def plot(self, selected, active, year="", type=""):
all_amounts = []
if year != "" and type != "":
if selected == "Expenses":
... |
# coding: utf-8
"""
Browse API
<p>The Browse API has the following resources:</p> <ul> <li><b> item_summary: </b> Lets shoppers search for specific items by keyword, GTIN, category, charity, product, or item aspects and refine the results by using filters, such as aspects, compatibility, and fields values.<... |
from boucanpy.core.types import DnsRecordData
|
# Copyright (c) 2001, Stanford University
# All rights reserved.
#
# See the file LICENSE.txt for information on redistributing this software.
from __future__ import print_function
import sys
import apiutil
apiutil.CopyrightC()
print("""/* DO NOT EDIT! THIS CODE IS AUTOGENERATED BY unpack.py */
#include "unpacke... |
from office365.runtime.client_result import ClientResult
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.resource_path import ResourcePath
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office365.sharepoint.base_... |
try:
from sys import platform
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image, ImageTk
import tkinter.font, os, core
except Exception as e:
print("You're missing a package!")
print()
print(e)
input()
def re... |
import torch.nn.functional as F
from torch.autograd import Variable
from models.ResNet_feat import ResClassifier
from train_setup import *
criterion = nn.CrossEntropyLoss()
eta = 1.0
num_k = 4
def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0):
return np.float(2.0 * (high - low) / (1.0 + n... |
import numpy as np
import scprep
from sklearn.decomposition import TruncatedSVD
from ....tools.normalize import log_cpm, log_scran_pooling
from ....tools.decorators import method
from ....tools.utils import check_version
def _rpy2py(X):
import rpy2.robjects as ro
from rpy2.robjects import numpy2ri
try:
... |
# Copyright (c) 2021 ING Wholesale Banking Advanced Analytics
#
# 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, mo... |
from datetime import datetime
from sqlalchemy import Column, Integer, DateTime, String, ForeignKey
from sqlalchemy.orm import relation
from scooter.models import BaseModel
class Scooter(BaseModel):
"""The class represents scooters table.
Class variables are fields of a table.
"""
__tablename__: str ... |
# Copyright Red Hat, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
import numpy as np
import h5py
from pyglib.estructure import dos as _dos
from future_builtins import zip
with h5py.File('GBANDS_0.h5', 'r') as f:
k_start = f['/IKP_START'][0]
k_end = f['/IKP_END'][0]
e_kn = []
psi_kn = []
for k in range(k_start, k_end+1):
e_kn.append(f['/ISPIN_1/IKP_{}/ek'... |
"""
Lambda Functions are important for functional programming
They are unamed, annonimous functions
syntax
lambda arg: expression
add = lambda x: x + 5
print(add(10))
"""
lambda_functions = [lambda x: x + j for j in range(3)]
first_lambda_function = lambda_functions[0]
print(first_lambda... |
# Generated by Django 2.1.2 on 2018-11-06 17:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hknweb', '0004_link'),
]
operations = [
migrations.DeleteModel(
name='Link',
),
]
|
# Copyright 2021 The Magenta 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 or agreed to in ... |
"""
Base for all output generator plug-ins
Copyright (c) 2020, Tidepool Project
All rights reserved.
"""
from typing import List
from functools import cached_property
import pluginlib
@pluginlib.Parent('output')
class OutputGenerator():
"""
Base class for all output generator plug-ins
"""
key = plugin... |
#!/usr/bin/python
#-*- encoding: utf8 -*-
import rospy
from std_msgs.msg import Bool, String, Empty
from mind_msgs.msg import RaisingEvents, SetIdleMotion
class TurnDetectorNode:
def __init__(self):
rospy.Subscriber('raising_events', RaisingEvents, self.handle_raising_events)
rospy.Subscriber('rob... |
#要测试的类
class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self,question):
self.question = question
self.response =[]
def show_question(self):
"""显示调查问卷"""
print(self.question)
def store_response(self,new_response):
"""存储单份调查问卷"""
self.response.appen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.