content stringlengths 5 1.05M |
|---|
# coding=utf-8
# 错误写法
def open_file():
f = open('photo.jpg', 'r+')
jpgdata = f.read()
f.close()
#正确写法
def open_file_right():
with open('photo.jpg', 'r+') as f:
jpgdata = f.read()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 17 12:55:25 2022
@author: catal
"""
import os
import smtplib
import imghdr
from email.message import EmailMessage
email_address = os.environ.get("gmail_app_user")
email_password = os.environ.get("gmail_app_pass")
msg = EmailMessage()
msg['Subject'] = "wanna scene this ... |
#!/usr/bin/python
import copy
import cPickle
import logging
import os
import subprocess
from time import time
from fetcher import fetch
from parser import parse
import settings
class SyncStamps:
def __init__(self, videos={}, playlists={}, expires=0.0):
self.videos = videos
self.playlists = playlists
self.expi... |
#!usr/local/bin/python3.8
# -*- coding: utf-8 -*import
import random
from typing import List, Dict
from classes.magic import Magic
class BColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERL... |
import subprocess
import re
class gdb(object):
def __init__(self, python_file, cpp_file, cpp_start_line):
self.process = subprocess.Popen(["PYTHONPATH=stencil:../.. gdb python"],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, cwd='.')
self.process.stdin.write("run " ... |
"""
Realizar un programa que imprima en pantalla los números impares del 1 al 100.
Lo haremos con las diferentes opciones
* while
* for (usando “range”) y sin usar un condicional, solo con el uso del rango
"""
# while
print("======================while (impares) ======================")
i = 1
"""
Para obtener los imp... |
import unittest
from unittest import mock
from repeat import repeat
class TestException(Exception):
pass
class Repeat_Function_Test(unittest.TestCase):
def test_Should_CallFunctionUntilStopIterationException_When_Called(self):
func = mock.Mock(spec=[])
func.side_effect = [ [1], [2]... |
def Mmul(a, b): # 行列の積
# [m×n型][n×p型]
m = len(a)
n = len(a[0])
if len(b) != n:
raise ValueError('列と行の数が一致しません')
p = len(b[0])
ans = [[0]*p for _ in range(m)]
for i in range(m):
for j in range(p):
for k in range(n):
ans[i][j] += a[i][k]*b[k][j] % M... |
from telegram import Update
from core import CoreContext
from core.session import message_wrapper
@message_wrapper
def reset(update: Update, context: CoreContext):
if not context.user.token:
context.chat.send_message("Anda sudah keluar fitur elearning.")
return -1
context.user.token = None
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Use 'Agg' to generate PNGs of graphs without displaying via X.
# If X works, you can comment the following two lines:
#import matplotlib
#matplotlib.use('Agg')
from balltracker.image import ImageStack
from balltracker.ball import ballSequence
def main():
... |
# Generated by Django 3.1.4 on 2020-12-25 15:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_comment'),
]
operations = [
migrations.AddField(
model_name='comment',
name='email',
... |
import seaborn as sns
sns.set_style("whitegrid")
penguins = sns.load_dataset("penguins")
def func(input="green"):
plot = sns.displot(penguins, x="flipper_length_mm", color=input, legend=False)
fig0 = plot.fig
fig0.set_size_inches(11, 8)
return fig0
import panel as pn
pn.extension()
select = pn.widg... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
import openpyxl
import csv
from django.urls import reverse
from django.views.generic import FormView, CreateView
from django.forms import ModelForm, HiddenIn... |
#data derived from http://www.data-compression.com/english.html
freqs = {'a': 0.080642499002080981, 'c': 0.026892340312538593, 'b': 0.015373768624831691, 'e': 0.12886234260657689, 'd': 0.043286671390026357, 'g': 0.019625534749730816, 'f': 0.024484713711692099, 'i': 0.06905550211598431, 'h': 0.060987267963718068, 'k': 0... |
import json
import os
import re
import numpy as np
from django.conf import settings
from django.views.decorators.csrf import csrf_protect
from django.core.files.storage import FileSystemStorage
from django.shortcuts import redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
from d... |
# File: ciscoesa_view.py
#
# Copyright (c) 2017-2022 Splunk 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 appl... |
from django.urls import path
from plugins.ctftime.views import CTFTimeView
app_name = 'ctftime'
urlpatterns = [
path('', CTFTimeView.as_view(), name='ctftime'),
]
|
# Generated by Django 3.0.6 on 2020-05-29 20:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20200529_1952'),
]
operations = [
migrations.AlterField(
model_name='product',
name='label',
... |
"""Contains the utilities to display things on the screen
"""
class FixedWidth():
"""Utility to display information in a tabulated manner
"""
def __init__(self, dimensions: dict):
"""
Args:
dimensions: dict containing fields as keys and column width (ints) as values
... |
import os
import sys
import requests
import subprocess
installer_version_url = 'https://public.api.mindsdb.com/installer/@@beta_or_release/docker___success___None'
api_response = requests.get(
installer_version_url.replace('@@beta_or_release', sys.argv[1]))
if api_response.status_code != 200:
exit(1)
instal... |
# Generated by Django 3.1.3 on 2021-04-06 05:32
import itertools
from django.db import migrations
from library.vcf_utils import get_variant_caller_and_version_from_vcf
def _get_variant_caller_from_vcf_file(VariantCaller, vcf_path):
variant_caller, version = get_variant_caller_and_version_from_vcf(vcf_path)
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# ... |
#!/usr/bin/env python3
from flask import Flask, redirect, render_template, request
from mini_cactpot import Result
app = Flask(__name__)
@app.context_processor
def ticket_payout():
"""
Make the values of payouts available to all templates
"""
values = [10000, 36, 720, 360, 80, 252, 108, 72, 54, 180,... |
import gym
import model
import exp_replay
import random
from wrappers import *
import torch
import torch.nn.functional as F
from collections import namedtuple
from tqdm import tqdm
from itertools import count
class Agent():
def __init__(self,action_space,frame_history_len,env,device,buffer_size,\
epsilon_start... |
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('SECRET_KEY', 'development_key')
DEBUG = True
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '*').split(':')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'djan... |
#
# Copyright (c) 2020 by Delphix. All rights reserved.
#
#######################################################################################################################
"""
This module contains common functionality that is being used across plugin. Like bucket size calculation, read file,
write data into fi... |
import logging
from selenium import webdriver
import time, re
from selenium.webdriver.support.select import Select
import threading
# 세마포어 기법 적용
sem = threading.Semaphore(1)
def login(browser):
with open("secret.txt", "r") as f:
line = f.readline()
loginId = line.split(':')[-1].replace('\n', '').... |
def const(a, b):
def result():
return a
def zilch(b):
return b
return result()
|
import time
import gym
import matplotlib.pyplot as plt
import torch
import numpy as np
from test_agents.PGAgent.agent import Agent as PGAgent
from test_agents.PGAgent_FCModel.agent import Agent as PGAgent_FCModel
from utils import save_plot
import wimblepong
# Make the environment
env = gym.make("WimblepongVisualSi... |
from __future__ import print_function, division
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, concatenate
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from k... |
import csv
import json
import re
dataRows = [];
headerRow = [];
with open('../data/8_Parents_Meet.csv', newline='',encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=',',quotechar='"',skipinitialspace=True)
isHeader = True;
for row in reader:
if(not isHeader):
age = 'young'
if(row[2] == '2... |
from setuptools import setup, find_packages
setup(
name="iris",
version="1.0",
py_modules=['iris'],
packages=find_packages(),
python_requires='>=3',
install_requires=['click', 'newspaper3k', 'twython'],
entry_points='''
[console_scripts]
iris=iris:cli
''',
)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=True)
class BasicBlock(nn.Module):
expansion = 1
... |
import numbers
import array
real_types = [numbers.Real]
int_types = [numbers.Integral]
complex_types = [numbers.Complex]
iterable_types = [set, list, tuple, array.array]
try:
import numpy
except ImportError:
pass
else:
real_types.extend([numpy.float32, numpy.float64])
int_types.extend([numpy.int32, nu... |
#!/usr/bin/env python2.7
'''A simple test for :class:`PVPositioner`'''
import time
import epics
import config
from ophyd import (PVPositioner, PVPositionerPC)
from ophyd.signal import (EpicsSignal, EpicsSignalRO)
from ophyd.device import (Component as C)
logger = None
def put_complete_test():
logger.info('--> ... |
import logging
import os
import shutil
import uuid
from subprocess import CalledProcessError
from typing import List, Iterable
from django.conf import settings
from django.db import models
from django.db.models import CASCADE, Q
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from ... |
from django.contrib.auth import user_logged_out
from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
# Create your models here.
from django.db.models.signals import post_save
from django.dispatch import receiver
from argos.libs.clients.aniketos import AniketosClient... |
import datetime
from pydantic import BaseModel
from typing import Optional
class MortgageCalculatorRequest(BaseModel):
propertyValue: Optional[float]
downPayment: Optional[float]
interestRate: Optional[float]
loanTermYears: Optional[int]
startDate: Optional[datetime.datetime]
pmi: Optional[fl... |
'''
Copyright (c) 2017 Mark Fisher
Licensed under the MIT License, see LICENSE in the project root for full license.
This module contains an icon provider for use with a QFileSystemModel, where the icons are specified
using a JSON settings file.
The format of the JSON file should be:
{
"types" : {
"Compu... |
D = [[[0]*110 for i in range(110)] for j in range(110)]
N,L,R = map(int,input().split())
D[1][1][1] = 1
Mod = 1000000007
for i in range(2,N+1):
for j in range(1,L+1):
for k in range(1,R+1):
D[i][j][k] = (D[i-1][j][k-1] + D[i-1][j-1][k] + (i-2)*D[i-1][j][k]) %Mod
# 1. i 번째 건물을 추가할 때, ... |
#! /usr/bin/env python
##############################################################################
# CreateJPEGKMZ.py
# A class to read EXIF data from geotageged JPEG files and
# create a KMZ File containing a quick look PNG
#
# Function for reading EXIF data modified from one
# proposed on http://stackoverflow.... |
#!/usr/bin/env python
from tabulate import tabulate
from time import sleep
import unittest
class Instr():
def __init__(self, count):
self._count = count
def isExit(self):
return False
@property
def count(self):
return self._count
def expand(self):
... |
"""
Code adapted from by: https://github.com/dgilland/pydash
"""
import collections
def get(obj, path, default=None):
current = obj
for key in path:
if isinstance(current, list) and isinstance(key, int):
if key < 0 or key >= len(current):
return default
else:
... |
"""Unit tests for readme.py"""
import re
from .readme import locate_badges, merge_badges, RE_MARKDOWN_IMAGE
def test_match_screenshot():
"""Tests replacing a screenshot with the module's regex"""
input_readme = """
# GodFather
A Delphi app to rename files (legacy project)
:
def __init__(self, url=None):
self._url = url or config.get_string(
"koapy.utils.me... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import functools
import cv2
import math
import numpy as np
import imageio
from glob import glob
import os
import copy
import shut... |
class DajareModel:
__text: str
__is_dajare: bool
__score: float
__reading: str
__applied_rule: str
@property
def text(self) -> str:
return self.__text
@text.setter
def text(self, text: str):
if not isinstance(text, str):
raise TypeError('invalid type')
... |
from utils import CSVScraper
class VancouverPersonScraper(CSVScraper):
# https://opendata.vancouver.ca/explore/dataset/elected-officials-contact-information/
csv_url = 'https://opendata.vancouver.ca/explore/dataset/elected-officials-contact-information/download/?format=csv&timezone=America/New_York&use_labels... |
import time
import gym.spaces
import numpy as np
import tensorflow as tf
from rlutils.replay_buffers import PyUniformReplayBuffer
from rlutils.infra.runner import TFRunner, run_func_as_main
from rlutils.tf.nn.models import EnsembleDynamicsModel
from rlutils.tf.nn.planners import RandomShooter
class PETSAgent(tf.kera... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ans = 0
dic = {}
i = 0
for j in range(len(s)):
i = max(dic.get(s[j], 0), i)
ans = max(ans, j - i + 1)
dic[s[j]] = j + 1
return ans |
from context import vfdb_to_seqfindr
|
from dataclasses import dataclass
@dataclass()
class ExperimentPaths(object):
pose_resnet_weights_path: str
pose_2d_coco_only_weights_path: str
pedrec_2d_path: str
pedrec_2d_h36m_path: str
pedrec_2d_sim_path: str
pedrec_2d_c_path: str
pedrec_2d_h36m_sim_path: str
pedrec_2d3d_h36m_path:... |
import random
import time
import orco
@orco.builder()
def do_something(config):
time.sleep(0.3) # Simulate computation
return random.randint(0, 10)
@orco.builder()
def make_experiment(config):
data = [do_something(x) for x in range(config["difficulty"])]
yield
time.sleep(config["difficulty"]) ... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from nipy.testing import *
from nipy.core.reference.slices import bounding_box, \
zslice, yslice, xslice
from nipy.core.reference.coordinate_map import AffineTransform
# Names for a 3D axis set
names = ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from fvcore.nn.focal_loss import sigmoid_focal_loss
from detectron2.layers.wrappers import cat
def _rezise_targets(targets, height, width):
"""
Resize the targets to the same size of logits (add height and width channels)
"""
targets ... |
from conans import ConanFile, CMake, tools
import os, platform
eastl_version = os.getenv('EASTL_VERSION', '0.0')
eastl_commit = os.getenv('EASTL_COMMIT', '')
class EASTLConan(ConanFile):
name = "eastl"
license = "MIT"
url = "https://github.com/BentouDev/conan-eastl"
version = eastl_version
commit ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Daniel E. Cook
"""
import os
import gunicorn # Do not remove this line - this is here so pipreqs imports
import click
from click import secho
from base.utils.gcloud import get_item
from base.utils.data_utils import zipdir
from base.database import (initializ... |
def get_expected(placed, lowest, override):
partial = [p for p in placed if p <= lowest]
if override > 0:
partial = partial[:-override]
only_mine = 37 - len(placed)
lowest_cnt = only_mine + len(partial)
if lowest_cnt == 0: return 0
ret = 0.0
ret += lowest * 36.0 * only_mine / fl... |
# coding=utf-8
# Copyright 2021 The init2winit 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 la... |
# coding=utf-8
# Copyright 2022 The Robustness Metrics 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 appli... |
"""
Tests all snippets in the docs and readme like this:
```yaml
rules:
```
To exclude, use shorthand `yml`.
"""
import re
import fs
from schema import SchemaError
from organize.actions import ACTIONS
from organize.config import CONFIG_SCHEMA, load_from_string
from organize.filters import FILTERS
RE_CONFIG = re.c... |
from .forms import ContactForm
from django.contrib import messages
from django.conf import settings
from django.shortcuts import reverse, redirect, render
from post_office import mail
def index(request):
context = {}
return render(request, 'DSSCDB/index.html', context)
def contact_us(request):
form_dat... |
def add(x: int, y: int) -> int:
"""Take two integers and returns the sum of them."""
return x + y
|
from lib import action
class ConsulAclCreateAction(action.ConsulBaseAction):
def run(self, name=None, acl_type='client', rules=None):
rules = rules.encode('ascii','ignore')
acl_id = self.consul.acl.create(name=name, type=acl_type, rules=rules)
return acl_id
|
from Assistant.exts.networks import internetConnection
from Assistant.utils.exceptions import InternetException
if internetConnection() is False:
raise InternetException(
"Alice works with INTERNET, Please get connected with INTERNET."
)
import threading
from os import startfile, path
import sys
impo... |
from lxml import etree
from parser import Parser
from utils import tidy_dict
'''
strip out some identified set of elements for the
triplestore/ontology definitions
strip out the rest of the text with associated, namespaced xpath
just in case?
'''
class BaseReader():
'''
parameters:
_service_descri... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path("login", views.LoginView.as_view(), name="login"),
path("logout", views.LogoutView.as_view(), name="logout"),
path("register", views.RegisterView.as_view(), name="register"),
... |
"""summary cope survey fields
Revision ID: 16452fdb1334
Revises: c0394a487b8b
Create Date: 2020-05-12 14:02:39.592019
"""
from alembic import op
import sqlalchemy as sa
import rdr_service.model.utils
from sqlalchemy.dialects import mysql
from rdr_service.participant_enums import PhysicalMeasurementsStatus, Questionn... |
import setuptools
from setuptools import setup, find_packages
import os
path = os.path.dirname(__file__)
with open(path + "/README.src.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='jittor',
version='1.0.0',
# scripts=[],
author="Jittor Group",
author_email="ran.dongl... |
from typing import Optional
from pydantic import BaseSettings
class EnvSettings(BaseSettings):
SQL_DSN: Optional[str] = "sqlite:///db.sqlite3"
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
|
from django.utils import translation
class PybbMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
profile = request.user.pybb_profile
language = translation.get_language_from_request(request)
if not profile.language:
... |
import simtk.unit as u
from simtk.openmm import app
import simtk.openmm as mm
from openmoltools import gafftools, system_checker
ligand_name = "sustiva"
ligand_path = "./chemicals/%s/" % ligand_name
temperature = 300 * u.kelvin
friction = 0.3 / u.picosecond
timestep = 0.1 * u.femtosecond
prmtop = app.AmberPrmtopFile... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from recipe import views
# defaultRouter will generate routes for our views(recipe.views)
router = DefaultRouter()
router.register('tags', views.TagViewSet)
router.register('ingredients', views.IngredientViewSet)
# for reverse() ... |
import os
import torch
from autoattack import AutoAttack
from torch.utils import data
from lens.models.robust_cnn_classifier import RobustCNNClassifier
from lens.utils.datasets import SingleLabelDataset
class AdversarialAttackError(BaseException):
pass
class AdversarialAttackNotPerformedError(AdversarialAttac... |
import config
import redis
import telebot
bot = telebot.TeleBot(config.API_TOKEN)
db = redis.Redis.from_url(config.REDIS_URI)
|
# Generated by Django 2.0.7 on 2020-05-06 04:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('categories', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='categories',
name='subcategories',... |
import collections
import numpy as np
class QCAspect(collections.namedtuple('QCAspect', 'label units data comment doi glossary')):
"""Facilitates the storage of quantum chemical results by labeling them with basic metadata.
Attributes
----------
label : str
Official label for `data`, often qc... |
# Generated by Django 2.2.24 on 2022-03-06 04:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('appearance', '0003_auto_20210823_2114'),
]
operations = [
migrations.AddField(
model_name='theme',
name='brand_name... |
# 2100. Свадебный обед
# solved
invitations_num = int(input())
friends_total = 2
for i in range(invitations_num):
friend_name = input()
if friend_name.find('+') != -1:
friends_total += 2
else:
friends_total += 1
if friends_total == 13:
friends_total += 1
print(friends_total * 100)
|
#!/usr/bin/env python
########################################################################.......
u"""filenav for Pythonista, version 2, by dgelessus.
This is the "slim" version of filenav 2. It consists of a single
navigable table and is thus ideal for use on an iPhone or iPod touch, or
even on an iPad in popover ... |
# -*- coding: utf-8 -*-
# !/usr/bin/python
import ctypes
import logging
import sys
import traceback
from lazagne.config.change_privileges import list_sids, rev2self, impersonate_sid_long_handle
from lazagne.config.users import get_user_list_on_filesystem, set_env_variables, get_username_winapi
from lazagne.config.dpap... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class PolyLine:
def __init__(self, segments=[]):
self.segments = segments
@staticmethod
def name():
return 'Poly Line'
def render(self, qp):
for seg in self.segments:
seg.render(qp)
def add_segment(self, value):
... |
#!/usr/bin/env python3
import socket
from IPy import IP
class DomainIPError(Exception):
pass
def get_ip(ip: str):
try:
IP(ip)
return ip
except ValueError:
try:
return socket.gethostname(ip)
except:
print()
raise DomainIPError
def scan_... |
"""
Forecast One By One
===================
A useful feature for short-term forecast in Silverkite model family is autoregression.
Silverkite has an "auto" option for autoregression,
which automatically selects the autoregression lag orders based on the data frequency and forecast horizons.
One important rule of this ... |
#
# Copyright (c) 2012, 2013, 2014 Hewlett-Packard Development Company, L.P.
#
# 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 requi... |
# Copyright 2016 The TensorFlow 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 applica... |
# Method one
def divisors(n):
if n == 1:
return "{} is prime".format(n)
else:
c = [x for x in range(2,n//2+1) if n%x==0]
if len(c)==0:
return "{} is prime".format(n)
else:
return c
print(divisors(12))
print(divisors(25))
print(divisors(13))
print("--------... |
class Solution:
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
times = []
for i in range(12):
for j in range(60):
if bin(i).count('1') + bin(j).count('1') == num:
times.append('{:d}:{:... |
import disnake
from disnake import ui, ButtonStyle
import configs
from bot import util
from bot.tickets import TicketType
class TicketOpeningInteraction(ui.View):
def __init__(self):
super().__init__(timeout=None)
@ui.button(label='Plainte', style=ButtonStyle.blurple, custom_id=configs.TICKET_COMPLA... |
# Copyright 2016 The TensorFlow 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 appl... |
"""Tests for the more idiomatic python client.
These are light, because exceptions, arg parsing happen serverside.
"""
import datetime
import random
import string
import unittest
import seer
class TestClient(unittest.TestCase):
def setUp(self):
self.name = ''.join(random.choice(string.ascii_uppercase +... |
if 0:
import astropy.io.fits as pyfits, os
#catalog = '/u/ki/dapple/nfs12/cosmos/cosmos30.slr.matched.cat'
catalog = '/u/ki/dapple/nfs12/cosmos/cosmos30.slr.cat'
p = pyfits.open(catalog)['OBJECTS']
print p.columns
#print p.data.field('z_spec')[4000:5000]
filters = ['MEGAPRIME-0-1-u','S... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: xu.peng
@file: config.py
@time: 2019/9/5 2:00 PM
@desc:
'''
data_path="/Users/wll/AI-MLTraining/mltraining/notebook/科学比赛/CCF-EAOIN/data"
train_data_text=data_path+"/Train/Train_DataSet.csv"
train_data_label=data_path+"/Train/Train_DataSet_Label.csv"
test_data_text... |
from esper.main import EsperTest
def test_esper():
# test esper without any subcommands or arguments
with EsperTest() as app:
app.run()
assert app.exit_code == 0
def test_esper_debug():
# test that debug mode is functional
argv = ['--debug']
with EsperTest(argv=argv) as app:
... |
# -*- coding: utf-8 -*-
"""Unit test package for onlinecourses_ooo."""
|
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.