content stringlengths 5 1.05M |
|---|
from clang.cindex import Config, Index, Cursor
from cymbal import monkeypatch_cursor
from ctypes import c_uint
from path import Path
from os import getenv
from sys import platform, prefix
initialized = False
ix = None
def current_platform():
rv=None
if platform.startswith('win'):
rv='Windows'
... |
class Solution(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
def merge(intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
new_intervals = []
num = ... |
# Copyright 2021 Ian Eborn
# A simple controller for a third-person camera
#
# This is a base-class, intended to be sub-classed. In particular, it doesn't implement the collision-related
# matters that inform the camera's behaviour.
# A Panda-related importation
from panda3d.core import PandaNode
# Some constants des... |
# Linden Parkes, 2019
# lindenmp@seas.upenn.edu
import os
import numpy as np
import nibabel as nib
import mayavi as my
import surfer
import math
from matplotlib.pyplot import get_cmap
def roi_to_vtx(roi_data, parcel_names, parc_file):
# roi_data = (num_nodes,) array vector of node-level data to plot onto su... |
from .cmr import duplicate_gunw_found
from .enum import enumerate_ifgs, enumerate_ifgs_from_stack
from .formatter import distill_all_pairs, distill_one_pair
from .gis import get_aoi_dataframe
from .stack import get_s1_coverage_tiles, get_s1_stack_by_dataframe
__all__ = [
'enumerate_ifgs',
'enumer... |
import argparse
import cv2
import numpy as np
import os
import torch
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from torch.optim.lr_scheduler import StepLR
from sklearn.model_selection import train_test_split
i... |
import time
import matplotlib
import matplotlib.pyplot as plt
import pyaudio
import numpy as np
matplotlib.use('Agg')
# https://stackoverflow.com/questions/7088672/pyaudio-working-but-spits-out-error-messages-each-time
class Plotter:
def __init__(self):
self.count = 0
self.x = []
self.y ... |
if sm.hasQuest(21301):
sm.warpInstanceIn(914022000, 1)
sm.setInstanceTime(10*60, 914022000)
else:
sm.warp(140020300, 1) |
# --------------------------------------------------------
# SoCo
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Yue Gao
# --------------------------------------------------------
import json
import math
import os
import time
from shutil import copyfile
import ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import time
import click
_CONTAINER_ENGINE_MISSING_MESSAGE = '''LXD or Docker are required in order to run tests without polluting the host system.
Switch between container engines using the --docker or --lxd command line options.
Install LXD it by r... |
"""Equidistant points on a sphere.
Fibbonachi Spiral:
https://bduvenhage.me/geometry/2019/07/31/generating-equidistant-vectors.html
Fekete points:
https://arxiv.org/pdf/0808.1202.pdf
Geodesic grid: (sec. 3.2)
https://arxiv.org/pdf/1711.05618.pdf
Review on geodesic grids:
http://citeseerx.ist.psu.edu/viewdoc/downloa... |
"""
User Interface layout file for the meta GUI of the egg-vid-get software
Author: Cody Jarrett
Organization: Phillips Lab, Institute of Ecology and Evolution,
University of Oregon
"""
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'egg_vid_get_meta_gui.ui'
#
# Created by:... |
#!/usr/bin/env python3
# coding=utf-8
import paho.mqtt.client as mqtt
from logging import getLogger, basicConfig, StreamHandler, Formatter, DEBUG, INFO, WARN
from logging import config as loggerConfig
from pprint import pprint
handler_format = Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
stream_hand... |
# -*- coding:utf-8 -*-
# author:Anson
from __future__ import unicode_literals
import json
import requests
from Call_API import ApiClient
import settings
def get_access_token():
"""
获取access_token
:return:
{
"errcode": 0,
"errmsg": "ok",
"access_token": "fw8ef8we8f76e6... |
#contando vogais
palavras = ('Hoje', 'amanhã', 'Gratis', 'chefe' 'ontem',
'verei', 'veremos', 'teremos', 'amolecer',
'arriscar', 'adoecer', 'felicidade', 'simplicidade',
'carro', 'loja', 'rocha', 'rochedo')
for p in palavras:
print(f'\nNa palavra {p.upper()} temos ', end=' ')
... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# This file has been modified from the original repository's version in the following ways:
# 1. The model loading logic u... |
# The socket module in Python is an interface to the Berkeley sockets API.
import socket
# We need to create regular expressions to ensure that the input is correctly formatted.
import re
from typing import Pattern
# Regular Expression Pattern to recognize IPv4 addresses.
ip_add_pattern: Pattern[str] = re.compile("^(... |
import ClusterEnsembles as CE
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pandas as pd
import math
from anndata import AnnData
from natsort import natsorted
from typing import Optional
from time import time
from FlowGrid._FlowGrid import *
def calinski_harabasz_score(X, labels)... |
import setuptools
from setuptools import setup
with open("README.md", 'r') as f:
long_description = f.read()
setup(
name = 'noodleswrapper', #Name user sees
version = '0.1.2',
author = 'Kabir Ghai',
author_email = 'KabirGhai18@gmail.com',
description = 'A wrapper used for meme generating using... |
from statistics import mean
from typing import Dict, Any, Callable, Optional, List
import torch
from decouple import Module
from torch import nn
from .events import (
ModelForwardStartEvent, ModelForwardEndEvent, ModelBackwardStartEvent, ModelBackwardEndEvent, ModelLossEndEvent,
ModelLossStartEvent, ModelSche... |
def plus(x): # returns a tuple of 2 elements [proshmo, arithmos]
a = ['+',x]
return a
def minus(x):
a = ['-',x]
return a
def times(x):
a = ['*',x]
return a
def div(x):
a = ['/',x]
if x==0:
raise ValueError('Division by zero.')
return a
def zero(a = None)... |
"""
Mendeley OAuth support
No extra configurations are needed to make this work.
"""
from social_auth.backends import ConsumerBasedOAuth, OAuthBackend
from django.utils import simplejson
MENDELEY_SERVER = 'mendeley.com'
MENDELEY_REQUEST_TOKEN_URL = 'http://api.%s/oauth/request_token/' % \
... |
#------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
import enaml
from enaml.stdlib.sessions import show_simple_view
if __name__ == '__main__':
... |
from rest_framework import serializers
from .models import Article
from .models import Feedback
from .models import Image
from .models import News
from .models import Subscription
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = (
'image',
... |
# Generated by Django 3.2 on 2022-01-18 08:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("base_app", "0003_alter_bus... |
from raPID import *
controller = PID(0.2, 171, 0.001, 5, 0, 15, 3, False)
controller.graph()
controller2 = PID(0.2, 171, 0.001, 5, 0, 15, 3, False)
controller2.gen_manim()
|
import pygame
from geometry import get_init_points
from constants import WIDTH, HEIGHT, MOVE_KEY_MAP, ROTATE_KEY_MAP, CW, ACW, MOVE, MOVE2LAYERS, ROTATE, OPPOSITE
from constants import SAVE_POSITION, RESET_POSITION, SAVE_KEY_MAP
from constants import FUNCTIONAL_KEY_MAP, SOLVE, NEXT_STEP, SHUFFLE
from constants import F... |
"""
Train a SegNet model
"""
from __future__ import print_function
import argparse
import os
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from utils.vi... |
import math
data = open('p099_base_exp.txt')
cnt, max_num, ans = 0, 0, 0
for line in data:
cnt += 1
base_exp = map(int, line.strip().split(','))
value = math.log(base_exp[0])*base_exp[1]
if value > max_num:
max_num = value
ans = cnt
print ans
|
import unittest.mock
import json
import copy
import concurrent.futures
import pkg_resources
import yaml
import tornado.gen
import tornado.testing
import v6wos
def future(result=None, exception=None):
f = concurrent.futures.Future()
f.set_result(result) if exception is None else f.set_exception(exception)
... |
# file containing functions that return json data
from json import dumps # function that serializes obj to a JSON formatted str using a conversion table
from collections import OrderedDict # dict subclass that remembers the order entries are added
def createGeneralDataJson(hourly_average, frequency_of_use, occupancy_... |
def process(x):
"""
Processes a message from the local expiration stream
Note: in this example we simply print to the log, but feel free to replace
this logic with your own, e.g. an HTTP request to a REST API or a call to an
external data store.
"""
log(f"Key '{x['value']['key']}' expired at... |
import numpy as np
from tf_agents.environments.py_environment import PyEnvironment
from tf_agents.specs.array_spec import ArraySpec, BoundedArraySpec
from tf_agents.trajectories import time_step as ts
import logic
from game import step
class GameEnv(PyEnvironment):
"""
Custom `PyEnvironment` environment.
... |
def Arq(): #Função que abre lê e salva o conteudo do arquivo em formato de lista
meu_arquivo = open('Ano novo.txt','r')
conteudo = meu_arquivo.readlines()
meu_arquivo.close()
return conteudo
def leitor(a):#Função que lê o arquivo e faz as operações com suas letras
cont = 0
contes =0
... |
'''-----------------------------------------------------------------------------
# S T R I P F U N C T I O N S --------------------------------------------'''
from neopixel import Color
class LEDFunctions:
def __init__(self, strip, c_width, c_height):
self.strip = strip
self.clock_width = c_w... |
from bs4 import BeautifulSoup as bs
import requests
# Get HTML from a given URL
def getHtmlFromWebpage(url):
return bs(requests.get(url).content, "html.parser") |
from marshmallow import Schema, fields
class ServiceSchema(Schema):
service_category_id = fields.Integer(required=True)
company_id = fields.Integer(required=True)
name = fields.Str()
class Meta:
ordered = True
|
""" Custom Nose-Hoover NVT thermostat based on ASE.
This code was originally written by Jonathan Mailoa based on these notes:
https://www2.ph.ed.ac.uk/~dmarendu/MVP/MVP03.pdf
It was then adapted by Simon Batzner to be used within ASE. Parts of the overall outline of the class are also based on the Langevin class... |
# Represents a single node in the Trie
class TrieNode:
def __init__(self, end_of_word=False):
# Initialize this node in the Trie
# Indicates whether the string ends here is a valid word
self.end_of_word = end_of_word
# A dictionary to store the possible characters in this node
... |
#!/usr/bin/env python
import sys
from PyQt4.QtGui import QApplication as QApp
from gui.EditorWindow import MainWindow
def main():
import grammar.grammars
grammar.grammars.compileGrammars()
app = QApp(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
profile = Fa... |
#Author: Andrea Urgolo @ Space1
import glob
import sys
from os import path
import pandas
from datetime import datetime
#import from parent dir
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from data_adapter import DataAdapter
class CSVAdapter(DataAdapter):
"""
Model... |
# Copyright 2021 Rikai Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
#!/usr/bin/env python
"""
###############################################
Meter Package Component Specific Work Book View
###############################################
"""
# -*- coding: utf-8 -*-
#
# rtk.hardware.gui.gtk.Meter.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 Andre... |
# coding: utf-8
"""
authentication.py
`````````````````
: API验证模块
: API采用用户注册邮箱和token两种形式验证
: 建议使用token,更加安全
.....................................
: copyright: (c) 2016 by MuxiStudio
: license: MIT
"""
from flask import g, jsonify
from flask_httpauth import HTTPBasicAuth
from app.admi... |
import numpy as np
import pandas as pd
from src.util.pandas import df_to_list_w_column_idx
def get_future_student(df_list, i, col_idx, next_ano_letivo, nProcesso, year):
# for each student year
for i in range(i, len(df_list)):
row = df_list[i]
# return if ano letivo is bigger than the one we ... |
"""Implementation of the NDXI family of features."""
from functools import partial
import numpy as np
from ..image import Image
from .feature import Feature
NDXI_TYPES = {
'nir_ndvi': ('nir-1', 'red'),
'rg_ndvi': ('red', 'green'),
'rb_ndvi': ('red', 'blue'),
'ndsi': ('nir-1', 'green'),
'ndwi': ('... |
"""
Calculate digital signatures for messages sent to/from credit providers,
using a shared secret key.
The signature is calculated as follows:
1) Encode all parameters of the request (except the signature) in a string.
2) Encode each key/value pair as a string of the form "{key}:{value}".
3) Concatenate ... |
import numpy as np
N = 4
f = [0, 100, 200, 300]
print('f =', f)
print()
f_even = f[0::2]
print('f_even =', f_even)
f_even_even = f_even[0::2]
f_even_odd = f_even[1::2]
print('f_even_even =', f_even_even)
print('f_even_odd =', f_even_odd)
reseven0 = f_even_even[0] + np.exp(-2j * np.pi * 0 / N) * f_even_odd[0]
reseve... |
""" Model search filter operations """
from typing import Any, List, Optional
from sqlalchemy import not_
from sqlalchemy.orm import Query
from sqlalchemy.sql.schema import Column
def filter_bool(
query: Query,
column: Column,
value: bool = None,
) -> Query:
""" Update the query to filter based on boo... |
"""
RipSaw Class to run various workloads and scale tests
"""
import logging
import tempfile
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.ocs.ocp import OCP
from ocs_ci.ocs.ocp import switch_to_default_rook_cluster_project
from ocs_ci.ocs.resources.ocs import OCS
from ocs_ci.ocs import constants
from s... |
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
class Node:
def __init__(self):
self.visits = 0
self.children = {}
def traverse(name, node, output):
... |
'''
Classes to transform relationship graphs into standardized representations
'''
from abc import abstractmethod
from typing import List
import json
from fhir.resources.coding import Coding
from fhir.resources.extension import Extension
from fhir.resources.narrative import Narrative
from graph import Graph, Node, ... |
from models.mesh_classifier import RegresserModel, patch
import time
from data import DataLoader
from setting import parse_opts
import torch
import torch.nn as nn
from losses.loss import DiceWithCELoss
from util.logger import log
from metrics.DiceEval import diceEval, AverageMeter
import os
from models.networks import ... |
import requests
from fuzzywuzzy import fuzz
from OWLPy.objects import Player, Team, Match
from OWLPy.errors import *
class Driver(object):
"""An Object for controlling API functions"""
def __init__(self):
self.baseurl = "https://api.overwatchleague.com/"
# Acquire Players
def get_player_by... |
"""add_druid_auth_py.py
Revision ID: e553e78e90c5
Revises: 18dc26817ad2
Create Date: 2019-02-01 16:07:04.268023
"""
# revision identifiers, used by Alembic.
revision = "e553e78e90c5"
down_revision = "18dc26817ad2"
import sqlalchemy as sa
from alembic import op
from sqlalchemy_utils import EncryptedType
def upgrad... |
import numpy as np
from itertools import permutations
from math import factorial
from collections import defaultdict
from .charpoly import charpoly
from .sequences import increasing_injections, integer_sequences, matrices_from_degree_sequence
class MarkedGraph:
def __init__(self,vertices=None,edges=[],mat=None,ma... |
# Copyright 2021 DeepMind Technologies Limited
#
# 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 agree... |
import dash
import dash_table
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
df['filter_set'] = ((df['lifeExp'] < 30)) * 1
df['filter_set'][(df['lifeExp'] >= 30) & (df['lifeExp'] < 50)] = 2
df['filter_set'][(df['lifeExp'] >= 50) & (df['lifeExp'] < 70)... |
from rest_framework import serializers
from django.contrib.auth.models import Permission,ContentType
# 内置函数类表:区别内容表
class PermContentTypeModelSerializer(serializers.ModelSerializer):
class Meta:
model = ContentType
fields = [
'id',
'name'
]
# 权限表(主)
class PermModelS... |
import mock
from unittest.mock import (
patch,
mock_open
)
import lib.trilio.trilio_data_mover_utils as datamover_utils
import unit_tests.test_utils
import charmhelpers
import os
import time
import shutil
import subprocess # noqa
class TestTrilioDataMoverUtils(unit_tests.test_utils.CharmTestCase):
def... |
from django.shortcuts import render
from .models import Categories
from my_auth.models import ExtraDetails
def check_extra_details(user):
'''
Function to create a extra_detail object for a user,
if it is not there
'''
if user.is_authenticated:
extra_details = None
try:
... |
from typing import Union
from collections import namedtuple
from pynars.Narsese._py.Connector import Connector
from pynars.NAL.Inference import *
from pynars.Narsese import Statement, Term, Compound
Feature = namedtuple(
'Feature',
[
'match_reverse',
'has_common_id',
'common_id_task... |
import argparse
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import prepare_data, get_batch
from pt_model import TransformerModel
def train(model, data_source, device, epoch, args, bptt=35):
total_loss = 0.
model.train()
for batch, i in enumerate(range(0, data... |
"""
Code modified from PyTorch DCGAN examples: https://github.com/pytorch/examples/tree/master/dcgan
"""
from __future__ import print_function
import argparse
import os
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as... |
# Have the function GasStation(strArr) take strArr which will be an an array consisting of the following elements: N which will be the number of gas stations in a circular route and each subsequent element will be the string g:c where g is the amount of gas in gallons at that gas station and c will be the amount of gal... |
import geopandas
from typing import Tuple
from geocompose.definitions import Addresses
def import_file(filename: str, *args, **kwargs) -> geopandas.GeoDataFrame:
file_obj = geopandas.read_file(filename, *args, **kwargs)
return file_obj
def read_files(shapefile: str, addressfile: str, *args, **kwargs) -> Add... |
from fec_filing_iterator import _version as version
def test_version():
assert len(version.__version_info__) == 3
|
import os
import zlib
from json import JSONDecoder, JSONEncoder
from typing import (
Any,
Dict,
Generic,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from eventsourcing.application.notificationlog import (
LocalNotificationLog,
RecordManagerN... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.leveleditor.worldData.del_fuego_building_int_tavern_1
from pandac.PandaModules import Point3, VBase3, Vec4
objectStruct = {'Obje... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# create tuple
a = ("one", "two", "three")
# print 'em
print a
# how many node/element we have?
print len(a) # 3
# print using format
print "Counting %s, %s, %s..." % a
# iterate
for x in a:
print x
# print value from specific index
print a[1] # 'two'
# create an... |
import mongoengine
import numpy as np
class QueryJob(mongoengine.Document):
text = mongoengine.StringField(required=True)
language = mongoengine.StringField(required=True)
processed = mongoengine.BooleanField(default=False)
@property
def queries(self):
return Query.objects(source=self)
... |
from django.utils.translation import gettext_lazy as _
from wagtail.contrib.table_block.blocks import TableBlock
from wagtail.core import blocks
class RichTextBlock(blocks.StructBlock):
alignment = blocks.ChoiceBlock(
choices=[
("start", "Leva"),
("center", "Sredinska"),
... |
#!/usr/bin/env python
import pyeapi
from pprint import pprint
pynet_sw3 = pyeapi.connect_to("pynet-sw3")
#pynet_sw4 = pyeapi.connect_to("pynet_sw4")
my_config = pynet_sw3.get_config()
for line in my_config:
print line
my_config2 = pynet_sw3.get_config(as_string=True)
print my_config2
shversion = pynet_sw3.enab... |
import Sofa
import SofaTest
def createScene(node):
# simply build a python controller here
node.createObject('PythonScriptController',
filename = __file__,
classname = 'Controller',
name = 'script' )
return node
class Controller(S... |
from bottle import Bottle, run, route, request, redirect, post, template
from bottle_flash2 import FlashPlugin
# Flash Setup
app = Bottle()
COOKIE_SECRET = 'super_secret_string'
app.install(FlashPlugin(secret=COOKIE_SECRET))
@route('/')
def sample():
return template('index.html', app = app)
@route('/done')
def d... |
winzerod='iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAABmJLR0QAIgAeAB/Z8kSUAAAACXBI'\
'WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AIKFBsdhWPs3wAAAB1pVFh0Q29tbWVudAAAAAAAQ3Jl'\
'YXRlZCB3aXRoIEdJTVBkLmUHAAAgAElEQVR42uy9eXhdV3ku/n5rrb33GXU0j55ix2Oc0ZlDEghD'\
'GwiU4XIplN4WCnSiLbfcUnrb3kLh15bSFlpKh0vpBBcu0EsDIRAgzITMiRM7juN4kmRbkj... |
from utils.dict_utils import *
import logging
log = logging.getLogger(__name__)
class V2Mapping:
"""
See documentation/VDUMapping.md
Mapping is strictly {DataLocationPath : LocationToPlaceDataPath}
Which should almost always be {TOSCAPath : SOL6Path}
"""
KEY_TOSCA = "dict_tosca"
KEY_SOL6... |
from insights.parsers.ls_sys_firmware import LsSysFirmware
from insights.tests import context_wrap
LS_SYS_FIRMWARE = """
/sys/firmware:
total 0
drwxr-xr-x. 5 0 0 0 Dec 22 17:56 .
dr-xr-xr-x. 13 0 0 0 Dec 22 17:56 ..
drwxr-xr-x. 5 0 0 0 Dec 22 17:56 acpi
drwxr-xr-x. 3 0 0 0 Dec 22 17:57 dmi
drwxr-xr-x. 10 0 0 0 Dec... |
#!/usr/bin/python
import urllib2
from BeautifulSoup import BeautifulSoup
# This is not the finished version of this script; rather it's one that shows the incremental
# chunks of code I wrote, and some of the checks that I did to convince myself that it was
# working properly
base_url = 'http://www.whatsthescore.com... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def forwards(apps, schema_editor):
AcademicYear = apps.get_model("academics", "AcademicYear")
Enrollment = apps.get_model("academics", "Enrollment")
Evaluable = apps.get_model("courseevaluations",... |
import os
import pickle
from copy import deepcopy
import random
import json
from pandas import DataFrame
import pandas as pd
from typing import Tuple, Dict
import urllib
random.seed(30)
class NoValidArticle(Exception):
"""no article can be found with the given constraints"""
pass
MAX_WIDTH = 7
MAX_LENGTH ... |
"""
MTGJSON Keywords Object
"""
from typing import Any, Dict, List
from ..providers.scryfall import ScryfallProvider
from ..utils import to_camel_case
class MtgjsonKeywordsObject:
"""
MTGJSON Keywords Object
"""
ability_words: List[str]
keyword_actions: List[str]
keyword_abilities: List[str]... |
import qi.logging
logger = qi.logging.Logger("arcsdk.robot")
def _get_conf(qiSession):
try:
oldprefs = qiSession.service('ALPreferences')
conf = oldprefs.readPrefFile("ALTelepathe", False)
conf = {v[0]: v[2] for v in conf}
return conf
except Exception:
import traceback
... |
# Generated by Django 3.2.4 on 2021-10-21 10:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("projects", "0019_auto_20200523_0929"),
]
operations = [
migrations.AddField(
model_name="project",
name="suppress_pl... |
from django.test import TestCase, SimpleTestCase
from django.core.files import File
from custom_user.models import User
from job_applications.utils import time_now_utc
from job_applications.models import Company, Application, Job
from django.utils import timezone as tz
import math
import re
import os
from django.conf... |
# coding: utf-8
# In[1]:
import absorberspec, ebossspec, sdssspec, datapath, fitsio, starburstspec
import cookb_signalsmooth as cbs
from scipy.stats import nanmean, nanmedian
import cosmology as cosmo
masterwave, allflux, allivar = ebossspec.rest_allspec_readin()
objs_ori = ebossspec.elg_readin()
nobj = objs_ori.siz... |
import asyncio
import nest_asyncio
nest_asyncio.apply()
import random
import numpy as np
import cv2
from av import VideoFrame
from aiortc import (
RTCIceCandidate,
RTCPeerConnection,
RTCSessionDescription,
VideoStreamTrack,
)
from aiortc.contrib.signaling import BYE, ApprtcSignaling
import multiprocessi... |
# -*- coding: utf-8 -*-
"""Session module for TcEx Framework"""
# flake8: noqa
from .tc_session import TcSession
|
# ResNet-50 network from the paper:
# "Deep Residual Learning for Image Recognition"
# http://arxiv.org/pdf/1512.03385v1.pdf
# License: see https://github.com/KaimingHe/deep-residual-networks/blob/master/LICENSE
# Download pretrained weights from:
# https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/resnet50... |
#-*- coding: utf-8 -*-
import datetime
from apps.common import utils
#from apps.models.user_property import UserProperty
from apps.models.user_base import UserBase
from apps.models.user_friend import UserFriend
from apps.models.user_cards import UserCards
from apps.models.level_user import LevelUser
from apps.models.us... |
from voltron.plugin import *
from voltron.dbg import *
class MockAdaptor(DebuggerAdaptor):
pass
class MockAdaptorPlugin(DebuggerAdaptorPlugin):
host = 'mock'
adaptor_class = MockAdaptor
|
#SYSTEM INFO
import os
import sys
import tabulate
import psutil
import platform
import time
import datetime
from datetime import datetime
os.system(' clear ')
def get_size(bytes, suffix="B"):
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{byte... |
import json
import os
import boto3
from aws_lambda_powertools import Logger, Tracer
logger = Logger()
tracer = Tracer()
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["TABLE_NAME"])
@logger.inject_lambda_context(log_event=True)
@tracer.capture_lambda_handler
def lambda_handler(event, conte... |
import unittest
from bot_core import BotCore
from mixins.rate_limiting import RateLimiting
from test_user_tracking import UserTrackingBotSpy
class RateLimitingTest(unittest.TestCase):
def setUp(self):
self.bot = RateLimitingBotSpy()
self.bot.set_channel_rate_limit(5)
self.bot.set_pm_rate_lim... |
from core.flow_runner import flow
flow.register("test01", set_schedule_active=False) |
from typing import Union, List
from decimal import Decimal
from pystratis.api import APIRequest, EndpointRegister, endpoint
from pystratis.api.balances.requestmodels import *
from pystratis.core.types import Address, Money
class Balances(APIRequest, metaclass=EndpointRegister):
"""Implements the balances api endp... |
import logging
from banal import ensure_list, is_mapping, is_listish
from elasticsearch import RequestError
from aleph.core import es, settings
from aleph.util import backoff, service_retries
log = logging.getLogger(__name__)
# This means that text beyond the first 100 MB will not be indexed
INDEX_MAX_LEN = 1024 * 1... |
import socket
class CheckInternet:
def __init__(self):
self.internet_available = False
def check_availability(self):
self.internet_available = False
if socket.gethostbyname(socket.gethostname()) != '127.0.0.1':
self.internet_available = True
return self.internet_av... |
class DPANodeTypeSpecification:
def is_satisfied_by(self, dpa_node):
classname = dpa_node.__class__.__name__
return (classname == 'DPANode')
|
# (C) Copyright 2017 Inova Development Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.