content stringlengths 5 1.05M |
|---|
"""Integrations with external services."""
|
class Elf:
def nall_nin(self):
print('Elf says: Calling the Overlord ...')
class Dwarf:
def estver_narho(self):
print('Dwarf says: Calling the Overlord ...')
class Human:
def ring_mig(self):
print('Human says: Calling the Overlord ...')
if __name__ == '__main__':
minions = [... |
"""
# ============================================================================= #
| Project: [MuJoCo Practivces]
| Title: Python + mujoco-py
| Author: Moses C. Nah
| Email: [Moses ] mosesnah@mit.edu
| Creation Date: Monday, September 7th, 2020
# ===================================... |
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for m in moves:
if m == 'R':
x += 1
elif m == 'L':
x -= 1
elif m == 'U':
y -= 1
else:
y += 1
return x == 0 and ... |
str1 = "P@#yn26at^&i5ve"
charCount = 0
digitCount = 0
symbolCount = 0
for i in str1:
if i.isalpha():
charCount += 1
elif i.isnumeric():
digitCount += 1
else:
symbolCount += 1
print("Chars = ", charCount)
print("Digits = ", digitCount)
print("Symbol = ", symbolCount)
|
# -*- coding: utf-8 -*-
#
from collections import namedtuple
import numpy as np
XY2D = namedtuple('XY2D', ['x', 'y'])
XY2D.__doc__ = """
Namedtuple for 2D point coordinate
"""
def point_rot2D(target=XY2D(1, 1), origin=XY2D(0, 0), radians=0):
"""
Rotate a 2D point coordinate around an ori... |
from time import sleep
import platform
import os
red = '\033[1;31m'
yel = '\033[;33m'
yelf = '\033[1;33m'
fim = '\033[m'
blue = '\033[1;34m'
green = '\033[1;32m'
print('Critica social: Um jogo sem nome')
nomej = str(input('Qual o seu nome? : '))
def clear():
if platform.system() == 'Windows':
os.system("cls... |
import json
import logging
import requests
import gzip
from os.path import abspath, dirname, join
from os import remove
from pydantic import BaseModel
from typing import List
LOCAL_PATH_TO_DATA = join(
abspath(dirname(__file__)),
'../../data'
)
FILTERED_FILENAME = 'filtered_list_of_works.json'
# Wellcome_DA... |
#! /usr/bin/env python3
# coding: utf-8
from __future__ import annotations
import datetime as dt
import html
import random
import re
import typing as t
import aiosql
import bbcode
from htmlslacker import HTMLSlacker
from psycopg2.extensions import connection
from gargbot_3000 import config
forum_queries = aiosql.fr... |
import datetime
import pandas as pd
from secrets import CLIENT_ID, CLIENT_SECRET
import requests
import json
import spotipy
from spotipy.oauth2 import SpotifyOAuth
def get_spotify_data():
# Request headers
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET,
... |
import numpy as np
def waysToArrange(N, K, k):
C = np.zeros((N + 1, N + 1))
for i in range(N + 1):
for j in range(i + 1):
if (j == 0 or j == i):
C[i][j] = 1
else:
C[i][j] = (C[i - 1][j - 1] +
C[i - 1][j])
dp = np.ze... |
from django.db import models
class Parent(models.Model):
name = models.CharField(max_length=200)
age = models.PositiveIntegerField()
def __str__(self):
return f'Name: {self.name}, Age: {self.age}'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import socket
import traceback
from functools import wraps
import eventlet
eventlet.monkey_patch(thread=True, time=True)
from builtins import bytes
import click
import msgpack
import flask
from flask import (Flask, render_template, make_response, copy... |
from data_sources import DataSource
from config import config
import random as rand
class JSONonsense:
CONFIG = config["JSONONSENSE"]
MIN_KEY_PER_OBJECT = int(CONFIG['MIN_KEY_PER_OBJECT'])
MAX_KEY_PER_OBJECT = int(CONFIG['MAX_KEY_PER_OBJECT'])
MAX_DEPTH = int(CONFIG['MAX_DEPTH'])
OBJ_CHANCE = floa... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: lib.coginvasion.cog.SuitFollowBossBehavior
from lib.coginvasion.cog.SuitPathBehavior import SuitPathBehavior
from lib.coginvasion.cog.Su... |
"""Shared functionality for interacting with Galaxy.
"""
|
import sys
import logging
from rsync_workflow.RsyncContext import RsyncManager, RsyncContext, set_debug
if len(sys.argv) != 3:
logging.error('missing arguments')
logging.error('rsync_clone.py [remote_path] [local_path]')
sys.exit(-1)
rsync_manager = RsyncManager()
rsync_manager.clone(*sys.argv[1:])
|
#!/usr/bin/env python
import sys
import time
from nsnitro import *
import argparse
import datetime
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Check Netscaler HA status')
parser.add_argument('--host', metavar='HOSTNAME', required=True, help='Netscaler hostname')
parser.add_argument('--u... |
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FireFoxOptions
from selenium.webdriver.support.expected_conditions import NoSuchElementException
from .captcha_handler import CaptchaHandler
chrome... |
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
from authors.apps.authentication.models import User
from django.contrib.postgres.fields import ArrayField
class UserProfile(models.Model):
photo = models.URLField(blank=True)
user = models.OneToOn... |
from .base import *
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# BASE_URL required for notification emails
BASE_URL = 'http://localhost:8000'
try:
from .local import *
except ImportError:
pass
|
"""Responses."""
from io import StringIO
from csv import DictWriter
from typing import List
from flask import Response, jsonify, make_response
from pma_api.__version__ import __version__
class ApiResult:
"""A representation of a generic JSON API result."""
def __init__(self, data, metadata=None, **kwargs):... |
#!/usr/bin/env python3.3
import gzip, sys
if __name__=='__main__':
feature = sys.argv[1] # has to be either 'cds' or 'exon' or 'gene'
gene_list = None
feature_in_gene_list = set([])
if len(sys.argv) == 3:
gene_list = set([])
with open(sys.argv[2]) as gl:
for line in gl:
... |
'''
Copyright (C) 2019-2021, Mo Zhou <cdluminate@gmail.com>
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 t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# API module of cve-search. Returns queries in JSON format
#
# Software is free software released under the "Modified BSD license"
#
# Copyright (c) 2013-2016 Alexandre Dulaunoy - a@foo.be
# Copyright (c) 2014-2017 Pieter-Jan Moreels - pieterjan.moreels@gmail.com
# i... |
#!/usr/bin/env python3
from subprocess import call
if __name__ == "__main__":
call(["vklabs_pypi", "publish-package", "."])
|
"""
Alex Staley -- Student ID: 919519311
Assignment 2 -- February 2020
### HERE BEGINS THE Main.py FILE ###
This code creates a neural network of perceptron objects, runs the experiments
described in assignment 2, and displays the results in the prescribed format.
Parameters are set via g... |
import pandas as pd; import numpy as np
import matplotlib.pyplot as plt
import os
def IMF(m):
'''
Calculates the probability of 18<m1<m
'''
return -60.307/1.3*(m**-1.3 - 18**-1.3)
# Define directory and load data
dataDir = 'COMPAS_Output_solar_metallicity'
sysParams = pd.read_csv(os.path.join(dataDir,... |
A=["1","2","3"]
A.append("4");
def B(C):
for figure in C:
print("数字是:",C)
B(A) |
from django.urls import path
from chat.views import ChatDetailView, HomePageView
app_name = 'chat'
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('<int:user_1>/<int:user_2>/chat/', ChatDetailView.as_view(), name='chatroom_detail'),
]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 16:04:18 2019
"""
##https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py
import os
import sys
import torch
import numpy as np
# Useful PyTorch classes
class EarlyStopping:
"""Early stops the training if validation los... |
#!/usr/bin/env python
#
# Copyright 2012 Steven Le (stevenle08@gmail.com)
#
# 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... |
# Under MIT license, see LICENSE.txt
from .ai_command import AICommand
from .engine_command import EngineCommand
from .pose import Pose
from .position import Position
from .path import Path
import Util.geometry as geometry
from .singleton import Singleton
|
"""
Finger exercise: Write a program that examines three variables— x , y , and z —
and prints the largest odd number among them. If none of them are odd, it
should print a message to that effect
"""
x = int(input("Enter the value for x: "))
y = int(input("Enter the value for y: "))
z = int(input("Enter the value for... |
from setuptools import setup, find_packages
with open("README.rst", "r", encoding="utf-8") as f:
readme = f.read()
setup(
name="discord-interactions.py",
version="0.0.7",
description="A library around the Discord Interactions API",
long_description=readme,
long_description_content_type="text/x... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class UserJSONPresenter(object):
"""
Present a user in the JSON format returned by API requests.
Note that this presenter as of now returns some information
that should not be publicly available, like the users email
address. This i... |
import pandas as pd
import numpy as np
# tfidf
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import Ridge
from sklearn import linear_model
class ContentBase:
@staticmethod
def getTfidf(x_train):
transformer = TfidfTransformer(smooth_idf=True, norm='l2')
tfidf = tra... |
import scrapy
class StarWarsSpider(scrapy.Spider):
name = 'starwars'
allowed_domains = ["starwars.com"]
start_urls = ['https://www.starwars.com/databank']
def parse(self, response):
# TODO - to investigate why this line of css selector code does not work on starwars site!!?
# urls = r... |
from dataclasses import dataclass
from typing import List, Optional
from urllib.parse import urljoin
from pyvultr.utils import BaseDataclass, VultrPagination, get_only_value
from .base import BaseVultrV2, command
from .enums import ACL
@dataclass
class UserInfo(BaseDataclass):
id: str # The User's id.
api_... |
import socket, sys, os, base64, json
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.fernet import Fernet
from PyTerminalColor.TerminalColor import TerminalColor
class Client... |
#-------------------------------------------------------------------------------
# Copyright (C) 2017 Carlos Guzman (cguZZman) carlosguzmang@protonmail.com
#
# This file is part of Cloud Drive Common Module for Kodi
#
# Cloud Drive Common Module for Kodi is free software: you can redistribute it and/or modify
# it un... |
# Creates new option in main menu bar
# EDITED: 2020-08-25
# ============================================
import pymel.core as pm
import toolbox
def create_my_menu(standalone=False):
'''Creates a CSA menu with my scripts'''
reload(toolbox)
# find main maya window
main_maya_window = pm.language.melGlob... |
#!/usr/bin/env python3
import yaml, argparse
import logging as log
from pathlib import Path
from cliva_fl.experiment import Experiment
# ARGUMENT PARSING
parser = argparse.ArgumentParser(description='Argument parser for log processing and plot creation')
parser.add_argument('-r', '--repeat', type=int, default=1, re... |
import io
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
# Avoids IDE errors, but actual version is read from version.py
__version__ = None
exec(open('api/version.py').read())
# Get the long description from the README file
with io.open(os.path.... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 23:2 7:28 2019
@author: Winham
网络测试
"""
import os
import numpy as np
from keras.models import load_model
from keras.utils import to_categorical
from data_preprocess import *
import mit_utils as utils
import time
import matplotlib.pyplot as plt
import... |
class AddInId(object, IDisposable):
"""
Identifies an AddIn registered with Revit
AddInId(val: Guid)
"""
def Dispose(self):
""" Dispose(self: AddInId) """
pass
def GetAddInName(self):
"""
GetAddInName(self: AddInId) -> str
name of addin associate... |
import numpy as np
import sidpy
from tqdm import trange, tqdm
from sklearn.feature_extraction import image
from sklearn.utils.extmath import randomized_svd
def clean_svd(im, pixel_size=1, source_size=5):
"""De-noising of image by using first component of single value decomposition"""
if not isinstance(im, sid... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen, Request
import time
import plugins
import urllib2
import json
class Plugin(plugins.BasePlugin):
__name__ = 'powerdns'
def run(self, config):
'''
... |
import subprocess
import typing
def run_process(args: typing.List[str], env=None) -> bytes:
run = subprocess.run(
args,
stdout=subprocess.PIPE,
env=env,
)
if run.returncode:
raise Exception(f"Exited with code {run.returncode}")
return run.stdout
|
class GeometryBase(CommonObject,IDisposable,ISerializable):
""" Provides a common base for most geometric classes. This class is abstract. """
def ComponentIndex(self):
"""
ComponentIndex(self: GeometryBase) -> ComponentIndex
If this piece of geometry is a component in something larger,like a Brep... |
import torch
import torchvision
import net
import numpy as np
from PIL import Image
import glob
if __name__ == '__main__':
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# device = torch.device('cpu')
test_list = glob.glob("test_images/*")
dehaze_net = net.dehaze_net().to(devic... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 31 08:13:13 2019
@author: BigBoss
"""
import serial, time, threading
def medir(x):
try:
while True:
y = x.readline().decode('utf-8')
#print(y.decode("ascii",end=""))
print(y)
except:
pass
x = serial.Serial("C... |
import numpy as np
import logging
logger = logging.getLogger(__name__)
def translate_array(arr,shifts):
"""
'translate' performs integer translation on a 2D numpy array.
Params:
arr - a 2D nparray
shifts - (xshift, yshift)
Returns
new array of same shape and datatype as arr
Com... |
#!/usr/bin/python
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Name: Haohang Xu
# Date: 10/1/2015
#
# Some experimentation with multithreaded programming
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
###########################################
### ... |
"""iKala Dataset Loader
.. admonition:: Dataset Info
:class: dropdown
The iKala dataset is comprised of 252 30-second excerpts sampled from 206 iKala
songs (plus 100 hidden excerpts reserved for MIREX).
The music accompaniment and the singing voice are recorded at the left and right
channels respe... |
import autograd.numpy as anp
import numpy as np
from autograd.scipy.stats import norm
from viabel.approximations import MFGaussian, MFStudentT
from viabel.objectives import AlphaDivergence, DISInclusiveKL, ExclusiveKL
from viabel.optimization import RMSProp
def _test_objective(objective_cls, num_mc_samples, **kwargs... |
from privyfilter.privyfilter import Privyfilter as pf
faces, imger = pf.faceScrub("../TestPics/10.jpg")
print(faces)
img = pf.RemoveMetaData("../TestPics/10.jpg")
print(img)
#Synthetic face replacement ( Simple Deepfake)
#get random sythetic face
fakeface = pf.getFakeFace()
fakeface.save_image("fakeface.jpg")
faces, ... |
import sys
class Physical_person():
def __init__(self, by, dr, dt, ad):
self.birth_year = by
self.disability_rate = dr
self.disability_type = dt
self.address = ad
def __repr__(self):
return "birth_year: " + str(self.birth_year) + "\n" +\
"disability_rate: " + str(self.disability_rate) + "\n" +\
... |
import sys
import os
import json
import string
# Natural Language Toolkit Packages
from nltk import CFG, ChartParser, Tree
from nltk.tokenize import word_tokenize
from nltk.parse.generate import generate
def parse_blazon(blazon):
blazon = blazon.lower()
to_discard = set(string.punctuation)
to_discard.remo... |
from setuptools import setup
from setuptools import find_packages
setup(
name='Formula1_data_scraper',
version='0.0.6',
description='Package that allows you to collect and store into an AWS postgreSQL RDS, the qualifying and practice data from any formula 1 race weekend from 2006 onwards',
url='htt... |
# Copyright 2017 NYU-FOXTROT. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # L... |
# Copyright 2018 Max Shinn <maxwell.shinn@yale.edu>
# 2018 Norman Lam <norman.lam@yale.edu>
#
# This file is part of PyDDM, and is available under the MIT license.
# Please see LICENSE.txt in the root directory for more information.
__all__ = ["Overlay", "OverlayNone", "OverlayChain", "OverlayUniformMixture... |
import torch
import torch_stonne
a=torch.randn(6,5)
b=torch.randn(5,5)
r=torch_stonne.simulated_matmul("", a, b, "../../simulation_files/maeri_128mses_128_bw.cfg", "tile", 0)
print(r)
print(torch.matmul(a,b))
|
import FWCore.ParameterSet.Config as cms
import RecoJets.JetProducers.CaloTowerSchemeB_cfi
towerMakerWithHO = RecoJets.JetProducers.CaloTowerSchemeB_cfi.towerMaker.clone(
UseHO = True
)
|
# ==============================================================
# Author: Rodolfo Ferro
# Twitter: @FerroRodolfo
#
# ABOUT COPYING OR USING PARTIAL INFORMATION:
# This script has been originally created by Rodolfo Ferro.
# Any explicit usage of this script or its contents is granted
# according to the license provided... |
import paramiko
import sys
import datetime
import threading
import logging
"""
Edit this line and add your command
"""
#cmd2run = "for f in $(ioscli lsdev -type adapter | grep fcs | grep 8Gb | awk {'print $1'}); do wwpn=$(ioscli lsdev -dev $f -vpd | grep Network | sed s'/\.//g;s/Network Address//g;s/ //g');echo $f,$ww... |
from nltk.corpus import wordnet
from nltk.tag import pos_tag
from pattern.en import pluralize
with open('nouns.txt', 'w') as ofile:
words = set(lemma.name().replace('_', ' ')
for synset in wordnet.all_synsets(wordnet.NOUN)
for lemma in synset.lemmas())
for word, tag in pos_tag(s... |
aliases['zc'] = 'rm ~/.z'
|
"""
Signal processing utilities
Author: Nicolas EKICIER
Release: V1.52 03/2021
"""
import numpy as np
def smooth_compute(input, dim, njob=-1, cst=100, ord=3):
"""
Compute whittaker smoothing in jobs
:param input: array of vi signal
:param dim: dimension of vector signal (0 = row / 1 = ... |
from __init__ import QMainWindow
from .view import View
from .model import Model
class Controller:
def __init__(self, parent_window: QMainWindow, round: int):
super().__init__()
self.parent_window = parent_window
self.round = round
self.view = View(self.parent_window, self.round)
... |
# -*- coding:utf-8 -*-
import csv
# 先按照年份来分类
year_dict = {}
with open('./entry.csv', 'r') as entry:
reader = csv.reader(entry)
for row in reader:
if reader.line_num == 1 or reader.line_num == 2:
continue
if reader.line_num == 3:
print(row)
# if reader.line_num ... |
import os
import json
import fhirclient.models.diagnosticreport as dr
import fhirclient.models.codeableconcept as concept
import fhirclient.models.meta as meta
import fhirclient.models.resource as resource
import fhirclient.models.observation as observation
import fhirclient.models.fhirreference as reference
i... |
from bs4 import UnicodeDammit
import unicodedata
import time
import re
def ensure_unicode(value):
return UnicodeDammit(value).unicode_markup
def normalize_unicode(value):
return unicodedata.normalize("NFKD", ensure_unicode(value))\
.encode('ascii', 'ignore')
def ensure_alphanum(value):
return re.sub(r'\W', '', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import ceil, floor, log2
from os import urandom
import pytest
import winternitz.signatures
__author__ = "Harald Heckmann"
__copyright__ = "Harald Heckmann"
__license__ = "mit"
wots = None
wots2 = None
wots_strange_w = None
wots_strange_w2 = None
wotsp = None... |
from bs4 import BeautifulSoup
import requests
MAX_PAGE = 250
# defining base_url to create a list of all page urls
BASE_URL = "https://www.truecar.com/used-cars-for-sale/listings/"
# defining host_name for creating urls for each car ad
HOST_NAME = "https://www.truecar.com"
pages = list()
urls = list()
failed_pag... |
from sklearn import preprocessing
import pandas as pd
from collections import defaultdict
class DfOneHotEncoder():
def __init__(self):
self.le = defaultdict()
self.ohe = defaultdict()
self.dropped_columns = {}
def fit(self, df, columns=None, **kwargs):
self.le = df[columns].a... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 4 11:42:49 2021
@author: Easin
"""
in1 = input()
in1 = int(in1)
if in1 %2 != 0:
x = in1 -9
y = 9
else:
x = in1 -4
y = 4
print(x,y) |
import random
from tests import utils as tests_utils
from .test_event_base import SalesManagoEventsTestsBase
class SalesManagoEventDataFeatureTest(SalesManagoEventsTestsBase):
def test_requestDict_for_minimal(self):
AGAINST = {
'email': self.CLIENT_MAIL,
'owner': self.OWNER_MAIL,
... |
#!/usr/bin/python3.8
import os
import json
import aiohttp
import asyncio
import logging
import pprint
from asyncio import wait_for
from aiohttp import web
from aiohttp import client
from hpfeeds.asyncio import ClientSession
HPFSERVER = os.environ.get("HPFSERVER", "127.0.0.1")
HPFPORT = int(os.environ.get("HPFPORT", 2... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 30 13:45:39 2020
the version of loompy should be the consistent with velocyto; otherwise error returned
@author: jingkui.wang
"""
import loompy
import glob
files = glob.glob("/Volumes/groups/cochella/git_aleks_jingkui/scRNAseq_MS_lineage/data/raw_... |
import random
class room:
def room(n,e,s,w,items):
stuff = "Really cool stuff",items
doors = [["north",n],["east",e],["south",s],["west",w]]
return [doors,stuff]
class levels:
def rooms(x,y,
room1 = "room1",
room2 = "room2",
room3 = "room3",
... |
# -*- coding: utf-8 -*-
"""
CTableModel类定义文件
"""
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtCore import Qt, QVariant
from enum import IntEnum, Enum
class CTableModel(QStandardItemModel):
# 各属性项枚举
class EAttrIndex(IntEnum):
EAttr_Id = 0 # id
EAttr_Descrition = 1 # 描述
EA... |
import json
import datetime
from lib.utils.utils import DATE_STRING, DATETIME_STRING
from const.query_execution import QueryExecutionErrorType
should_escape_list = (",", '"', "\n", "\r")
def spread_dict(x, y):
z = x.copy()
z.update(y)
return z
def merge_str(str1: str, str2: str, separator: str = "\n")... |
from django.urls import resolve, reverse
import pytest
from build_migration.users.views import UserViewSet
class TestUserURLs:
"""Test URL patterns for users app."""
@pytest.mark.parametrize("url,view_class", [("/users/", UserViewSet)])
def test_users_views_resolve(self, url, view_class):
asser... |
import numpy as numpy
a = numpy.arange(16).reshape(4,4)
print ('First array')
print(a)
print('\n')
print('Horizontal splitting')
b = numpy.hsplit(a,2)
print(b)
print('\n') |
'''
# nflfantasy/fantasymath.py
# scraper/parser for fantasymath.com fantasy resources
'''
import logging
import time
from sportscraper.scraper import RequestScraper
class Scraper(RequestScraper):
'''
'''
def __init__(self, **kwargs):
'''
Scrape fantasymath API
Args:
... |
#! python
# -*- coding: utf-8 -*-
# This is a utility module for integrating SMS providers into VizAlerts.
import os
import re
import phonenumbers
import twilio
# import local modules
import config
import log
import vizalert
# store the SMS client we get back from Twilio for use across all modules
smsclient = None
... |
# SPDX-License-Identifier: Apache-2.0
# Licensed to the Ed-Fi Alliance under one or more agreements.
# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
# See the LICENSE and NOTICES files in the project root for more information.
import factory
from edfi_performance.api.client.scho... |
"""
Design your implementation of the linked list. You can choose to use the
singly linked list or the doubly linked list. A node in a singly linked
list should have two attributes: val and next. val is the value of the
current node, and next is a pointer/reference to the next node. If you want
... |
from keras.engine.saving import model_from_json
from matplotlib import image
import numpy as np
from app import SKIN_CLASSES
f = open('E:\\STUDY\PYTHON\\New folder (2)\\akiec2.jpg', 'r')
print("naerm "+ f.name)
path = 'static/data/' + f.name
f.save(path)
j_file = open('modelnew.json', 'r')
loaded_json_model = j_file.... |
from abc import ABC, abstractmethod
from typing import Dict, List, Optional
from omegaconf import DictConfig
from pydantic.dataclasses import dataclass
from pytorch_lightning.callbacks import Callback
from seg_lapa.config_parse.callbacks_available import (
CheckpointConf,
EarlyStopConf,
LearningRateMonito... |
import pandas as pd
import multiprocessing
import argparse
from functools import partial
import logging
import os, sys, glob, datetime, time, gzip
import collections
from collections import defaultdict
from math import log
from scTE.miniglbase import genelist, glload, location
from scTE.annotation import annoGtf
import... |
from typing import Any
from boa3.builtin import interop, public, type
@public
def call_flags_all() -> interop.contract.CallFlags:
return interop.contract.CallFlags.ALL
@public
def main(scripthash: type.UInt160, method: str, args: list) -> Any:
return interop.contract.call_contract(scripthash, method, args)... |
#!/usr/bin/env python3
# encoding: utf-8
"""
booleanTest.py
Created by Jakub Konka on 2010-11-21.
Copyright (c) 2010 Uni of Strathclyde. All rights reserved.
"""
import sys
import os
def boolean_test(anything):
'''Tests whether the statement is True or False
Keyword arguments:
anything -- the statement to be e... |
from datadog_checks.base import AgentCheck
from datadog_checks.base.errors import CheckException
from datadog_checks.utils.subprocess_output import get_subprocess_output
import json
EXPECTED_RESPONSE_CODE = "NO_ERROR"
class LighthouseCheck(AgentCheck):
def check(self, instance):
lighthouse_url = instance... |
# 面试题 08.01. 三步问题
# 三步问题。有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶或3阶。实现一种方法,计算小孩有多少种上楼梯的方式。结果可能很大,你需要对结果模1000000007。
# 示例1:
# 输入:n = 3
# 输出:4
# 说明: 有四种走法
# 示例2:
# 输入:n = 5
# 输出:13
# 提示:
# n范围在[1, 1000000]之间
class Solution:
data = [1, 1, 2, 4]
def waysToStep(self, n: int) -> int:
mod_num = 1000000007
... |
import FWCore.ParameterSet.Config as cms
from DQMOffline.PFTau.candidateBenchmark_cfi import *
from DQMOffline.PFTau.pfCandidateBenchmark_cfi import *
from DQMOffline.PFTau.metBenchmark_cfi import *
DQMOfflineParticleFlowSequence = cms.Sequence (
candidateBenchmark +
pfCandidateBenchmark +
metBenchmark ... |
import logging
from sqlalchemy import Column, INT, TEXT, BOOLEAN, REAL
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy_utc import UtcDateTime
from pajbot import utils
from pajbot.managers.db import Base
from pajbot.managers.so... |
from dataclasses import dataclass
from typing import Union
from postmanparser.description import Description
@dataclass
class KeyVal:
key: str
value: str
disabled: bool = False
description: Union[Description, None, str] = None
@classmethod
def parse(cls, data: dict):
description = da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.