content stringlengths 5 1.05M |
|---|
from django.http import HttpResponseRedirect
from apps.invite_remixer.urls import reverse_invite_id
from canvas.metrics import Metrics
def invite(request, invite_id):
inviter, url = reverse_invite_id(invite_id)
homepage_invite = url == '/'
Metrics.visit_from_invite.record(request, inviter=inviter.id, inv... |
import socket
class Client():
def __init__(self,Address=('198.37.231.220',25565)):
self.s = socket.socket()
self.s.connect(Address)
c = Client()
|
#!/usr/bin/python
import sys, time, random, string, os, argparse, signal
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler) # catch SIGIN with signal_handler
def realtime(txt, t=0.02, nl=1):
for i in range(len(txt)):
sys.stdout.write('\r%s' % txt[0:i+1])
... |
from mayan.apps.appearance.classes import Icon
from mayan.apps.permissions.icons import icon_permission
icon_acl_delete = Icon(driver_name='fontawesome', symbol='times')
icon_acl_list = Icon(driver_name='fontawesome', symbol='lock')
icon_acl_new = Icon(
driver_name='fontawesome-dual', primary_symbol='lock',
... |
'''From EDF-Like paper'''
from math import ceil # ceiling function
def set_prio(tasks, prio_policy=0, lam=0):
# if prio_policy not in [1, 2, 3, 4]:
# print("Priority policy is not implemented.")
# return
if prio_policy == 2: # DM
p = 0
for task in tasks:
# Popular.
... |
import re
import numpy as np
class ZFile:
def __init__(self, filename):
self.filename = filename
self.station = ""
self.decimation_levels = None
self.lower_harmonic_indices = None
self.upper_harmonic_indices = None
self.f = None
def open_file(self):
# a... |
from flask import flash
from db.dbconn import curs
class userInfoManager:
def __init__(self, user_id):
self.updateQuery = ""
self.user_id = user_id
def ChangeUserInfo(self, pwss, user_name, email, identifyNum):
error = None
if "" in [pwss, user_name, email, identifyNum]:
... |
import torch
from torch import nn
def evaluate():
pass
|
# Code taken from https://github.com/openai/baselines/tree/master/baselines/a2c
import os
import numpy as np
import tensorflow as tf
def mse(pred, target):
return tf.square(pred-target)/2.
def cat_entropy(logits):
a0 = logits - tf.reduce_max(logits, 1, keep_dims=True)
ea0 = tf.exp(a0)
z0 = tf.reduce_... |
import json
from . import app
import requests
from typing import Union
import os
# get request example
# https://www.googleapis.com/books/v1/volumes?q=isbn:9785171157340
def get_book_by_isbn(isbn: str) -> Union[dict, None]:
""" Basic GET-request bo Google books "
Args:
- isbn(str) - ISBN number
Retu... |
__author__ = "Andre Merzky"
__copyright__ = "Copyright 2013, The SAGA Project"
__license__ = "MIT"
from ..namespace import constants as ns
# replica flags enum:
OVERWRITE = ns.OVERWRITE # 1
RECURSIVE = ns.RECURSIVE # 2
DEREFERENCE = ns.DEREFERENCE # 4
CREATE ... |
"""
Install Module
"""
# Django
from django.core.management import execute_from_command_line
# local Django
from app.modules.util.helpers import Helpers
from app.modules.entity.option_entity import Option_Entity
from app.modules.entity.user_entity import User_Entity
class Install():
__option_entity = None
... |
#!/usr/bin/env python
import sys
from argparse import ArgumentParser
import yaml
from rtmbot import RtmBot
def parse_args():
parser = ArgumentParser()
parser.add_argument(
'-c',
'--config',
help='Full path to config file.',
metavar='path'
)
return parser.parse_args()
... |
import macarico
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as Var
class PPO(macarico.Learner):
"Proximal Policy Optimization"
def __init__(self, policy, baseline, epsilon, temperature=1.0, only_one_deviation=False):
super(PPO, self).__init__(... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
import json
from flask import abort, current_app, jsonify, make_response
from api.blueprint import api
from core import crossdomain
from flask_security import auth_token_required
from flask_login import current_user
from api.views.all_views import api_version
@api.route('/<api_version>/models', methods=['GET', 'OPTIO... |
M, N, K = int(input()), int(input()), int(input())
# Black is True, Gold Is False
canvas = [[True for _ in range(N)] for _ in range(M)]
for _ in range(K):
choices = input().split()
a, b = choices[0], int(choices[1])
if a == "R":
row = canvas[b - 1]
new_row = [not b for b in row]
canvas[b - 1] = new_row
else... |
# Generated by Django 3.2.9 on 2021-11-07 15:04
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_LPB', '0012_auto_20211106_1811'),
]
operations = [
migrations.RemoveField(
model_name='tarefa'... |
from toee import *
from utilities import *
from Co8 import *
def OnBeginSpellCast( spell ):
print "Disintegrate OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
game.particles( "sp-transmutation-conjure", spell.caster )
def ... |
import ssl
from typing import Optional, List
import aiomas
from loguru import logger
from chord.helpers import gen_finger
######################
# RPC Procedures
######################
async def rpc_ask_for_succ(
next_node: dict, numeric_id: int, ssl_ctx: ssl.SSLContext
) -> (bool, Optional[dict]):
"""
... |
def jogar():
print('*********************************')
print('***Bem vindo ao jogo da Forca!***')
print('*********************************')
palavra_secreta = 'banana'
letras_acertadas = ['_', '_', '_', '_', '_', '_']
enforcou = False
acertou = False
erros = 0
print(letra... |
#############################
# Created on Jul 2, 2015
#
# @author: nqian
#############################
from math import sqrt
from numpy import empty_like, dot, array
def get_vector(point1, point2):
return array([point1[0] - point2[0], point1[1] - point2[1]])
def perpendicular(a):
"""
Returns a numpy a... |
from django.urls import path
from .views import student, single_student
urlpatterns = [
path('', student, name="student"),
path('<slug>/', single_student, name='single-student'),
# path('registration/', views.student_regi, name='student_regi'),
] |
twitch_icon = "<:twitch:404633403603025921> "
cmd_fail = "<:tickNo:342738745092734976> "
cmd_success = "<:tickYes:342738345673228290> "
loading = "<a:loading:515632705262583819> "
bullet = "<:bullet:516382013779869726> "
right_arrow_alt = "<:arrow:343407434746036224>"
left_arrow = "<a:a_left_arrow:527634992415899650>"
... |
import os.path
from utilitaries.utils import extr, extract, gravity_law
def test_extr():
liste = [[0,1,2,3,1,9,100,1],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]
assert extr(liste) == (100,0)
def test_extract():
assert os.path... |
from javax.servlet.http import HttpServlet
import test184p
class test184s1(HttpServlet):
def doGet(self, request, response):
response.setContentType("text/html")
out = response.getOutputStream()
out.println("<html>")
out.println("<head> <title> JPython test184s1 servlet </title></... |
from .utils import json_value
def extract_media_v1(data):
"""Extract media from Private API
"""
user = data["user"]
location = data.get("location")
if location:
location = {"pk": int(location.get("pk")), "name": location.get("name")}
video_url = ""
if "video_versions" in data:
... |
import sys
import numpy as np
with np.load('uhat_dataset.npz') as data:
train_data = data['x_chars_train']
test_data = data['x_chars_test']
train_labels = data['y_chars_train']
test_labels = data['y_chars_test']
# reshape to flatten and normalize image data
train_data = train_data.reshape(len(train_da... |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework import permissions
from DrugID_API.models import Asset, Drug, Set, Result,... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_admin_user(host):
u = host.user('admin')
assert u.shell == '/bin/bash'
assert u.groups == ['admin', 'sudo']
def test_adm... |
# Generated by Django 2.2 on 2019-04-27 23:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("profile", "0012_listentry_ordering")]
operations = [
migrations.RemoveField(model_name="mediaresource", name="category"),
migrations.DeleteModel(name="Medi... |
import os
flask_secret_key='$FlaskSecretKey'
notasi_password='$NotasiPassword'
sqlalchemy_secret_key='$SQLAlchemySecretKey'
debug = False
saml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'saml')
login_default = 'local' |
import unittest
import agents
from envs.puzzle import Puzzle
class MyTestCase(unittest.TestCase):
def test_bfs(self):
bfs = agents.make('bfs')
p = Puzzle('1010101110000000000000000')
p.max_depth = 7
p.max_length = 5
sol, search = p.traverse(bfs)
print(sol)
... |
from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \
JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint
from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID
from sqlalchemy.orm import declarative... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""Document-Specific Utilities
"""
from typing import List, Dict, Any
from .errors import MissingFieldError
class DocUtilsMixin:
@classmethod
def get_field(self, field: str, doc: Dict, missing_treatment: bool='raise_error'):
"""
For nested dictionaries, tries to access a field.
... |
import os
from enum import Enum
this_dir = os.path.dirname(__file__)
# Filenames
LIST_REC_LINK = "index_rec.html"
LIST_DATE_LINK = "index_newest.html"
PEOPLE_LINK = "people.html"
SOURCES_DIR = "sources"
OUTPUT_DIR = os.path.abspath(os.path.join(this_dir, "../../output"))
assert os.path.exists(OUTPUT_DIR), str(OUTPUT_... |
import math
import numpy as np
def reshape_into_tiles(a, axis, filler_mat=None):
assert a.ndim == 3, 'Expected 3D array, got {}'.format(a.shape)
def get_tile_from_a(tile_i):
return a[get_idx_slice(axis, tile_i, ndim=3)]
C = a.shape[axis]
if filler_mat is None:
filler_mat = np.zeros_l... |
import argparse
import json
from teme.teme import get_token
from teme.teme import send_message
# construct the command line arguments
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--message", required=True,
help="message to send to telegram pushit bot")
ap.add_argument("-t", "--token", required=Fa... |
import blrequests.cli
import subprocess
def test_bare_usage_stdout():
result = subprocess.run(["blrequests"], capture_output=True)
expected = b"Hello World!"
assert result.stdout.strip() == expected
|
import requests
data = {
'msg1': 'wow',
'msg2': 'such',
'msg3': '@rawmsg'
}
response = requests.post('http://example.com/post', data=data)
|
# The intention is to make the test names descriptive enough to not need any docstrings for most of them
#pylint: disable=missing-docstring
# It seems better to have all tests for one module in the same file than to split across multiple files,
# so accepting many public methods and many lines makes sense
#pylint: disa... |
import argparse
import os
import shutil
import sys
import csv
import glob
from orbitpy import preprocess, orbitpropcov, communications, obsdatametrics, util
import time
def main(user_dir, gnd_stn_fl):
""" This script invokes the relevant classes and functions from the :code:`orbitpy` package to execute
a missi... |
import pandas as pd
essay_cantonese = pd.read_csv(
"source/essay-cantonese.txt",
header=None,
names=["char", "freq"],
sep="\t",
)
found = pd.read_csv(
"output/found.tsv",
header=None,
names=["char", "freq"],
sep="\t",
)
file = open("output/essay-new.txt", "w")
# All words from essay_c... |
def push_and_print(q):
while True:
x = (yield)
if x == '':
return
print('push_and_print: {}'.format(x))
q.append(x)
q = []
p = push_and_print(q)
try:
# p has to be primed in order to advance to the first `yield`
p.send(None)
print(q) # []
p.send('a') #... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.build_gra... |
"""
Otrzymujesz liste napisow. Znajdz najdluzszy wspolny przedrostek
dla wszystkich napisow z listy.
"""
# Wersja 1
# Zlozonosc czasowa O(n^2)
def najdluzszy_przedrostek_v1(slowa):
wynik = ""
n = len(slowa)
j = float("inf")
for slowo in slowa:
s = len(slowo)
if j > s:
j =... |
"""
Script entry point
"""
from src.calrissian.particle_vector2_network import ParticleVector2Network
from src.calrissian.layers.particle_vector2 import ParticleVector2
from src.calrissian.layers.particle_vector2 import ParticleVector2Input
import numpy as np
def main():
# train_X = np.asarray([[0.2, -0.3]])
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn import datasets
from sklearn.model_selection import train_test_split
import random
#
# def load_iris(fraction=1, plot=True, type=1):
#
# if type==1:
# df = np.loadtxt("data/iris_classes1and2_scaled.tx... |
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import exceptions
from odoo.tests.common import TransactionCase
class TestMtoMtsRoute(TransactionCase):
def _create_quant(self, qty):
self.quant = self.env['stock.quant'].create({
'owner_id': self.company_partner.id,
... |
def fibonacci(number):
a = 0
b = 1
sum = a + b
while(number!=0):
print(a)
a = b
b = sum
sum = a + b
number -= 1
num = int(input("\nEnter the number: \n"))
print("\nThe %d terms of fibonacci series is displayed : \n"%(num))
fibonacci(num)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
Create tables using the API instance connector
"""
def get_tables(debug : bool = False, **kw):
"""
Call the normal get_tables with the API instance connector instead
"""
from meerschaum.connectors.sql.tables import get_tables as _get_... |
# Copyright 2013-2015 Pervasive Displays, 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 applicable law or agree... |
class Node:
def __init__(self, data):
self.data = data
self.prev_node = None
self.next_node = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def start_insert(self, data):
new_node = Node(data)
... |
from django.shortcuts import render
from django.http import HttpResponse
from chatwork.models import Account
import requests
from datetime import date
from dateutil.relativedelta import relativedelta
from django.db.models import Count
import environ
env = environ.Env(DEBUG=(bool, False))
# Create your views here.
def... |
"""
Let this module to be executed from the command line with python -m src.asm2cfg
from root of the project
"""
from . import command_line
if __name__ == '__main__':
command_line.main()
|
from math import inf
from math import pi as π
from . import _ureg as _units
class Laser:
__units = {}
__omega = None
__linewidth = None
__A = 0
__theta_k = 0
__theta_p = π / 2
__electric_field = None
def __init__(self, units=None, laser=None, **new_laser):
if units:
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 14:48:18 2016
Tissue Enrichment Analysis (TEA).
classes: none yet (v 0.11)
functions:
enrichment_analysis
plot_enrichment_results
@author: davidangeles
"""
__author__ = "David Angeles-Albores"
__copyright__ = "Copyright 2016, WormBase"
__credits__ = ["David Angeles... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy import linalg as LA
import pdb
import random
from skmultiflow.ADCN.ADCN_process.utilsADCN import deleteRowTensor, deleteColTensor
# random seed control
# np.random.seed(0)
# torch.manual_seed(0)
# random.seed(0)
# =======... |
import cv2 as cv
class SegmentacaoPorLimiar:
def __init__(self, tipoLimiarBinario, limiar=None,
intensidade=None, algoritmoOTSU=False):
if (limiar is not None) and (intensidade is not None):
self.__limiar = limiar
self.__intensidade = intensidade
self.__tip... |
"""Additional Keras callbacks."""
import numpy as np
import tensorflow as tf
from junn_predict.common.timed import Timed
from tensorflow.keras.callbacks import Callback
from ..io.tiffmasks import tiff_masks
class TensorBoardSegmentationCallback(Callback):
"""Callback to run the model on some test data for segmen... |
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
from spice import ispice
import healpy as hp
from glob import glob
from planck_util import log_bin
freq1 = 100
freq2 = 143
simdir = '/project/projectdirs/planck/data/npipe/npipe6v19_sim'
cachedir = 'smooth_maps'
fwhm_deg = 3
fwhm_arcmin = fwhm_de... |
# -*- coding: utf-8 -*-
"""
This variable defines the models and their corresponding data loaders as well as extra-parameters
when needed. The mapping specified here will be directly used during disaggregation.
.. list-table:: Liste of available models
:widths: 25 25 50
:header-rows: 1
* - Model name
-... |
import mock
import unittest
class Class1(object):
def __init__(self, name):
self.name = name
def get_name(self):
print "Pradeep"
return "Pradeep"
class TestClass1(unittest.TestCase, Class1):
def setUp(self):
print "Start"
def test_get_name(self):
name = self... |
MOBILE_PREFIX = [
{'prefix': '1', 'en': 'USA', 'cn': '美国'},
{'prefix': '1', 'en': 'PuertoRico', 'cn': '波多黎各'},
{'prefix': '1', 'en': 'Canada', 'cn': '加拿大'},
{'prefix': '7', 'en': 'Russia', 'cn': '俄罗斯'},
{'prefix': '7', 'en': 'Kazeakhstan', 'cn': '哈萨克斯坦'},
{'prefix': '20', 'en': 'Egypt', 'cn': '埃... |
# code from: http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/
# import the necessary packages
# from __future__ import print_function
import cv2
# load the image and convert it to grayscale
image = cv2.imread("jurassic_world.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imsh... |
import cv2
import numpy as np
drawing = False
mode = True
ix, iy = -1, -1
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
if mo... |
from sqlalchemy import Column, BigInteger, Text, ForeignKey
from sqlalchemy.orm import relationship
from . import Base
MAX_CHANNELS = 9
class Guild(Base):
__tablename__ = "guilds"
id = Column(BigInteger, primary_key=True)
prefix = Column(Text)
event_role_id = Column(BigInteger)
channel_role_id ... |
# -*- coding: utf-8 -*-
__author__ = """Datos Argentina"""
__email__ = 'datos@modernizacion.gob.ar'
__version__ = '0.0.6'
from .text_classifier import TextClassifier
|
from os import environ, path
import click
from kubetools.exceptions import KubeDevError
from kubetools.settings import get_settings, get_settings_directory
from . import dev
from .backend import (
get_all_containers,
get_all_containers_by_name,
get_container_status,
)
from .process_util import run_proces... |
from SimPEG import Problem, mkvc, Maps, Props, Survey
from SimPEG.VRM.SurveyVRM import SurveyVRM
import numpy as np
import scipy.sparse as sp
############################################
# BASE VRM PROBLEM CLASS
############################################
class Problem_BaseVRM(Problem.BaseProblem):
"""
"""... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from mcenter_server_api.models.base_model_ import Model
from mcenter_server_api import util
class IntervalChart(Model):
"""NOTE: This class is auto generated by O... |
import sys
import os
import numpy.distutils
from numpy.distutils.exec_command import find_executable
from openmdao.core.system import AnalysisError
from openmdao.core.component import Component
from openmdao.util.options import OptionsDictionary
from openmdao.util.shell_proc import STDOUT, DEV_NULL, ShellProc
from ... |
import os
from unittest import TestCase
from .mailer import Mailer
from mailosaur import MailosaurClient
from mailosaur.models import SearchCriteria, MailosaurException
class EmailsTest(TestCase):
@classmethod
def setUpClass(cls):
api_key = os.getenv('MAILOSAUR_API_KEY')
base_url = os.getenv('M... |
from __future__ import print_function
import functools
import numpy as np
import matplotlib.pyplot as plt
import py2gcode.gcode_cmd as gcode_cmd
import py2gcode.cnc_path as cnc_path
import py2gcode.cnc_pocket as cnc_pocket
import py2gcode.cnc_boundary as cnc_boundary
import py2gcode.cnc_drill as cnc_drill
import flat... |
color = {'red':'\033[31m',
'green': '\033[32m',
'blue': '\033[34m',
'cyan' : '\033[36m',
'magenta' : '\033[35m',
'yellow' : '\033[33m',
'black' : '\033[30m',
'white' : '\033[37m',
'clear' : '\033[0;0m',
'bold' : '\033[1m',
'reverse' : '\033[2m',
'black-b' : '\033[40m', #-b fr... |
from __future__ import absolute_import
from checkout_sdk.common.common import Address
from checkout_sdk.common.enums import PaymentSourceType
from checkout_sdk.payments.payments_four import PaymentRequestSource
class RequestIdealSource(PaymentRequestSource):
bic: str
description: str
language: str
d... |
from pytest_regressions.data_regression import DataRegressionFixture
import gdsfactory as gf
from gdsfactory.component import Component
def test_get_bundle_u_direct_different_x(
data_regression: DataRegressionFixture, check: bool = True
) -> Component:
"""
.. code::
4----5
__... |
import logging
import json
import attr
import requests
from . import conf
from . import serializer
from .exceptions import ApiError, AuthError
logger = logging.getLogger(__name__)
@attr.s
class NovaPoshta(object):
"""
A base API class, that holds shared methods and settings for other models.
Creates ba... |
from .knights_archers_zombies.knights_archers_zombies import (ManualPolicy, env, parallel_env,
raw_env)
|
#! /usr/bin/env python
#usage: script.py
#from memory_profiler import profile
from ete3 import NCBITaxa
import argparse
import textwrap
import sys
import re
#@profile
def main(argv):
parser = argparse.ArgumentParser(
description=textwrap.dedent("""\
Summarize and filter alignments by taxid.
Required argumen... |
import unittest
from ac2020.days.Day21 import Day21
class Day21Test(unittest.TestCase):
def test_empty_input(self):
day = Day21()
day._set_input('')
self.assertEqual('0', day.part1())
self.assertEqual('', day.part2())
def test_correct_input(self):
day = Day21()
... |
import subprocess, json, sys
from datetime import datetime
class Facter (object):
def __init__(self, piecesRequested):
self.piecesRequested = piecesRequested
self.separator = '.'
self.facterCommand = ['facter', '--json', '--external-dir', '/etc/facter/facts.d/']
def __listOfFacts(self)... |
from enum import Enum
from inspect import isclass
from typing import Any, List, Literal, Type, Union
from django.conf import settings
from rest_framework.serializers import empty
from typing_extensions import get_args, get_origin
class ParsedType(object):
_hint: Any
def __init__(self, hint: Any):
se... |
from django.http import HttpResponse, JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import *
from rest_framework import viewsets
import requests
import json
import urllib
import geojson
from datetime import datetime, timedelta
... |
n1 = float(input('Primeiro Segmento:'))
n2 = float(input('Segundo Segmento:'))
n3 = float(input('Terceiro Segmento:'))
if n1 < n2 + n3 and n1 < n2 + n3 and n3 < n1 + n2:
print('Os segmentos acima podem formar um triângulo', end='')
if n1 == n2 == n3
print('ESCALENO')
elif n1 != n2 != n3 != n1:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Producer-consumer pattern, Scheduler."""
import collections
class Task(
collections.namedtuple(
'Task',
'trigger, interval, time, priority, fn, args, kwargs, id'
)
):
__slots__ = []
def __eq__(s, t): return (s.time, s.priority) == (t.t... |
### IMPORTS
import json
import scripts.nlp_lib as nlp
from igramscraper.instagram import Instagram
from google.cloud import firestore
from flask import jsonify
DB = firestore.Client()
### CONSTANTS
FIRESTORE_ID = 'export GCLOUD_PROJECT=poke-app-269623'
IG_SESSION_STORE = '/tmp/ig_temp'
USER_ID = None
ORGS_TABLE ... |
import argparse
import numpy as np
import h5py
def check(raw, seg):
import napari
with napari.gui_qt():
viewer = napari.Viewer()
viewer.add_image(raw)
viewer.add_labels(seg)
def export_from_bigcat(in_path, out_path):
with h5py.File(in_path, 'r') as f:
raw = f['volumes/raw... |
from decimal import Decimal
from django.core.exceptions import ObjectDoesNotExist
from django import forms
from lib.buyers.models import Buyer
from lib.paypal.constants import PAYPAL_CURRENCIES
from lib.sellers.models import SellerPaypal, SellerProduct
from lib.transactions.models import Transaction
from solitude.ba... |
# USAGE
# python simple_request.py
# import the necessary packages
import requests
import datetime
import os
import cv2
# initialize the REST API endpoint URL along with the input
## python server
SERVER_IP = "0.0.0.0"
SERVER_PORT = "5050"
API_BASE_URL = "http://"+SERVER_IP+":"+SERVER_PORT
API_URL = API_BASE_URL+"/... |
import unittest
import nzmath.compatibility
class SetTest(unittest.TestCase):
def testSet(self):
"""
set and frozen set is ready to use.
"""
self.assertTrue(set([1]))
self.assertTrue(frozenset([1]))
class CardTest(unittest.TestCase):
def testCardInsteadofLen(self):
... |
print ('Olá, seja bem vindo ao nosso site, para continuar, adicione seus dados e responda a algumas perguntas')
nome = input ('Qual é o seu nome?')
idade = input ('Qual a sua idade?')
gen = input ('Qual é o seu genero?')
print ('Confirme seus dados: Você se chama {},tem {} anos, e é do genêro {}. Correto?'.format(nome,... |
import os
import re
from collections import Counter
from collections import defaultdict
import numpy as np
from tqdm import tqdm
from utils import parameter_parser
class StringProcess(object):
def __init__(self):
self.other_char = re.compile(r"[^A-Za-z0-9(),!?\'\`]", flags=0)
self.num = re.compil... |
# Packages
import pandas as pd
import json
import csv
import re
from lyricsTokenizer import tokenizer
# Raw Data
songData_set1 = pd.read_csv("./dataset/raw/songData_set1.csv")
songData_set2 = pd.read_csv("./dataset/raw/songData_set2.csv")
# Processed Data Storage
jsonData = {}
jsonData['songs'] = []
csvData = []
csv... |
from random import randint, choice
import logging
MARIO_GEO_ADDRESS_START = 0x127C90
MARIO_GEO_ADDRESS_END = 0x122E2C
RAM_COPY_OFFSET = 0x8016F000
RAM_COPY_END = 0x801A72F8
MEM_COLOR_ADDRESSES = {
'OVERALLS': 0x823B64,
'HAT_AND_SHIRT': 0x823B7C,
'GLOVES': 0x823B94,
'SHOES': 0x823BAC,
'SKIN': 0x823BC4,
'H... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import datetime
from compute.navigation_graph import compute_navigation_graph
from tests.base import TestCase
from tests.modelfactory import create_location_visit
from models import LocationVisit, NavigationVertex, N... |
#mysql アクセス
#pip3 install PyMySQL
#error hundle
# 1045 (28000) ← ユーザが存在しない。以下の容量で作成
#grant all privileges on client_data.* to connect_tester@"192.168.%" identified by
# 'gasys' with grant option;
import imp
import mysql.connector
CONF_PATH = "/home/pi/dev_info.conf"
import read_conf
class ReadMysql:
def __init... |
# <snippet_imports>
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import TextOperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import TextRecognitionMode
from azure.cognitiveservices.vision.computervi... |
import gast as ast
import beniget
mod = ast.parse("""
T = int
def func() -> T:
return 1
""")
fdef = mod.body[1]
node = fdef.returns
du = beniget.DefUseChains()
du.visit(mod)
du.chains[node]
ud = beniget.UseDefChains(du)
ud.chains[node]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.