content stringlengths 5 1.05M |
|---|
import types
import logging
import datetime
from google.appengine.ext import db
from google.appengine.ext import blobstore
from google.appengine.ext.db.metadata import Kind
from bottle import Bottle, run, template, abort, request, response, redirect
from cork import get_flash, set_flash, SUCCESS, ERROR, stripslashes
... |
# Generated by Django 3.1.dev20200305084444 on 2020-04-21 15:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Project', '0015_auto_20200421_2009'),
]
operations = [
migrations.RenameField(
model_name='employee',
old_na... |
import sys
import clang.cindex
from dataclasses import dataclass, field
from mako.template import Template
@dataclass
class Struct:
namespace:list = field(default_factory=list)
name:str = ""
fields:list = field(default_factory=list)
def collectStructs( node, namespace = [] ):
structs =[]
for child in node.get... |
import pydash
import pytest
from unittest.mock import patch
from io import StringIO
from azure.ai.ml import command, MpiDistribution, dsl, Input, Output
from azure.ai.ml._restclient.v2022_05_01.models import TensorFlow
from azure.ai.ml._utils.utils import load_yaml
from azure.ai.ml.entities import (
Component,
... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 The Cirq Developers
#
# 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 appli... |
from .env import WorldEnv
def make_env(args):
return WorldEnv() |
import pathlib, sys
home_path = pathlib.Path('.').resolve()
while home_path.name != "membership_inference_attack":
home_path = home_path.parent
utils_path = home_path/'src'/'utils'
if utils_path.as_posix() not in sys.path:
sys.path.insert(0, utils_path.as_posix())
import torch
import torch.utils.data
import t... |
import csv
try:
import importlib.resources
except ImportError:
pass
class IANAList:
def __init__(self):
self.used_ports = set()
raw = importlib.resources.read_text('str2port', 'iana.csv').strip().split('\n')
records = csv.DictReader(raw)
for record in records:
p... |
print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*... |
from flask import Flask, request, jsonify
import sqlite3
import time
import os
import sys
database_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "database.db")
app = Flask(__name__)
@app.route('/', methods=['GET'])
def get_api_version():
return 'API V1'
@app.route('/api/get/all', methods... |
import codecs
import io
from datetime import datetime
from pathlib import Path
import pandas as pd
import spacy
# nlp = spacy.load("../CustomNERData")
nlp = spacy.load("el_core_news_lg")
# with open("zeroUrlText.txt", "r", encoding='utf8') as text_file:
# text = text_file.read()
with open("zeroUrlSubject.txt", "... |
import pymysql
import json
def insertsql_from_json():
#connect
conn = pymysql.connect(
host="",
port=3306,
user="root",
password="",
database="",
charset="utf8"
)
curs = conn.cursor()
with open("foul_of.json","r",encoding="utf8") as json_file:
... |
from django.contrib import admin
from django import forms
from . import models
class procedure_s9AdminForm(forms.ModelForm):
class Meta:
model = models.procedure_s9
fields = "__all__"
class procedure_s9Admin(admin.ModelAdmin):
form = procedure_s9AdminForm
list_display = [
"N_pr... |
from aif360.algorithms.inprocessing.adversarial_debiasing import AdversarialDebiasing
from aif360.algorithms.inprocessing.adversarial_error_debiasing import AdversarialErrorDebiasing
from aif360.algorithms.inprocessing.art_classifier import ARTClassifier
from aif360.algorithms.inprocessing.prejudice_remover import Prej... |
"""
Before going through the code, have a look at the following blog about AVL Tree:
https://en.wikipedia.org/wiki/AVL_tree
@author: lashuk1729
"""
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
class AVL_Tree():
def ge... |
import numpy as np
from scipy.integrate import simps
def cog(input_data,wave,wave_axis,lande_factor=0,cpos = False):
'''
Calculates the velocity [and longitudinal field] of a profile or set of profiles using CoG technique.
input_data: the input data may have dimmensions of:
[wave] = 1D the program... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request,FormRequest
class LonginspiderSpider(scrapy.Spider):
name = 'loginSpider'
allowed_domains = ['example.webscraping.com']
# 爬取只能用户登录后才能爬取的数据
start_urls = ['http://example.webscraping.com/places/default/user/profile']
def parse(self... |
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from accounts.models import get_sentinel_user
from django.conf import settings
from core.models import SiteCustomization
class Command(BaseCommand):
def _create_site(self):
example_site = Site.objects.get(pk=1... |
#!/usr/bin/env python
'''
Naive parallel algorithm of prefix sum
http://people.cs.vt.edu/yongcao/teaching/cs5234/spring2013/slides/Lecture10.pdf
'''
import threading
# look maybe multiprocessing lib
import TestFunction
test_data = [2,6,2,3,5]
'''
Generic sum function
'''
def accumulate(in_list, amo... |
from __future__ import absolute_import
from .models import UEditor, UEditorField
from .widgets import AdminUEditor
__all__ = ['UEditor', 'UEditorField', 'AdminUEditor']
|
"""A launcher script for running algorithms."""
if __name__ == '__main__':
import argparse
import gym
parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, required=True)
parser.add_argument('--alg', type=str, required=True)
known_args, unknown_args = parser.parse_known_arg... |
from enum import Enum
class KillType(Enum):
NONE = 0
CURRENT = 1
ALL = 2
def __bool__(self):
return self != KillType.NONE
# Python2 compatibility
__nonzero__ = __bool__
|
import numpy as np
import paddle
import paddle.nn.functional as F
from paddle import ParamAttr
from paddle.nn import Layer
from paddle.nn import Conv2D
from paddle.nn.initializer import XavierUniform
from paddle.regularizer import L2Decay
from ppdet.core.workspace import register, serializable
@register
@serializable... |
def __chooseObjectFromList(ctx, objects, attribute):
# TODO: use entropy
random = ctx.random
temperature = ctx.temperature
weights = [
temperature.getAdjustedValue(
getattr(o, attribute)
)
for o in objects
]
return random.weighted_choice(objects, weights)
d... |
# -*- coding: utf-8 -*-
# python.
import datetime
# ------------------------------------------------------------
# django.
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.utils.translat... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
"""
Slixmpp: The Slick XMPP Library
Copyright (C) 2010 Nathanael C. Fritz, Lance J.T. Stout
This file is part of Slixmpp.
See the file LICENSE for copying permission.
"""
import logging
import threading
from slixmpp import Iq
from slixmpp.exceptions import XMPPError, IqError, IqTimeout
from slixmpp.x... |
def parameters(net, base_lr):
total_length = 0
default_lr_param_group = []
lr_mult_param_groups = {}
for m in net.modules():
# print(type(m), len(list(m.named_parameters(recurse=False))))
# print(list(m.named_parameters(recurse=False)))
total_length += len(list(m.parameters(recu... |
##############################################################################
# Copyright 2018 Rigetti Computing
#
# 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://ww... |
import ray
@ray.remote(num_cpus=8)
def f():
print('blah')
return True
ray.init(address="auto")
[f.remote() for _ in range(100)]
|
import logging
import os
class Utility():
"""This class is the utility for named entity recognition."""
def __init__(self, debug_mode=False, verbose_mode=False, callback_status=None, callback_progress=None):
"""Creates Utility instance.
Args:
bool *debug_mode*: toggle logger level... |
def invert(image):
for row in range(image.shape[0]):
for col in range(image.shape[1]):
for c in range(3):
image[row][col][c] = -image[row][col][c]
|
'''
TMC, XTI, tsproj parsing utilities
'''
import collections
import logging
import os
import pathlib
import re
import types
import lxml
import lxml.etree
from .code import (get_pou_call_blocks, program_name_from_declaration,
variables_from_declaration, determine_block_type)
# Registry of all Twi... |
import sublime
import sys, os
def plugin_loaded():
editor_dir = sys.path[0]
if editor_dir in os.environ['PATH']:
return
settings = sublime.load_settings('PortableInstallationHelper.sublime-settings')
if settings.get('subdir') is None:
print("="*86)
print("PortableInstallationHelper: Error loading settings.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Schooner - Course Management System
# University of Turku / Faculty of Technilogy / Department of Computing
# (c) 2021, Jani Tammi <jasata@utu.fi>
#
# AssistantWorkqueue.py - Data object for assistant workqueue
# 2021-09-04 Initial version.
# 2021-09-25 Support f... |
"""
Mask R-CNN
Train on my occ5000 dataset
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Kidd Liu
"""
import os
import sys
import datetime
import numpy as np
import skimage.draw
# Root directory of the projec
ROOT_DIR = os.getcwd()
if ROOT_DIR.endswith("sam... |
class LocationConfig():
def __init__(self, core_config: dict):
self.core_config = core_config
self.county = None
self.county_code = None
@property
def city(self):
"""The current value of the city name in the device configuration."""
return self.core_config["l... |
"""
Let's see how a class gets actually created
define a body of class with constructor and methods
create dictionary to have constructor and methods in it.
Create a new class Spam using type method, class name as first
argument, second base classes from which it inherits and pass
clsdict as third argument as dictionar... |
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from .views import FrameCreateView, FrameDetailsView, SpaceDetailsView, SpaceCreateView, AgentCreateView, AgentDetailsView
urlpatterns = {
url(r'^auth... |
from unittest.mock import patch
from phoenix.integration.datadog import get_all_slack_channels
@patch("phoenix.integration.datadog.api.Monitor.get_all")
def test_get_all_slack_channels(mocked_get_all):
mocked_get_all.return_value = (
"@slack-alerts{{/is_warning}}{{#is_warning_"
"recovery}}@slack-... |
#!/usr/bin/env python3
scores = {
"John": 75,
"Ronald": 99,
"Clarck": 78,
"Mark": 69,
"Newton": 82,
}
grades = {}
for name in scores:
score = scores[name]
if score > 90:
grades[name] = "Outstanding"
elif score > 80:
grades[name] = "Exceeds Expectations"
elif score ... |
"""Task that gives reward at regular intervals during task."""
from . import abstract_task
class StayAlive(abstract_task.AbstractTask):
"""StayAlive task. In this task a reward is given at regular intervals."""
def __init__(self, reward_period, reward_value=1.):
"""Constructor.
Args:
... |
from pathhack import pkg_path
import os
import pickle
import numpy as np
from os.path import join
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib import gridspec
import matplotlib.patches as patches
from matplotlib.animation import FuncAnimation
plt.rc('xtick', labelsize=15)
pl... |
"""
Creates a new pytplot variable as the time average of original.
Notes
-----
Similar to avg_data.pro in IDL SPEDAS.
"""
import numpy as np
import pyspedas
import pytplot
def avg_data(names, dt=None, width=60, noremainder=False,
new_names=None, suffix=None, overwrite=None):
"""
Ge... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
import os
import hashlib
import unittest
from scrapy.http import Request, Response
from scrapy.spider import Spider
from scrapy.utils.test import get_crawler
from scrapy.exceptions import NotConfigured
from hubstorage import HubstorageClient
from scrapy_hcf import HcfMiddleware
HS_ENDPOINT = os.getenv('HS_ENDPOINT',... |
from ctypes import (
string_at,
addressof,
sizeof,
create_string_buffer,
cast,
pointer,
POINTER,
)
# converts a ctype into a string
def pack(ctype_instance):
return string_at(addressof(ctype_instance), sizeof(ctype_instance))
# convert from string to ctype
def unpack(ctype, string):
... |
## -*- coding: UTF-8 -*-
## init.py
##
## Copyright (c) 2019 libcommon
##
## 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... |
from django.contrib.auth import get_user_model, logout
from django.contrib.auth.forms import UserCreationForm
from django.conf import settings
from django import forms
from django.forms.utils import ErrorDict
from django.test import override_settings
from django.core.cache import cache
from django.core.exceptions impor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('robocrm', '0045_machine_toolbox_id'),
]
operations = [
migrations.AlterField(
model_name='machine',
... |
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ans = list()
nums = sorted(nums)
for i, num_0 in enumerate(nums):
if i>0 and nums[i] == nums[i-1]:
continue
left = i... |
# Questão 2: Estruturas de repetição
""" Use a função len(string) para saber o tamanho de um texto (número de caracteres). """
class Contagem:
def escreverTexto(self):
texto = input("Escreva o texto: ")
contagem = len(texto)
print(f"O texto possui {contagem} caracteres.")
... |
from tests.testcase import TestCase
from edmunds.localization.localizationmanager import LocalizationManager
from edmunds.localization.location.drivers.googleappengine import GoogleAppEngine
class TestLocalization(TestCase):
"""
Test the Localization
"""
def test_not_enabled(self):
"""
... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
# -*- coding: utf-8 -*-
class BaseConfig(object):
DEBUG = True
|
import collections
from typing import Dict, Any, Tuple, List
import tensorflow as tf
from dpu_utils.mlutils import Vocabulary
import encoders.utils.tree_processing
from utils import data_pipeline
from .encoder import Encoder, QueryType
def _try_to_queue_node(
node: encoders.utils.tree_processing.TreeNode,
... |
_class_registry_cache = {}
_field_list_cache = []
def _import_class(cls_name):
"""Cache mechanism for imports.
Due to complications of circular imports mongoengine needs to do lots of
inline imports in functions. This is inefficient as classes are
imported repeated throughout the mongoengine code. ... |
from bs4 import BeautifulSoup
from rawdata.EN_F14 import s
def is_course(c):
if c.count("-") == 2 and len(c) == 12:
return True
def is_teacher(c):
if c.replace(" ", "").replace("-", "").isalpha():
return True
soup = BeautifulSoup(s)
td = soup.get_text().split("\n")
all_data = []
index = 0
... |
alph = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ_.")
while True:
try:
n, mes = input().split(" ")
n = int(n)
except ValueError:
break
mes = list(mes[::-1])
for i in range(len(mes)):
ind = alph.index(mes[i])
mes[i] = alph[(ind + n) % len(alph)]
final = ""
for char i... |
from functools import wraps
import google.oauth2.id_token
from flask import current_app, g, request
from google.auth.transport import requests
from werkzeug.exceptions import Unauthorized
google_requests = requests.Request()
def jwt_validate(f):
@wraps(f)
def decorated_function(*args, **kwargs):
id_... |
#!/usr/bin/python
# coding=utf-8
import sys
import time
import sqlite3
import telepot
from pprint import pprint
from datetime import date, datetime
import re
import traceback
ROOT = '/root/git/stock-analyzer/'
def sendMessage(id, msg):
try:
bot.sendMessage(id, msg)
except:
print str(datetime.n... |
import os
HUClist = ["1002", "1003", "1004"] # HUC4 geospatial tiles to search over.
inDir = "../data/cov/static" # Source parameter grid folder.
FCPGdir = "../FCPGs" # Output FCPG folder.
covList = [] #Initialize list of parameter grids.
# iterate through all source parameter grids.
if os.path.isdir(inDir):
... |
# TODO: Mock test file read/write
from app import view, list
def test_export_view_json(runner):
"""
Tests exporting single article to json
"""
res = runner.invoke(view, ["new_wangonya", "-e", "json"])
assert res.exit_code == 0
def test_export_list_json(runner):
"""
Tests exporting artic... |
# coding=utf-8
# Copyright 2021 rinna Co., Ltd.
#
# 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 agr... |
import pya
from pya import *
from SiEPIC.utils import get_technology, get_technology_by_name
from SiEPIC.utils import arc, arc_wg, arc_to_waveguide, points_per_circle#,layout
import math
class swg_fc_test(pya.PCellDeclarationHelper):
"""
Sub-wavelength-grating fibre coupler PCell litho test structure.
2017/07/... |
from bot_logger import logger
from cogs.modules.coin_market import CurrencyException, FiatException
from collections import defaultdict
from discord.errors import Forbidden
import discord
import json
CMB_ADMIN = "CMB ADMIN"
ADMIN_ONLY = "ADMIN_ONLY"
ALERT_DISABLED = "ALERT_DISABLED"
class AlertFunctionality:
""... |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import csv
import os
from os import path
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--file", type=str)
parser.add_argument("--max", type=float)
parser.add_argument("--target", type=int, default=-1)
parser.add_argument("--... |
"""Test the Admin functionality of the organizer App"""
from django.contrib.auth import get_user_model
from test_plus import TestCase
from config.test_utils import get_instance_data, omit_keys
from ..models import NewsLink, Startup, Tag
from .factories import (
NewsLinkFactory,
StartupFactory,
TagFactory,... |
"""Support for Xiaomi Yeelight WiFi color bulb."""
from __future__ import annotations
import asyncio
import logging
from yeelight import BulbException
from yeelight.aio import KEY_CONNECTED
from homeassistant.const import CONF_ID, CONF_NAME
from homeassistant.core import callback
from homeassistant.helpers.dispatche... |
#!/usr/bin/env python2.7
# coding=utf-8
"""
@date = '8/9/16'
@author = 'chenjian'
@email = 'chenjian@cvte.com'
"""
import time
import cv2
import os
if __name__ == '__main__':
os.environ['GENICAM_ROOT_V2_4'] = '/opt/imperx/bobcat_gev/lib/genicam'
print(os.environ['GENICAM_ROOT_V2_4'])
import CameraBobc... |
import torch
from torch_scatter import segment_cpu, gather_cpu
from torch_scatter.helpers import min_value, max_value
if torch.cuda.is_available():
from torch_scatter import segment_cuda, gather_cuda
def seg(is_cuda):
return segment_cuda if is_cuda else segment_cpu
def gat(is_cuda):
return gather_cuda... |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/91_notebook_export.ipynb (unless otherwise specified).
__all__ = ['read_nb', 'check_re', 'is_export', 'find_default_export', 'export_names', 'extra_add', 'notebook2script',
'get_name', 'qual_name', 'source_nb', 'script2notebook', 'diff_nb_script']
#Cell
from .... |
from sauronlab.core.core_imports import *
from sauronlab.extras.addon_tools import AddonTools
from sauronlab.extras.video_core import VideoCore
from sauronlab.extras.videos import SauronxVideo, SauronxVideos
from sauronlab.model.cache_interfaces import AVideoCache
DEFAULT_SHIRE_STORE = PurePath(sauronlab_env.shire_pat... |
from flask import Flask, render_template, url_for, redirect, request
import pprint
import json
import requests
places = {
"Chitrakala Parishath": (12.9794, 77.5910),
"Jawaharlal Nehru Planetarium": (12.984731000000099, 77.589573000000001),
"Cafe Coffee Day": (12.926442000000099, 77.680487000000099),
"Chai Point":... |
from lib.actions import BaseAction
__all__ = [
'ListVMsAction'
]
NODE_ATTRIBUTES = [
'id',
'name',
'state',
'public_ips',
'private_ips'
]
class ListVMsAction(BaseAction):
api_type = 'compute'
def run(self, credentials):
driver = self._get_driver_for_credentials(credentials=c... |
"""
The new Google ReCaptcha implementation for Flask without Flask-WTF
Can be used as standalone
"""
__NAME__ = "Flask-ReCaptcha"
__version__ = "0.4.2"
__license__ = "MIT"
__author__ = "Mardix"
__copyright__ = "(c) 2015 Mardix"
try:
from flask import request
from jinja2 import Markup
import requests
exce... |
from django.apps import AppConfig
class CurlyConfig(AppConfig):
name = 'curly'
|
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from p... |
# -*- coding: utf-8 -*-
from django.db import models
from django.template.defaultfilters import slugify
class Module(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, blank=True, unique=True)
def __unicode__(self):
return self.name
def save(self, *a... |
"""Minimal test for testing test-runner"""
from toxtest import __version__
def test_version() -> None:
"""Test the version string"""
assert __version__ == "0.1.0"
|
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
from tqdm import tqdm
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_set = datasets.CIFAR10(root="ds/", transform=transforms.ToTensor(), download=True)
t... |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (c) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Unit tests for the openclean API extensions of the openclean engine."""
import pkg_resources
import py... |
from pypresence import Presence
from pypresence.exceptions import InvalidPipe
import time
def run_persence(current_version: str):
try:
RPC = Presence("EDIT-HERE") # add your RPC ID
RPC.connect()
RPC.update(
state=f"Version {current_version}",
details="pyt... |
import glob,sys
success=False
in_ironpython="IronPython" in sys.version
if in_ironpython:
try:
from ironpython_console import *
success=True
except ImportError:
raise
else:
try:
from console import *
success=True
except ImportError:
pass
... |
# UCI Electronics for Scientists
# https://github.com/dkirkby/E4S
#
# Blink an external LED connected to D12.
import board
import digitalio
import time
led = digitalio.DigitalInOut(board.D12)
led.direction = digitalio.Direction.OUTPUT
while True:
led.value = not led.value # toggle on/off
time.sleep(0.5) # sec... |
''' Comandos Break e loops infinitos '''
'''cont = 1
while cont <= 10: # para contar até 10
print(cont, '-> ', end='')
cont += 1
print('Acabou')'''
'''while True: -> comando para loop infinito
print(cont, '-> ', end='')
cont += 1
print('Acabou')'''
# exemplo:
'''n = 0
while n != 999: # -> só para de... |
import discord
from discord.ext import commands
from discord import utils
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='ping')
async def ping(self, ctx):
"""Pings to someone."""
await ctx.send(f'{ctx.author.mention}... |
from django.apps import AppConfig
class ArtConfig(AppConfig):
name = 'Calture'
verbose_name = 'ماژول آثار هنری'
|
import time
from collections import OrderedDict
from typing import TypeVar, Generic, Optional, Callable, Dict, Any, List
T = TypeVar("T")
class ExpirationQueue(Generic[T]):
"""
Handles queue of item that need to be expired and removed from the queue over time
"""
time_to_live_sec: int
# NOTE: t... |
import graphene
from graphene_django import DjangoObjectType
from .models import Pitstop
class PitstopType(DjangoObjectType):
class Meta:
model = Pitstop
class Query(graphene.ObjectType):
pitstops = graphene.List(PitstopType)
def resolve_pitstops(self, info, **kwargs):
return Pitstop.o... |
from datetime import datetime
from dataclasses import dataclass
import requests
class UmbrellaClient:
def __init__(self, integration_key, secret_key, organizationid, hostname="https://reports.api.umbrella.com/v2/organizations", limit=300):
self.limit = limit
self.hostname = hostname
self.secret_key = secret_key... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib as mpl
import numpy as np
import pandas as pd
import seaborn.apionly as sns
def cm2inch(value): return value/2.54
plt.style.use('custom')
dfA = pd.read_csv('/tmp/A.csv')
dfB = pd.read_csv('/tmp/B.csv')
dfB['mc'] += 10... |
import cv2
import os.path
import xlsxwriter
import datetime
workbook_one = xlsxwriter.Workbook("report/img_one.xlsx")
worksheet_one = workbook_one.add_worksheet()
img_one_list = []
workbook_two = xlsxwriter.Workbook("report/img_two.xlsx")
worksheet_two = workbook_two.add_worksheet()
img_two_list = []
wo... |
import os
import json
from dvc.main import main
from tests.basic_env import TestDvc
class TestMetrics(TestDvc):
def setUp(self):
super(TestMetrics, self).setUp()
self.dvc.scm.commit('init')
for branch in ['foo', 'bar', 'baz']:
self.dvc.scm.checkout(branch, create_new=True)
... |
# 集合 类似Java set数据结构
num = {1, 2, 3, 4, 5}
print(type(num))
# 数据元素唯一
num.add(1)
print(num) # {1, 2, 3, 4, 5}
# 不可变集合
set1 = frozenset({1, 2, 3, 4, 5})
# set1.add(6) 直接报错
|
import pickle
import numpy
import time
import math
from sklearn.linear_model import LinearRegression
aqstations = {'BL0':0, 'CD1':1, 'CD9':2, 'GN0':3, 'GN3':4, 'GR4':5, 'GR9':6, 'HV1':7, 'KF1':8, 'LW2':9,
'ST5':10, 'TH4':11, 'MY7':12}
ngrid = 861
def getCoef(idx):
py = tmpdata[24:]
linear = Line... |
# -*- coding: utf8 -*-
import itertools
def formatLine(r):
r = list(r)
l1 = ' '.join('{:02x}'.format(c) for c in r)
l2 = ''.join(chr(c) if 32 <= c < 127 else '.' for c in r)
return l1, l2
def hexDump(data):
size, over = divmod(len(data), 16)
if over:
size += 1
offsets = range(0,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyBroadException
try:
# import eventlet
# eventlet.monkey_patch(all=True, thread=False)
pass
except:
pass
import decimal
import logging
import logging.config
import os
import eventlet.wsgi
import sqlalchemy_utils
import yaml
from flask imp... |
import sched as s
import signal, os
if __name__ == '__main__':
nb=0
error=0
try:
nb,error = s.scheduler()
except Exception as inst:
print(inst)
|
import smart_imports
smart_imports.all()
class TimeTest(utils_testcase.TestCase):
def test_creation(self):
dext_settings_models.Setting.objects.all().delete()
dext_settings.settings.refresh()
settings_number = dext_settings_models.Setting.objects.all().count()
self.assertEqual... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.