content stringlengths 5 1.05M |
|---|
import tushare as ts
import csv
import time
import pandas as pd
pro = ts.pro_api('1dbda79ce58d052196b7ddec1663d53e4ea20571195a1a6055aab0c7')
stock_basic = pro.stock_basic(list_status='L', fields='ts_code, symbol, name, industry')
# 重命名行,便于后面导入neo4j
basic_rename = {'ts_code': 'TS代码', 'symbol': '股票代码', 'name': '股票名称', ... |
class DinnerPlates:
def __init__(self, capacity: int):
self.capacity = capacity
self.stack = []
def push(self, val: int) -> None:
if len(self.stack[-1]) < self.capacity:
self.stack[-1].append(val)
else:
self.stack.append([val])
def pop(self) -> int:... |
from __future__ import annotations
from typing import Literal
from prettyqt import core
from prettyqt.qt import QtCore
from prettyqt.utils import InvalidParamError, bidict
NAME_TYPE = bidict(
default=QtCore.QTimeZone.NameType.DefaultName,
long=QtCore.QTimeZone.NameType.LongName,
short=QtCore.QTimeZone.N... |
import json
from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = te... |
from copy import deepcopy
class SimpleAgent:
def getAction(self, gameState):
gameState._getValidWords()
return gameState.validWords, len(gameState.validWords)
class HeuristicAgent:
def getAction(self, gameState):
gameState._getValidWords()
if len(gameState.validWords)==1:
... |
from .property import Property
from .namedelement import NamedElement
from .renderer import Renderer
class Method(NamedElement, Renderer):
def __init__(self, **kwargs):
self.parameters = \
[Property(**p) for p in kwargs.pop('parameters', [])]
self.returns = \
[Property(**r)... |
#importing our libraries that we will be using for emotion detection
from operator import index
from textwrap import fill
from tkinter import Label, Tk
import numpy as np
import cv2
import keras
from tkinter import *
import pandas as pd
import webbrowser
win = Tk() #main application window
win.geometry('600x500')
win.... |
print("Hello World")
name = input("Hello, what is your name? ")
age = input("How old are you? ")
lunch = input("What do you want for lunch? ")
print("\n\n\n")
print(f"Hello {name}, your lunch order of {lunch} is here.")
print(f"You are tall for an {age} year old") |
import tensorflow as tf
from match.layers.activation import Dice, activation_layer
from match.layers.core import PredictionLayer, Similarity, DNN
from match.layers.sequence import SequencePoolingLayer, WeightedSequenceLayer
from match.layers.utils import (NoMask, Hash, concat_func, reduce_mean, reduce_sum, reduce_max,... |
from django.db import models
from datetime import date
import datetime
from django.utils import timezone
from django.contrib.auth.models import User
ITEM_CATEGORIA = (
('C','Conferencia'),
('S','Seminario'),
('Co','Congreso'),
('Cu','Curso'),
)
ITEM_TIPO=(('... |
import os
import asyncio
import asyncio.subprocess as aiosp
import locale
import yaml
import json
import io
from threading import Thread
import websockets
HOSTNAME = 'localhost'
WSS_PORT = 8765
HTTP_PORT = 8888
ASM_DIR = 'champs'
STDIN_F_NAME = 'stdin.txt'
COREWAR_EXE = "cmake-build-debug/corewar_vm"
# COREWAR_EXE = ... |
import codecs
import os
import re
import setuptools
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding option to open
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_meta(*meta_file_parts, meta_key):
"""
Extract __*meta... |
from .template_generator import TemplateGenerator |
import pytest
import requests
from uuid import uuid4
from datetime import date, timedelta
from json import JSONDecodeError
from backend.tests.factories import OrderFactory, ProductFactory, OrderProductFactory
from backend.util.response.user_orders import UserOrdersSchema
from backend.util.response.error import ErrorSc... |
import toml
import numpy
from utils import retry, accounts, firstProducer, numProducers, intToCurrency
config = toml.load('./config.toml')
def allocateFunds(b, e):
dist = numpy.random.pareto(1.161, e - b).tolist() # 1.161 = 80/20 rule
dist.sort()
dist.reverse()
factor = 2_000_000 / sum(dist)
total ... |
#!/usr/bin/env python
'''
These objects and functions are part of a larger poker assistant project.
Content of this script enable the user to simulate game of Texas Holdem Poker.
'''
__author__ = 'François-Guillaume Fernandez'
__license__ = 'MIT License'
__version__ = '0.1'
__maintainer__ = 'François-Guillaume Fernan... |
from collections import namedtuple
from reportlab.pdfbase import pdfmetrics, ttfonts
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm... |
import os
import sys
from distutils.core import setup
import matplotlib
import numpy
# import py2exe
# from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
# from matplotlib.figure import Figure
sys.setrecursionlimit(5000)
# Compile program using:
# python compileScript.py py2exe
# add an... |
from allauth.account.views import SignupView
from allauth.account.views import ConfirmEmailView
from users.forms import CustomUserCreationForm
class MySignupView(SignupView):
form_class = CustomUserCreationForm
class ConfirmEmailView(ConfirmEmailView):
def post(self, *args, **kwargs):
self.object = c... |
# coding=utf-8
# Copyright 2020 The Tensor2Robot 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 ... |
PACKAGE_HEADER = """\
/**
* Dlang vulkan types and function definitions package
*
* Copyright: Copyright 2015-2016 The Khronos Group Inc.; Copyright 2016 Alex Parrill, Peter Particle.
* License: $(https://opensource.org/licenses/MIT, MIT License).
* Authors: Copyright 2016 Alex Parrill, Peter Particle
*/
module... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
"""Run BL server."""
import argparse
from bl_lookup.server import app
from bl_lookup.bl import models, generate_bl_map
parser = argparse.ArgumentParser(description='Start BL lookup server.')
parser.add_argument('--host', default='0.0.0.0', type=str)
parser.add_argument('--port', default=8144, typ... |
from quo.table import Table
data = [
["Name", "Gender", "Age"],
["Alice", "F", 24],
["Bob", "M", 19],
["Dave", "", 24]
]
Table(data)
|
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import numpy as np
from numpy import exp, log, log10
# Constants
version = 20180411
# %% Parameters for out-of-equilibrium Bayes factor calcualtions
trials = 5
n12_range = [1e3, 1e4]
n12_points = 10
n12s = np.logspace(log10(n12_range[0]), log10(n12_range[1]), num=n12_points)
jobs_count_tars = 204 # max: 224
jobs_... |
#!/usr/bin/env python
"""
This application replicates the switch CLI command 'show interface fex'
It largely uses raw queries to the APIC API
"""
from acitoolkit import Credentials, Session
from tabulate import tabulate
def show_interface_fex(apic, node_ids):
"""
Show interface fex
:param apic: Session i... |
from hsclient.hydroshare import Aggregation, File, HydroShare, Resource
|
from .apps import GitHubApp
App = GitHubApp
|
# 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 warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
from django.apps import AppConfig
class MaingateConfig(AppConfig):
name = 'MainGate'
|
a3 = int(input())
a2 = int(input())
a1 = int(input())
atotal = (a3 * 3) + (a2 * 2) + a1
b3 = int(input())
b2 = int(input())
b1 = int(input())
btotal = (b3 * 3) + (b2 * 2) + b1
if atotal > btotal:
print("A")
elif atotal < btotal:
print("B")
else:
print("T")
|
"""
2015 Day 14
https://adventofcode.com/2015/day/14
"""
from dataclasses import dataclass
from typing import Sequence, Tuple
import aocd # type: ignore
@dataclass(frozen=True)
class Reindeer:
"""
Object encapsulating a reindeer's name and inherent attributes.
"""
name: str
speed: int
flyti... |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.urls import static
from . import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^auth/', include('loginsys.urls')),
url(r'^', include('mainpage.urls')),
url(r'^personal/', includ... |
import numpy as np
from sklearn.cluster import AgglomerativeClustering
import logging
class Clusterer(object):
"""
Abstract class for different clustering
variants based on the online clustering.
"""
def __init__(self, *args, **kwargs):
"""
Initializes the clusterer.
"""
... |
# Generated by Django 3.1.7 on 2021-03-02 15:10
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Country',
fiel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Samvaran Kashyap Rallabandi - <srallaba@redhat.com>
#
# Topology validator for Ansible based infra provsioning tool linch-pin
from ansible.module_utils.basic import *
import datetime
import sys
import json
import os
import shlex
import tempfile
import yaml
imp... |
"""
A simple set of math methods that we can build our
logging infrastructure on top of.
"""
import lib.logger
def add_some_numbers(a, b):
""" Adds the passed parameters and returns the result.
"""
logger_name = 'add_some_numbers'
logger = logging.getLogger(__name__).getChild(logger_name)
res... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Given a tryjob and perf profile, generates an AFDO profile."""
from __future__ import print_function
i... |
from forum.models import User, SubscriptionSettings, QuestionSubscription
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
def handle_noargs(self, **options):
users = User.objects.all()
for u in users:
s = SubscriptionSettings(user=u)
s.sav... |
import tensorflow as tf
def get_max_quant_value(num_bits: int) -> float:
return 2 ** (num_bits - 1) - 1
def quantize(input_tensor: tf.Tensor, scale: float, num_bits: int):
"""
https://arxiv.org/pdf/1910.06188.pdf
"""
threshold = tf.cast(get_max_quant_value(num_bits), tf.float32)
return tf.cl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 10:33:04 2020
@author: dianasimpson
"""
# Imported packages and files
import tkinter as tk
from tkinter import ttk, Menu
# Global variables for formatting
FT_DOG = 'dark olive green'
FT_GRY = '#E7E7E7'
LB_N16 = ('Times', 16)
LB_B16 = ('Times Bo... |
#Driver code
class Node:
def __init__(self, val):
self.val = val
self.right = None
self.left = None
def create():
n = int(input())
if n == -1:
return None
root = Node(n)
root.left = create()
root.right = create()
return root
def print_tree(root):
if roo... |
from __future__ import division
from past.utils import old_div
import unittest
from nineml.abstraction import (
Dynamics, Regime, Alias, Parameter, AnalogReceivePort, AnalogReducePort,
OnCondition, AnalogSendPort, Constant, StateAssignment)
from nineml.abstraction.dynamics.visitors.modifiers import (
Dynami... |
from modpy.proxy._polynomial import PolynomialModel
from modpy.proxy._kriging import SimpleKrigingModel, OrdinaryKrigingModel, UniversalKrigingModel
|
"""
FiftyOne v0.7.1 admin revision.
| Copyright 2017-2021, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
def up(db):
db.admin.command({"setFeatureCompatibilityVersion": "4.4"})
def down(db):
db.admin.command({"setFeatureCompatibilityVersion": "4.2"})
|
import oscar.apps.customer.apps as apps
class CustomerConfig(apps.CustomerConfig):
name = 'apps.customer'
|
"""
Selection Sort
https://en.wikipedia.org/wiki/Selection_sort
Worst-case performance: O(N^2)
If you call selection_sort(arr,True), you can see the process of the sort
Default is simulation = False
"""
def selection_sort(arr, simulation=False):
iteration = 0
if simulation:
print("iteration",iter... |
import itertools
from networking_p4.extensions import p4
def list_quota_opts():
return [
('quotas',
itertools.chain(
p4.p4_quota_opts)
),
]
|
default_app_config = "grandchallenge.workstations.apps.WorkstationsConfig"
|
# coding: utf-8
import enum
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import Enum
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Numeric
from sqlalchemy import String
from sqlalchemy.orm import relationship
import typing
from rolling.server.do... |
default_app_config = 'gallery.apps.GalleryAppConfig' |
import datetime
import json
import numpy as np
import pandas as pd
import requests
import psycopg2.extras
def query_yahoo_finance(stock_code, start, execution_date):
# convert execution_date to timestamp
execution_date = execution_date.format("%Y-%m-%d")
element = datetime.datetime.strptime(execution_dat... |
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_digits
from sklearn.preprocessing import scale
digits = load_digits()
X = digits.data # --> 8x8 픽셀
y = digits.target
#plt.matshow(digits.images[0])
#plt.show()
## scale ##
X_scale = scale(X, axis=0) # scaling
pca... |
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
class Solution:
def findKthLargest(self, nums, k):
if len(nums) < k:
return []
index = randint(0, len(nums) - 1)
pivot = nums[index]
less = [i for i in nums[:index] + nums[index + 1:] if i < piv... |
#coding:utf-8
#
# id: bugs.core_5808
# title: Support backup of encrypted databases
# decription:
# THIS TEST USES IBSurgeon Demo Encryption package
# ################################################
# ( https://ib-aid.com/download-demo-firebird-... |
MAIN_PAGE_ADMIN_TEMPLATE = """\
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
<div align="center">
<h1>General</h1>
<div align="center">
<table>
<tr>
<td>
<form action="/mainsearch" method="post">
<div><input type="submit" value="... |
import logging
import os
import sys
from argparse import ArgumentParser
from signal import SIGUSR1, SIGUSR2, signal
from subprocess import PIPE, run
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from loren_frank_data_processing import save_xarray
from loren_frank_data_proce... |
import calendar
def iterweekdays(calendar): return calendar.iterweekdays()
for calendar in [calendar.Calendar(), calendar.Calendar(firstweekday=0), calendar.Calendar(firstweekday=6)]:
print('-----',calendar,'-----')
print(iterweekdays(calendar))
for weekday in iterweekdays(calendar): print(weekday, end=',... |
# Django settings for dd_auth project.
import os
from django.utils.translation import ugettext_lazy as _
APP_PATH = os.path.dirname(os.path.abspath(__file__))
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'EN... |
#!/usr/bin/env python
# Lint as: python3
"""This directory contains local site-specific implementations."""
# Local site-specific implementations that have to be imported to be registered
# should be imported in plugins.py.
|
from .ray_util.gif_logger import GIFLogger
def get_trainable(class_name):
if class_name == 'VPredTrainable':
from .trainable_interface import VPredTrainable
return VPredTrainable
if class_name == 'BalancedCamFilter':
from .data_filter import BalancedCamFilter
return BalancedCam... |
import abc
from datetime import date, datetime
import json
from wagtail.core.models import Page
from wagtail.documents.models import Document
from wagtail.images.models import Image
from django.forms import ValidationError
from django.forms.models import model_to_dict
from django.contrib import messages
from core im... |
import logging
from types import FrameType
from typing import cast
from loguru import logger
class InterceptHandler(logging.Handler):
loglevel_mapping = {
50: 'CRITICAL',
40: 'ERROR',
30: 'WARNING',
20: 'INFO',
10: 'DEBUG',
0: 'NOTSET',
}
def emit(self, re... |
import yaml
import argparse
import pandas as pd
from sklearn.model_selection import train_test_split
from get_data import load_config, load_data
def split(config):
split_config = config['split_data']
feature_config = config['features']
data = pd.read_csv(feature_config['path'])
x_train, x_test = train... |
# -*- coding: utf8 -*-
import sys
from frame import log
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
SEARCH_URL = "https://search.jd.com/Search?"
def good_detail_parser(keyword):
params = {
"keyword": keyword,
"enc": "utf-8"
}
search_page = requests.get(... |
.table
int soma1_param
int soma1_a3
int soma2_param3
int soma_param1
int soma_param2
int soma_result
int life_a
int life_b
int main_var = 2
int main_var2
.code
soma1:
soma1:
soma1_param:
pop soma1_param
mov $2, 1
1:
mov $3, 2
2:
mov $4, 3
3:
mul $5, $3, $4
$3:
add $6, $2, $5
$2:
mov $7, 4
4:
add $8, $6, $7
$6:
mov... |
#!/usr/bin/env python3
"""
Netflix Genre Scraper.
This tool scrapes the Netflix website to gather a list of available genres
and links to their respective pages. Please use sparingly to avoid annoying
the Netflix webservers.
"""
import argparse
import logging
import os.path
import shelve
import sys
from datetime impor... |
from __future__ import unicode_literals
import sys
def get_columns_width(rows):
width = {}
for row in rows:
for (idx, word) in enumerate(map(unicode, row)):
width.setdefault(idx, 0)
width[idx] = max(width[idx], len(word))
return width
def pprint_table(rows):
rows = list... |
import torch
from norse.torch.functional.lif_refrac import LIFRefracParameters
from dataclasses import dataclass
@dataclass
class EILIFParameters:
tau_ex_syn_inv: torch.Tensor = torch.as_tensor(
1 / (20 * 1e-3), dtype=torch.double)
tau_ih_syn_inv: torch.Tensor = torch.as_tensor(
1 / (50 * 1e-3... |
import torchvision
import torchvision.transforms as transforms
import numpy as np
from .dataset_base import BaseDataset
class IMBALANCECIFAR10(torchvision.datasets.CIFAR10, BaseDataset):
"""Imbalanced Cifar-10 Dataset
References
----------
https://github.com/kaidic/LDAM-DRW/blob/master/imbalance_cif... |
from django.conf import settings
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import TemplateView
from django.core.exc... |
from drf_yasg import openapi
from rest_framework import status
from . import sample_error_response
class SampleDistrictResponses:
def __generate_sample_districts_response(self, status_code):
"""Generates sample response for districts response"""
response = openapi.Response(
descriptio... |
class Solution:
def XXX(self, nums1: List[int], nums2: List[int]) -> float:
if nums1 or nums2:
nums = sorted(nums1 + nums2)
n = len(nums)
if n%2 == 0:
m = int(n/2 -1)
n = m+1
return (nums[m] + nums[n])/2
else:
... |
import os
import logging
from mkdocs import utils
from mkdocs.config import config_options, Config
from mkdocs.plugins import BasePlugin
log = logging.getLogger('mkdocs')
class LocalSearchPlugin(BasePlugin):
config_scheme = (
('promise_delay', config_options.Type(int, default=0)),
)
def on_post_... |
"""
#What's that ?
A set of script that demonstrate the use of Tensorflow experiments and estimators on different data types for various tasks
@brief : the main script that enables training, validation and serving Tensorflow based models merging all needs in a
single script to train, evaluate, export and serve.
taking ... |
import pandas as pd
import numpy as np
import utils
'''
MIT License
Copyright (c) 2020 Faviola Molina - dLab - Fundación Ciencia y Vida
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 re... |
from flask import Blueprint
from flask_restful import Api
from .resources import ImageAiResource
from .sentences import SentenceResource, SentenceItemResource
bp = Blueprint("restapi", __name__, url_prefix="/api/v1")
api = Api(bp)
def init_app(app):
api.add_resource(ImageAiResource, "/upload/")
api.add_reso... |
begin_unit
comment|'# Copyright 2015 IBM Corp.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
commen... |
import urllib
from bs4 import BeautifulSoup
import urlparse
import mechanize
import pickle
import re
try:
import sys
if 'threading' in sys.modules:
del sys.modules['threading']
print('threading module loaded before patching!')
print('threading module deleted from sys.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-03 09:41
from __future__ import unicode_literals
import company.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... |
try:
## Per semplificarci la vita con l'html
from bs4 import BeautifulSoup
except:
print("Devi installare bs4 per avviare questo programma.\nPer installarlo: pip install -U bs4")
try:
## Per ricevere il codice sorgente delle pagine
import requests
except:
print("Devi installare requests per avvi... |
from . import oracle
Oracle = oracle.Oracle
__version__ = "1.0.1"
__all__ = ['oracle']
|
# Generated by Django 3.0 on 2019-12-25 18:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trips', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='trip',
name='terminal',
field... |
#!/bin/env python
# -*- coding: utf-8 -*-
from io import open
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
# From https://docs.pytest.org/en/latest/goodpractices.html#manual-integration
# See if we could instead use pytest-runner
class PyTest(TestComma... |
"""Generated client library for dataproc version v1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.dataproc.v1 import dataproc_v1_messages as messages
class DataprocV1(base_api... |
import os
import tornado.ioloop
import tornado.web
import tornado.websocket
# TODO move this to cfg
PORT = 8080
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("html/index.html")
class PageNotFoundHandler(tornado.web.RequestHandler):
def get(self):
self.redirect("/",... |
# Generated by Django 2.1.3 on 2018-11-17 17:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat', '0004_remove_chat_admin'),
]
operations = [
migrations.AlterField(
model_name='chat',
name='participants',
... |
a = [5, 2, 6, 3]
print(sorted(a)) # RETURNS SORTED ARRAY => [2, 3, 5, 6]
print(a) # => [5, 2, 6, 3]
a.sort() # SORT IN ASCENDING ORDER
print(a) # [2, 3, 5, 6]
a.sort(reverse=True) # SORT IN DESCENDING ORDER
print(a) # [6, 5, 3, 2]
|
# Copyright (c) 2022. K2-Software
# All software, both binary and source published by K2-Software (hereafter, Software) is copyrighted by the author (hereafter, K2-Software) and ownership of all right, title and interest in and to the Software remains with K2-Software. By using or copying the Software, User agrees to a... |
from typing import Any
from modAL.utils.data import modALinput
from modAL import ActiveLearner
class TorchTopicsActiveLearner(ActiveLearner):
def _fit_to_known(self, bootstrap: bool = False, **fit_kwargs) -> 'BaseLearner':
pass
def _fit_on_new(self, X: modALinput, y: modALinput, bootstrap: bool = ... |
"""The go-eCharger (MQTT) switch."""
import logging
from homeassistant import config_entries, core
from homeassistant.components import mqtt
from homeassistant.components.select import SelectEntity
from homeassistant.core import callback
from .definitions import SELECTS, GoEChargerSelectEntityDescription
from .entity... |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
import asyncio
import loggi... |
# test construction of array.array from different objects
from array import array
# tuple, list
print(array('b', (1, 2)))
print(array('h', [1, 2]))
# raw copy from bytes, bytearray
print(array('h', b'12'))
print(array('h', bytearray(2)))
print(array('i', bytearray(4)))
# convert from other arrays
print(array('H', a... |
import os
import sys
from django.conf import settings
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
BASE_DIR = os.path.dirname(__file__)
DEBUG = False
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
# -*- coding:utf-8 -*-
"""
服务配置
Author: HuangTao
Date: 2018/05/03
"""
import json
from quant.utils import logger
class Config:
""" 服务配置
"""
def __init__(self):
""" 配置项
`SERVER_ID` 服务ID
`RUN_TIME_UPDATE` 是否支持配置动态更新
`LOG` 日志配置
`R... |
"""
Time: O(1)
Space: O(1), no "extra" space are used.
"""
class Solution(object):
def readBinaryWatch(self, turnedOn):
ans = []
if turnedOn>8: return ans #at most 8 LED are turned on for a valid time.
for h in xrange(12):
for m in xrange(60):
if (bin(h) + bin(m)... |
# This file contains the interfaces that can be used for any order-book on the zcoins platform.
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Text
class SingleProductOrderBook(ABC):
"""Contains the order-book for a single product."""
def __init__(self, product_id: Tex... |
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from PyQt5.QtGui import QOpenGLTexture, QImage, QAbstractOpenGLFunctions
## A class describing the interface to be used for texture objects.
#
# This interface should be implemented by OpenGL implementations to hand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.