text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-16 10:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questions', '0022_data_migration'),
]
operations = [
migrations.AlterField... |
"""
Neste caso, queremos fazer a previsão dos preços (prices) das casas.
Atributo previsor (coluna 5) - "sqft_living"
Atributo classe (coluna 2) - "price"
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from ... |
""" Get Environment Variables """
import os
OAUTH_CONSUMER_KEY = os.environ.get(
'OAUTH_CONSUMER_KEY', None)
OAUTH_CONSUMER_SECRET = os.environ.get(
'OAUTH_CONSUMER_SECRET', None)
OAUTH_TOKEN = os.environ.get(
'OAUTH_TOKEN', None)
OAUTH_TOKEN_SECRET = os.environ.get(
'OAUTH_TOKEN_SECRET', None)
|
"""chatproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
import subprocess
from test_pyenv import TestPyenvBase
class TestPyenvFeatureInstall(TestPyenvBase):
def test_check_pyenv_install_list(self, setup):
result = subprocess.run(['pyenv', 'install', '-l'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = str(result.stdout, "utf-8")
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import e2e_args
import infra.ccf
import os
import logging
from time import gmtime, strftime, perf_counter
import csv
import random
from loguru import logger as LOG
import json
import subprocess
def run(args):
host... |
import logging
import os
logging.basicConfig(
format=('%(asctime)s - %(name)s - %(levelname)s - '
'%(module)s.%(funcName)s:%(lineno)d - %(message)s'))
log = logging.getLogger('watchcat')
log.setLevel(logging.DEBUG)
DIR = os.path.dirname(os.path.realpath(__file__))
TEMPLATE_DIR = os.path.abspath(os.pat... |
from .family_member import *
|
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
from enum import Enum
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from sklearn import preprocessing, model_selection, feature_selection, ensemble, linear_model, metric... |
# -*- coding: utf-8 -*-
import os
import uuid
from django.core.urlresolvers import reverse
from django.contrib.gis.db import models
from pytils.translit import slugify
class City(models.Model):
title = models.CharField(u'Название', max_length=255)
slug = models.SlugField(u'Алиас')
class Meta:
d... |
import inspect
import logging
import re
import sys
from functools import reduce, wraps
from shutil import which
from typing import Any, Callable, List, Type, TypeVar
logger = logging.getLogger(__name__)
# Method for typing 'cls' taken from https://stackoverflow.com/a/56856290.
T = TypeVar("T")
# These are the globa... |
import logging
from rest_framework import status
from rest_framework.views import set_rollback
from rest_framework.response import Response
from rest_framework.views import exception_handler
logger = logging.getLogger( 'chibi_django.exceptions' )
class Http_error( Exception ):
"""
exceptcion generica
A... |
# -*- coding: utf-8 -*-
import os
import re
from selenium import webdriver
from xvfbwrapper import Xvfb
from cabu.exceptions import DriverException
from cabu.utils.headers import Headers
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
try:
from urllib.... |
from http import HTTPStatus
from asynctest import TestCase
from asyncworker.testing import HttpClientContext
from httpmetrics import app, alert_test
class ExampleMetricEndpointTest(TestCase):
async def test_warning_example_metric_value_0(self):
priority = "warning"
value = 0
async with H... |
# -*- coding: utf-8 -*-
# Core Django imports
from django.conf.urls import url, include
# Imports from your apps
from django.urls import path
from agency import views
from agency.views import handler404
urlpatterns = [
url('agency/', include('agency.urls')),
path('agency/api/', include('agency.api.urls_api'... |
"""Router for /runs actions endpoints."""
from fastapi import APIRouter, Depends, status
from datetime import datetime
from typing_extensions import Literal
from robot_server.errors import ErrorDetails, ErrorResponse
from robot_server.service.dependencies import get_current_time, get_unique_id
from robot_server.servic... |
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... |
import os
from PIL import Image
from torchvision.transforms import ToPILImage, ToTensor, Resize
if __name__ == '__main__':
CROP_SIZE = 256
UPSCALE_FACTOR = 2
HR_PATH = f'data/new_data/test_x{UPSCALE_FACTOR}/target/'
LR_PATH = f'data/new_data/test_x{UPSCALE_FACTOR}/data/'
BICUBIC_PATH = f'data/ne... |
import sys
sys.path.append("../")
from appJar import gui
app=gui("FRAME DEMO", "250x150")
app.setBg("yellow")
app.startFrame("LEFT", row=0, column=0)
app.setBg("blue")
app.setSticky("NEW")
app.setStretch("COLUMN")
app.addLabel("LEFT LABEL", "Label on the left")
app.setLabelBg("LEFT LABEL", "red")
app.addLabel("LEFT... |
# two cipher texts
ciph1 = bytes.fromhex('1a0d134503550e0a1d4542071f56')
ciph2 = bytes.fromhex('0d0710071d19490d0e5607004f00074e47')
key = 'The '
def decypher(key, c1, c2):
# create the empty decypher texts
d1, d2 = '', ''
# loop through extra key
for i, ki in enumerate(key):
d1 += chr(c1[... |
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, 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 o... |
from kafka import SimpleProducer, KafkaClient
from os.path import expanduser
import requests
from requests_oauthlib import OAuth1
import urllib, datetime, time, json, sys, boto3
import creds # we made this module for importing twitter api creds
client = boto3.client('emr')
s3res = boto3.resource('s3')
bucket_name ... |
from __future__ import absolute_import, unicode_literals
import six
import shutil
import os
import sys
import unittest
from io import StringIO
import boto
import mock
from django.test import TestCase
from django.utils import timezone
from fs.memoryfs import MemoryFS
from moto import mock_s3
from . import djpyfs
from... |
from .activities import Activity
from .survies import Survey |
# Generated by Django 2.2.10 on 2020-02-17 21:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('user', '0027_auto_20200211_1731'),
('user', '0027_auto_20200213_2026'),
]
operations = [
]
|
# Copyright (c) 2020 PaddlePaddle 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 app... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HSimple_CompleteLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HSimple_CompleteLHS.
"""
# Flag th... |
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis-python
#
# Most of this work is copyright (C) 2013-2018 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may ho... |
#!/usr/bin/env python
# Find the sum of all numbers which are equal to the sum
# of the factorial of their digits.
# We know if n has d digits, then sum(n) <= d*9! = 362880d and n >= 10*(d-1)
# hence sum(n) = n implies 3628800d >= 10^d. We must have d <= 7.
from math import factorial
from python.decorators import e... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 5 16:44:23 2017
author: Christian Bender
This python library contains some useful functions to deal with
prime numbers and whole numbers.
Overview:
isPrime(number)
sieve Er(N)
getPrimeNumbers(N)
primeFactorization(number)
greatestPrimeFactor(number)
smallestPrimeFactor... |
from .square import Square
class Tax(Square):
'''
Represents the Income Tax and Super Tax squares.
'''
def __init__(self, name, tax):
'''
The 'constructor'.
'''
super().__init__(name)
self.tax = tax
def landed_on(self, game, player):
'''
Ca... |
import torch
from torchvision.ops.boxes import nms, batched_nms, box_iou
def bbox_switch(bbox, in_type, out_type): # 'xyxy', 'xywh'
if in_type == 'xyxy' and out_type == 'xywh':
bbox = torch.cat([(bbox[..., 0: 2] + bbox[..., 2: 4]) / 2, bbox[..., 2: 4] - bbox[..., 0: 2]], dim=-1)
elif in_type == 'xywh... |
"""
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import math
#import csv
import json
import random
import pprint
import scipy.misc
import numpy as np
from glob import glob
import os
#import matplotlib.pyplot as plt
from time import gmtime, strftime
from config import _300W_LP_... |
espr = str(input('Escreva a sua expresão: '))
pard = espr.count('(')
pare = espr.count(')')
if pard == pare:
print('A sua expressão é válida')
else:
print('A sua expressão é inválida')
|
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot initialization. """
import os
import signal
from distutils.util import strtobool as sb
from logging import... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 UnitedStack 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.... |
import abc
import os
class Engine(abc.ABC):
def __init__(self, host: str = "localhost", port: int = 8500, scheme: str = "http"):
self._host = str(os.getenv("CONSUL_HOST", host))
self._port = int(os.getenv("CONSUL_PORT", port))
self._scheme = str(os.getenv("CONSUL_SCHEMA", scheme))
@pr... |
from pyforms.terminal.Controls.ControlBase import ControlBase
class ControlImage(ControlBase):
_filename = ''
def initControl(self): pass
def save(self, data):
if self.value!=None: data['value'] = self._value
def load(self, data):
if 'value' in data: self.value = data['value... |
import pytest
import scipy as sp
import numpy as np
import timeit
# set up a fixture for the Compartment model
@pytest.fixture(scope='module')
def model():
from compartmentmodels.compartmentmodels import CompartmentModel
model = CompartmentModel()
return model
@pytest.fixture(scope='module')
def prepar... |
def watch_pyramid_from_the_side(characters):
if not characters:
return characters
res=[]
length=len(characters)
for i in range(length):
res.append(" "*(length-i-1)+characters[-i-1]*(i*2+1)+" "*(length-i-1))
return "\n".join(res)
def watch_pyramid_from_above(characters):
if not ch... |
# Faça um programa que leia o número de matrícula do funcionário, o número
# de horas trabalhadas mensais, o valor que ele recebe por hora e o número
# de filhos e, em seguida calcule e escreva o salário deste funcionário,
# sendo que cada filho acrescenta 10% no salário do funcionário. Implemente
# uma função para... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("ANALYSIS")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(-1)
)
process.source = cms.Source(
"PoolSource",
secondaryFileNames = cms.untracked.vstring(
'/store/relval/CMSSW_7_1_0_pre3/RelValTTbar_13/GEN-SIM-RECO/POS... |
from django import forms
from .models import User
class UserRegisterForm(forms.ModelForm):
name = forms.CharField(max_length=100)
surname = forms.CharField(max_length=100)
email = forms.EmailField()
password = forms.PasswordInput()
class Meta:
model = User
fields = ['name', 'surna... |
# -*- coding:utf-8 -*-
# email:bingchengzhou@foxmail.com
# create: 2021/2/1
from .attention import Attention
from .srn_decoder import SrnDecoder |
#!/usr/bin/env python
from ctypes import *
from ctypes.util import find_library
from os import path
import sys
# For unix the prefix 'lib' is not considered.
if find_library('svm'):
libsvm = CDLL(find_library('svm'))
elif find_library('libsvm'):
libsvm = CDLL(find_library('libsvm'))
else:
b = False
fo... |
"""
ASGI config for feature_flags_project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault... |
#!/usr/bin/env python
# coding=utf-8
# Stan 2011-06-22
from __future__ import (division, absolute_import,
print_function, unicode_literals)
import sys
import os
import re
import logging
from PySide import QtCore, QtGui, __version__ as pyside_version
from .. import __pkgname__, __description__... |
# -*- coding: utf-8 -*-
from parse import BookManager, Book
if 0:
from gluon import current, URL, A, SPAN, P
request = current.request
session = current.session
response = current.response
db = current.db
def index():
session.filename = request.args[0]
filename = session.filename
Bo... |
#Copyright (C) 2018, by Jaeyoung Lim, jaeyoung@auterion.com
# 2D quadrotor environment using rate control inputs (continuous control)
#This is free software: you can redistribute it and/or modify
#it under the terms of the GNU Lesser General Public License as published by
#the Free Software Foundation, either version ... |
# Copyright 2016 Google 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 agreed to in writing,... |
import os
import capnp
CEREAL_PATH = os.path.dirname(os.path.abspath(__file__))
capnp.remove_import_hook()
log = capnp.load(os.path.join(CEREAL_PATH, "log.capnp"))
car = capnp.load(os.path.join(CEREAL_PATH, "car.capnp"))
print(log.Event) |
from common.numpy_fast import interp
import numpy as np
from selfdrive.hardware import EON, TICI
from cereal import log
TRAJECTORY_SIZE = 33
# camera offset is meters from center car to camera
if EON:
CAMERA_OFFSET = 0.06
PATH_OFFSET = 0.0
elif TICI:
CAMERA_OFFSET = -0.04
PATH_OFFSET = -0.04
else:
CAMERA_OF... |
from __future__ import absolute_import, division, unicode_literals
from six import text_type, binary_type
from six.moves import http_client, urllib
import codecs
import re
import webencodings
from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase
from .constants import ReparseException
from . imp... |
"""
cargo-raze crate workspace functions
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
def _new_http_archive(name, **kwargs):
if not native.existing_rule(name):
... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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/lice... |
"""Build and Version QuerySet classes."""
from django.db import models
from readthedocs.core.utils.extend import SettingsOverrideObject
from readthedocs.projects import constants
__all__ = ['VersionQuerySet', 'BuildQuerySet', 'RelatedBuildQuerySet']
class VersionQuerySetBase(models.QuerySet):
"""Versions tak... |
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh... |
from brightway2 import *
import warnings
from .utils import ParameterNameGenerator
from presamples.models.parameterized import ParameterizedBrightwayModel as PBM
from numpy import inf
import copy
class ActivityLandBalancer():
"""Balances land exchange samples at the activity level
Upon instantiation, will ide... |
# ZestyParser 0.8.1 -- Parses in Python zestily
# Copyright (C) 2006-2007 Adam Atlas
#
# 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 ri... |
from pyramid.renderers import get_renderer
from pyramid.view import view_config
from ..resources import Document
#
# Default "retail" view
#
@view_config(
renderer='templates/splash.pt',
)
def splash_view(request):
manage_prefix = request.registry.settings.get('substanced.manage_prefix',
... |
from .base_types import *
from .public_components import *
from .engine import *
|
import json
with open('/opt/mesosphere/etc/expanded.config.json', 'r') as f:
expanded_config = json.load(f)
|
import os
import math
import time
import numpy as np
from .programParser import find_numbers, find_word
from .linalg import UR_2_Pose, Pose_2_TxyzRxyz, txyzRxyz_2_pose
class Postprocessor():
"""
Generate program for Rozum Robotics robots like Pulse 75 or Pulse 90.
Initial program is RoboDK generated pro... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'LPTHW Exercise 47 - Unit tests',
'author': 'Spyros Dellas',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'spyrosdellas@yahoo.com',
'v... |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""A Juju charm for alertmanager."""
import hashlib
import logging
from typing import List, Optional
import yaml
from charms.alertmanager_k8s.v0.alertmanager_dispatch import AlertmanagerProvider
from charms.karma_k8s.v0.... |
"""Logger for NBoost classes"""
import termcolor
import logging
import copy
import os
def set_logger(context, verbose=False):
"""Return colored logger with specified context name and debug=verbose"""
if os.name == 'nt': # for Windows
return NTLogger(context, verbose)
# Remove all handlers assoc... |
## @file
# This file is used to define common static strings used by INF/DEC/DSC files
#
# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
import re
gIsWindows = None
gWorkspace = "."
gOptions = None
gCaseInsensitive = False
gAllFiles =... |
from .make_predictions import chemprop_predict, make_predictions
from .molecule_fingerprint import chemprop_fingerprint
from .predict import predict
__all__ = [
'chemprop_predict',
'chemprop_fingerprint',
'make_predictions',
'predict'
]
|
import os
import sys
import psutil
from monk.keras_prototype import prototype
from monk.compare_prototype import compare
from monk.pip_unit_tests.keras.common import print_start
from monk.pip_unit_tests.keras.common import print_status
import tensorflow as tf
if(tf.__version__[0] == '2'):
import tensorflow.compa... |
# --- Revised 3-Clause BSD License ---
# Copyright Semtech Corporation 2022. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright ... |
import matplotlib.pyplot as plt
from scipy.io import wavfile # get the api
from scipy.fftpack import fft
from pylab import *
def f(filename):
# song files are in ogg... we need it to be in wav.
fs, data = wavfile.read(filename)
# songs have multiple channels, but we only need one channel
... |
import cv2
import imread_from_url
from detector1K.utils import download_image
from detector1K import Detector1K
if __name__ == '__main__':
draw_scores = True
detection_model_path = 'models/object_localizer_float32.onnx'
detection_threshold = 0.3
classification_model_path = 'models/resnet50_vd_ssld_float32.onnx... |
from os import path
from setuptools import setup
# Read the contents of README file
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="artagger",
version="0.1.4",
description="A Rippl... |
from typing import TYPE_CHECKING
from collections import defaultdict, deque
from itertools import product
from pytools import memoize
if TYPE_CHECKING:
from codelets.adl import ArchitectureNode, StorageNode, ComputeNode
from codelets.codelet_impl import Codelet
from codelets.adl.flex_param import FlexParam
fr... |
import pexpect
import argparse
parser = argparse.ArgumentParser(description='Remote Connector')
# config of stepping machine
parser.add_argument('--step_usr', default='XXX', type=str, help='user name of stepping machine')
parser.add_argument('--step_pwd', default='YYY', type=str, help='password of stepping machine')... |
# 保存
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
'Content-Type': 'application/json; charset=UTF-8'
}
data = {
"projectDeclare": {
"id": "f4001645-c27e-4e3b-92ee-157... |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Project:
glideinWMS
Description:
unit test for validate_node from
glideinwms/creation/lib/cWDictfile
Author:
Dennis Box dbox@fnal.gov
"""
import unittest
import xmlrunner
fr... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import _init_path
import codecs
import os.path
import re
import sys
import subprocess
from functools import partial
from collections import defaultdict
import numpy as np
try:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
ex... |
###########################################################################
#
# Copyright 2019 Google 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
#
# https://www.apache.org... |
# 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 writing, software
# distributed under the Li... |
# bogus.py
#
# Bogus example of a generator that produces and receives values
def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -... |
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.cluster import _kmeans
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler
from pkg import detect_anomaly as da
from pkg imp... |
from lightkg.erl import NER
ner_model = NER()
train_path = '/home/lightsmile/NLP/corpus/ner/train.sample.txt'
dev_path = '/home/lightsmile/NLP/corpus/ner/test.sample.txt'
vec_path = '/home/lightsmile/NLP/embedding/char/token_vec_300.bin'
# ner_model.train(train_path, vectors_path=vec_path, dev_path=dev_path, save_pa... |
from typing import Optional
class AppStats:
def __init__(
self,
cpu_usage: Optional[float] = None,
mem_usage: Optional[float] = None,
):
self.cpu_usage = cpu_usage
self.mem_usage = mem_usage
|
import os
import sys
import unittest
from redisgraph import Graph, Node, Edge
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from base import FlowTestsBase
redis_graph = None
people = ["Roi", "Alon", "Ailon", "Boaz", "Tal", "Omri", "Ori"]
class testGraphMultiPatternQueryFlow(FlowTestsBase):
def ... |
from sets_categories_data import (VEGAN,
VEGETARIAN,
KETO,
PALEO,
OMNIVORE,
ALCOHOLS,
SPECIAL_INGREDIENTS)
def cle... |
"""
Class for holding Constellations of Satellites within it.
"""
from .Satellite import Satellite
import warnings
class Constellation(object):
"""
Class for describing and holding a constellation of satellites
"""
def __init__(self, num_sats, num_planes, phasing, inclination, altitude,
... |
# https://leetcode.com/problems/isomorphic-strings/
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# dict = {"e": [0], "g": [1, 2]}
# dict = {"a": [0], "d": [1, 2]}
# dict.values() --> [[0], [1, 2]]
def get_char_index(s):... |
import os
from argparse import ArgumentParser
from multiprocessing import Process, active_children
from time import sleep
from common import parse_clients_args
from missions.multi_agent import MultiAgent
def agent_factory(name, role, clients, agent_type, steps, mission, mode):
from missions.multi_agent import Mu... |
from time import sleep
from functools import wraps
def delay(seconds):
output = None
print(f"Sleeping for {seconds} second(s)")
sleep(seconds)
def inner_function(function):
@wraps(function)
def wrapper(*args, **kwargs):
print("[START]")
output = function(*ar... |
import json
import base64
import requests
import urllib.parse as urllib
import xml.etree.ElementTree as eTree
import traceback
import lib
from lib import DEBUG
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from sys import exit... |
import os
import pandas as pd
import pytest
from toucan_data_sdk.utils.generic import (
compute_evolution_by_criteria,
compute_evolution_by_frequency,
)
from toucan_data_sdk.utils.generic.compute_evolution import DuplicateRowsError
from toucan_data_sdk.utils.helpers import ParamsValueError
fixtures_base_dir ... |
#!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# 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 ag... |
# The Leginon software is Copyright 2004
# The Scripps Research Institute, La Jolla, CA
# For terms of the license agreement
# see http://ami.scripps.edu/software/leginon-license
#
import threading
import wx
import leginon.gui.wx.Events
import leginon.gui.wx.Node
import leginon.gui.wx.ToolBar
import leginon.gui.wx.Ta... |
import asyncio
from unittest import mock
from pytest import mark
from twisted.internet import defer
from twisted.internet.defer import Deferred
from twisted.trial.unittest import TestCase
from twisted.python.failure import Failure
from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy... |
"""tberg's newbie-ish functions, all in one place"""
def sort_list_of_dictionaries(unsorted_list, key_to_sort_by, reverse=False) -> list:
return sorted(unsorted_list, key=lambda k: k[key_to_sort_by], reverse=reverse)
|
"""
Example of running optical and contact cluster stuff on gromacs file
"""
from __future__ import absolute_import, division, print_function
import os.path as op
import numpy as np
import numpy.testing as npt
import pdb
import gsd.hoomd
import sys
import clustering as cl
import random
import scipy
import time
#from co... |
import bagel
import pathlib
def main():
bagel.utils.mkdirs(output_path)
file_list = bagel.utils.file_list(input_path)
for file in file_list:
kpi = bagel.utils.load_kpi(file)
print(f'KPI: {kpi.name}')
kpi.complete_timestamp()
train_kpi, valid_kpi, test_kpi = kpi.split((0.49... |
import psycopg2
try:
connection = psycopg2.connect(
database='postgres', user='gtripathi', password='QJdYWGAA6XqqU7bnF.PUr', host='hiring-quiz-database.cztyxuc8pfkm.ca-central-1.rds.amazonaws.com', port= '5432')
cursor = connection.cursor()
postgres_insert_query = """ INSERT INTO mobile (ID, MODEL, PRICE)... |
# Generated by Django 2.2.5 on 2019-10-04 11:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_process', '0012_auto_20191004_1127'),
]
operations = [
migrations.AlterModelOptions(
name='secondcatage',
optio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.