content
stringlengths
0
894k
type
stringclasses
2 values
"""Try out other sklearn score to measure the """ import os import sys import glob import numpy as np import argparse import tqdm import matplotlib.pyplot as plt from sklearn.neighbors import LocalOutlierFactor from pathlib import Path sys.path.append('../') from eval.metric import silhouette, hsic_gam_mat, inertia_ap...
python
from setuptools import find_packages, setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name="ml_example", packages=find_packages(), version="0.1.0", description="Example of ml project", author="Your name (or your organization/company/team)", entry_points=...
python
import shutil from dataclasses import dataclass from pathlib import Path import requests from mealie.core import root_logger from mealie.schema.recipe import Recipe from mealie.services.image import minify logger = root_logger.get_logger() @dataclass class ImageOptions: ORIGINAL_IMAGE: str = "original.webp" ...
python
""" Mesh Normalization """ import os import sys import cv2 import numpy as np from scipy import io as io import torch import pickle import trimesh import argparse from external.smplx.smplx import body_models sys.path.insert(0, '../external/pyrender') import pyrender def main(opt): model = body_models.create(mo...
python
import logging import time from datetime import datetime import IOstation import clim2bry import configM2R import decimateGrid import model2roms __author__ = 'Trond Kristiansen' __email__ = 'trond.kristiansen@niva.no' __created__ = datetime(2009, 1, 30) __modified__ = datetime(2021, 7, 27) __version__ = "1.6" __statu...
python
from gpt2.data.dataset import Dataset from gpt2.data.vocabulary import Vocab from gpt2.data.tokenization import Tokenizer from gpt2.data.corpus import TokenizedCorpus
python
aspect_ratio=1.0 batchSize=1 checkpoints_dir='../checkpoints/' cluster_path='features_clustered_010.npy' data_type=32 dataroot='./data/1/test' display_winsize=512 engine=None export_onnx=None feat_num=3 fineSize=512 fine_size=480 how_many=50 input_nc=3 instance_feat=False isTrain=False label_feat=False label_nc=36 load...
python
# 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 # d...
python
"""Test for kernel functionality.""" import functools import jax import jax.numpy as jnp import pytest import pytest_cases from probfindiff.utils import autodiff, kernel, kernel_zoo def case_exponentiated_quadratic(): k = lambda x, y: jnp.exp(-(x - y).dot(x - y)) return kernel.batch_gram(k)[0] def case_...
python
#!/usr/bin/env python3 import json, os print("Content-type:text/html\r\n\r\n") print("<title>Testing CGI</title>") #Lab code # Q1 print(os.environ) json_object = json.dumps(dict(os.environ)) print(json_object) # Q2 for param in os.environ.keys(): if param == "QUERY_STRING": print("<b>%20s</b>: %s<br>".form...
python
#!/usr/bin/env python """ This example shows how to create shipments. The variables populated below represents the minimum required values. You will need to fill all of these, or risk seeing a SchemaValidationError exception thrown. Near the bottom of the module, you'll see some different ways to handle the label data...
python
#! /usr/bin/python """radargrab Get the images and backgrounds associated with a storm event and save them to a directory or something """ import urllib2 import httplib import time from xml.dom import minidom from HTMLParser import HTMLParser _n0r = "http://radar.weather.gov/ridge/RadarImg/N0R/%s/" _overlay = "http://...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import platform from ctypes import cdll, c_wchar_p, create_unicode_buffer from platformpaths import sopaths, ridelibpaths APL = cdll.LoadLibrary(sopaths[platform.architecture()[0]][platform.system()]) def InitAPL(runtime, WSargs): __C_APL_WSargs_Binding_Pa...
python
# -*- coding: utf-8 -*- # pylint: disable=unidiomatic-typecheck # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redis...
python
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import NestedSet, get_root_of from erpnext.utilities.transaction_base import delete_events from frappe.model.d...
python
class PartitionScheme(basestring): """ mbr|gpt|unknown Possible values: <ul> <li> "mbr" - Master Boot Record Partition Table Scheme., <li> "gpt" - GUID Partition Table Scheme., <li> "unknown" - Partition Scheme other than MBR or GPT or an unformatted LUN. </ul> """ ...
python
# -*- coding: utf-8 -*- """字典树实现敏感词过滤""" import codecs class TrieNode(object): def __init__(self, value=None): self._end = False self._child = dict() self._value = value def add(self, ch): if not self._child.has_key(ch): node = TrieNode(ch) self._child...
python
import json import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def hello(event, context): logger.info(f"AWS Lambda processing message from GitHub: {event}.") body = { "message": "Your function executed successfully!", "input": event } response = { "st...
python
import json import os import psycopg2 import time #import pdb; pdb.set_trace() POSTGRES_HOST = "database" POSTGRES_USER = os.environ["POSTGRES_USER"] POSTGRES_PASSWORD = os.environ["POSTGRES_PASSWORD"] DB = "datamonitor" DATA_DIR = "data" def load_data(): wait_for_db() #only load once if is_data_there(...
python
import logging import os import mock import unittest import vixen from vixen.processor import PythonFunctionFactory from vixen.project import Project, TagInfo from vixen.vixen import VixenUI, Vixen, UIErrorHandler, is_valid_tag from vixen.vixen_ui import get_html, get_html_file from vixen.tests.test_project import Te...
python
import yaml import os from pathlib import Path from utils.dict_wrapper import DictWrapper class EvaluationConfiguration: ''' Represents the configuration parameters for running the evaluation process ''' def __init__(self, path): ''' Initializes the configuration with contents from t...
python
#!/usr/bin/env python # # Copyright 2009 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 o...
python
import json import boto3 import os import urllib.parse s3 = boto3.client('s3') # Cliente do Amazon Textract textract = boto3.client('textract') def getTextractData(bucketName, documentKey): # Chamando o Amazon Textract com os parâmetros do bucket e do arquivo .png response = textract.detect...
python
BLOCK_SIZE = 1024 BACKING_FNs = ['../../songs/lamprey/drums.wav', '../../songs/lamprey/bass.wav', '../../songs/lamprey/piano.wav', '../../songs/lamprey/violin.wav']
python
#!/usr/bin/env python """find_profit is O(n) over a list, given a window, to find the maximum profit possible given a single pair of trades taking place in that window""" import unittest def find_profit(prices, window): """Given a certain window size and a list of prices, find the highest profit possible if e...
python
# Generated by Django 3.1.2 on 2020-10-27 22:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tailscout_app', '0005_auto_20201015_2047'), ] operations = [ migrations.AlterField( model_name='job', name='bacteria...
python
import json import pandas as pd import urllib3 import numpy as np import re http = urllib3.PoolManager() votd = json.loads(http.request('GET',"https://public.tableau.com/api/gallery?page=0&count=10000&galleryType=viz-of-the-day&language=any").data) df = pd.json_normalize(votd['items'], max_level=0) # initialise dataf...
python
from .cachable_functions import Cachable from .params import CachableParam
python
from flask_server_files.models.defect import DefectModel d1 = DefectModel.new_defect()
python
import json from twitter_helper import TwitterHelper with open('config.json') as f: data = json.load(f) username = "@CoolDude32149" th = TwitterHelper(data, username) message = "Thank you for your complaint" th.stream_tweet()
python
import pytest data = [ (pytest.lazy_fixture("a_base_model_object"), {"id": "1", "name": "default_name"}), ({1, 2, 3}, [1, 2, 3]), ] @pytest.mark.parametrize("obj, expected", data) def test_base_model_enhanced_encoder(obj, expected): from fractal.contrib.fastapi.utils.json_encoder import BaseModelEnhanced...
python
# launcher.py from math import radians, degrees, cos, sin from graphics import * from shotTracker import ShotTracker class Launcher: def __init__(self, win): # Draw the base shot of the launcher base = Circle(Point(0, 0), 3) base.setFill("red") base.setOutline("red") base.d...
python
from uqcsbot import bot, Command from uqcsbot.utils.command_utils import loading_status from typing import Dict, List from collections import defaultdict from random import shuffle, choice @bot.on_command("emojify") @loading_status def handle_emojify(command: Command): ''' `!emojify text` - converts text to ...
python
""" @brief @file Various function to help investigate an error. """ import traceback from io import StringIO class ErrorOnPurpose(Exception): """ raise to get the call stack """ pass def get_call_stack(): """ Returns a string showing the call stack when this function is called. .. e...
python
import argparse import subprocess from typing import Tuple from data_copy import copy_pgdata_cow, destroy_exploratory_data_cow from pgnp_docker import start_exploration_docker, shutdown_exploratory_docker, setup_docker_env from sql import checkpoint, execute_sql, \ wait_for_pg_ready from util import ZFS_DOCKER_VOL...
python
# Copyright (c) 2020 Huawei Technologies Co., Ltd. # Licensed under CC BY-NC-SA 4.0 (Attribution-NonCommercial-ShareAlike 4.0 International) (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://creativecommons.org/licenses/by-nc-sa...
python
from .wd_containers import _ParameterContainer import os import sys # below snippet is taken from subprocess32 manual if os.name == 'posix' and sys.version_info[0] < 3: import subprocess32 as subprocess else: import subprocess class _WDIO: def __init__(self, container, wd_path, wd_binary_name): se...
python
from django.test import TestCase from .models import Location,Tag import datetime as dt # Test case for locations class LocationTestClass(TestCase): def setUp(self): self.location = Location(location='Nairobi') def test_instance(self): self.assertTrue(isinstance(self.location, Location)) ...
python
# -*- coding: utf-8 -*- ''' Manage Dell DRAC. .. versionadded:: 2015.8.2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import re # Import Salt libs from salt.exceptions import CommandExecutionError import salt.utils.path # Import 3rd-party...
python
from bs4 import BeautifulSoup as bs import os import re import ntpath class GetEngine(object): """ This class contains the methods needed to get the files, to help make the pdf file. The class contains the following methods: get_html() --- Which gets the html file names. get_pdf() --- Which gets the...
python
# # @package version.py # @brief Argos version finder import os import core # Argos core # # Attempts to determine the version of this argos by its .VERSION file def get_version(): return core.get_argos_version() # Read the .VERSION file # #join = os.path.join # #dirname = os.path.dirname # #abspath = os.pa...
python
import cv2 import numpy as np import scipy.ndimage from sklearn.externals import joblib from tools import * from ml import * import argparse # Arguments parser = argparse.ArgumentParser() parser.add_argument('--mode', '-mode', help="Mode : train or predict", type=str) parser.add_argument('--a', '-algorithm', help="alg...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """This module declares the different meanings that the Orbit 6 components can take and their conversions """ from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh import numpy as np from ..errors import UnknownFormError from ..utils.node import...
python
""" Tasks related to `oms` project. Import as: import oms.oms_lib_tasks as oomlitas """ import logging import os from invoke import task import helpers.hdbg as hdbg import helpers.hgit as hgit import helpers.lib_tasks as hlibtask _LOG = logging.getLogger(__name__) # TODO(gp): This was branched from im/im_lib_ta...
python
#!/usr/bin/env python # Copyright (c) Megvii, Inc. and its affiliates. All Rights Reserved import re import setuptools import sys TORCH_AVAILABLE = True try: import torch from torch.utils import cpp_extension except ImportError: TORCH_AVAILABLE = False print("[WARNING] Unable to import torch, pre-comp...
python
from tkinter import * from math import * class test(): def __init__(self): self.a=dict(name="",usn="",q1="",q2="",q3="",q4="",t1="",t2="",ass="") self.resulttable=Tk() self.resulttable.geometry("1500x1500") self.resulttable.config() self.ent=Frame(self.resulttable) self.ent.grid() self.res1=Frame(se...
python
import json from typing import Any, Dict, List, Optional, Set, Tuple from google.cloud import ndb from backend.common.consts.media_type import MediaType from backend.common.models.media import Media from backend.common.models.team import Team from backend.tasks_io.datafeeds.parsers.json.parser_paginated_json import ...
python
"""\ Pyconstruct provides metrics and losses to be used with most of the structured output problems out there. """ from .losses import * __all__ = losses.__all__
python
# Copyright 2020 Alibaba Group Holding Limited. 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 ...
python
from gym_tak.tak.board import Presets, Board from gym_tak.tak.piece import Colors, Types from gym_tak.tak.player import Player class TakGame: def __init__(self, preset: Presets, player1: str, player2: str) -> None: super().__init__() self.preset = preset self.board = Board(preset) ...
python
# -*- coding: utf-8 -*- from os import path __cdir__ = path.dirname(__file__) __fabfile__ = path.join(__cdir__, 'commands.py')
python
from i3pystatus import Module class Text(Module): """ Display static, colored text. """ settings = ( "text", ("color", "HTML color code #RRGGBB"), ) required = ("text",) color = None def init(self): self.output = { "full_text": self.text }...
python
import sqlalchemy as sa from aiopg.sa import create_engine from datetime import datetime from sqlalchemy.dialects.postgresql import UUID async def init_pg(app): settings = app['settings']['db'] engine = await create_engine( **settings ) app['db'] = engine # async with app['db'].acquire() ...
python
"""Return the euclidean distance beetween the given dictionaries.""" from .minkowsky import minkowsky from typing import Dict def euclidean(a: Dict, b: Dict)->float: """Return the euclidean distance beetween the given dictionaries. Parameters ---------------------------- a: Dict, First dictio...
python
# Generated by Django 2.2.13 on 2021-08-19 10:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0123_reportcolumn_preview_only'), ] operations = [ migrations.CreateModel( name='R...
python
import torch from torch import nn from torch.nn import functional as F import math class NoisyLinear(nn.Module): def __init__(self, in_features, out_features, std_init=0.5): super(NoisyLinear, self).__init__() self.in_features = in_features self.out_features = out_features self.st...
python
from django import template import mistune register = template.Library() @register.filter def markdownify(text): # safe_mode governs how the function handles raw HTML renderer = mistune.Renderer(escape=True, hard_wrap=True) markdown = mistune.Markdown(renderer=renderer) return markdown(text)
python
import sys import os from dotenv import load_dotenv # see by https://github.com/mytliulei/boundless/blob/master/python/%E6%89%93%E5%8C%85exe/pyinstaller.md if getattr(sys, 'frozen', False): BASE_DIR = os.path.dirname(sys.executable) else: # 文件所在目录 #BASE_DIR = os.path.abspath(os.path.dirname(__file__)) ...
python
import fbuild.config.c as c # ------------------------------------------------------------------------------ class extensions(c.Test): builtin_expect = c.function_test('long', 'long', 'long', name='__builtin_expect', test='int main() { if(__builtin_expect(1,1)); return 0; }') @c.cacheproperty...
python
from rest_framework import serializers from .models import Brew class BrewSerializer(serializers.ModelSerializer): class Meta: model = Brew fields = ("started_brewing", "outages")
python
#!/usr/bin/env python3 from flask import Flask, make_response, request, render_template app = Flask(__name__) # entry point for our users # renders a template that asks for their name # index.html points to /setcookie @app.route("/index") @app.route("/") def index(): return render_template("index.html") # set t...
python
from __future__ import annotations import functools import os import traceback from enum import Enum from typing import Callable from typing import TypeVar from CCAgT_utils.constants import FILENAME_SEP from CCAgT_utils.constants import STRUCTURE R = TypeVar('R') def basename(filename: str, with_extension: bool = ...
python
# -*- coding: utf-8 -*- ''' European Biotechnology pipelines Scrapy pipelines docs: https://docs.scrapy.org/en/latest/topics/item-pipeline.html ''' import datetime import re import scrapy from event.items import EventItem, ResponseItem from common.util import xpath_class, lot2dol, flatten, lmap class EuropeanBiot...
python
from coalib.bearlib.abstractions.Linter import linter from dependency_management.requirements.GemRequirement import GemRequirement @linter(executable='sqlint', use_stdin=True, output_format='regex', output_regex=r'.+:(?P<line>\d+):(?P<column>\d+):' r'(?P<severity>ERROR|WARNING) (?P<messag...
python
# Test # acc_des = 'This is a test account.2' # acc_username = '2' # acc_password = '2' # secret_msg = 'Hello :)' # enc_acc_dess = enc.encrypt_data( # 'b2001bccdcb7ea5556526cb70e58206996c3039282dd62e2ddc4a1d55be6c1d6', # data=acc_des) # enc_username = enc.encrypt_data( # 'b2001bccdcb7ea5556526cb70e58206996c...
python
# r""" # For training model. # Consist of some Trainers. # """ # # import argparse # import torch.nn as nn # # from pathlib import Path # from torch.optim import SGD # from torch.cuda.amp import GradScaler # from torch.optim.lr_scheduler import StepLR # from torchvision.transforms import transforms # from torchvision.d...
python
# 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...
python
""" Utility functions """ import os from collections import namedtuple def process_args(args, mode): """ save arguments into a name tuple as all scripts have the same arguments template :param args: argument list as passed from the command line :type args: list """ if len(args) > 4: ...
python
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): # write code here i = 0 length = len(array) while(i<length): while(i<length and array[i]%2!=0): # 找到偶数 i += 1 j = i + 1 while(j < length and array[j]%2==0 ): # 找到...
python
class GSP: def __init__(self): self.start = [] self.goal = [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input("Enter Start ...
python
from flask import render_template, request, jsonify from datetime import datetime from hw_todo.utils import get_canvas_tasks from hw_todo.tests import app db_canvas = {"Tasks": []} db = db_canvas @app.route('/docs') def get_docs(): print('sending docs') return render_template('swaggerui.html') @app.route('...
python
""" File: pylinex/basis/EffectiveRank.py Author: Keith Tauscher Date: 17 Oct 2017 Description: File containing function which, given a training set of curves and a corresponding noise level, determines the effective rank of the training set, which is the number of modes to fit within the erro...
python
from app import db,create_app from flask_script import Manager, Server from flask_migrate import Migrate, MigrateCommand from app.models import Blogpost app=create_app('development') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('server', Server) manager.add_command('db', MigrateCommand) @man...
python
import os from torch_geometric.data import InMemoryDataset, DataLoader, Batch from torch_geometric import data as DATA from torch.utils.data.dataloader import default_collate import torch import numpy as np import time # initialize the dataset class DTADataset(InMemoryDataset): def __init__(self, root='/tmp', dat...
python
# -*- coding: utf-8 -*- def main(): h, w = map(int, input().split()) s = [list(input()) for _ in range(h)] ans = 0 for i in range(h - 1): for j in range(w - 1): count = 0 for ni, nj in [(i, j), (i + 1, j), (i, j + 1), (i + 1, j + 1)]: if s[ni][nj] == "...
python
import time from typing import List, Dict, Any, Tuple _measurements = {} _formats = {} _default_format = 'Duration of "{name_range}": {humanized_duration}' def set_format(format: str) -> None: if not isinstance(format, str): raise TypeError('Format should be of type "str"') global _default_format ...
python
from PyQt5.QtCore import QObject, pyqtSignal class Model(QObject): amount_changed = pyqtSignal(int) even_odd_changed = pyqtSignal(str) enable_reset_changed = pyqtSignal(bool) users_changed = pyqtSignal(list) @property def users(self): return self._users def add_user(self, value...
python
def hello(who): print 'Hello, %s!' % who if __name__ == '__main__': print hello(sys.args[1] if len(sys.args) >= 2 else 'World')
python
import argparse import sys import time import unittest import warnings import emoji from lib.const import CSPM_RUNNING_K8S_MASTER_CHECK_LOG, CSPM_RUNNING_K8S_WORKER_CHECK_LOG, CSPM_START_LOG from lib.cspm.api import wait_for_compliance_event, wait_for_finding from lib.cspm.finding import ( is_expected_k8s_master_n...
python
# # Copyright 2021- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # import os from time import time from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from sklearn import metrics from hkmeans import HKMeans from clustering_utils import fetch_20ng, save_r...
python
import pytest import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import LogisticRegression from picknmix import Layer class TestLayer: def test_different_numbers_of_preprocessor_and_models(self): with pytest.raises(E...
python
""" Standard classes for the Converter module """ import logging import pickle import uuid from django.core.cache import cache class ConverterLoadError(Exception): """ Exception when loading a converter from its redis pickle """ msg = 'Error while loading converter' class BaseConverter: """ ...
python
# @author Kilari Teja from halley.skills.tdl.utils import PropMap, Constants import re class OPERATOR(object): DESCRIPTOR = None @classmethod def register(clas, tokenStore, statsCollector=None): OPERATOR.registerStatic(clas, tokenStore) @staticmethod def registerStatic(clas, tokenStore, statsCollector=Non...
python
from typing import List def info_from_jenkins_auth(username, password, required_scopes): """ Check and retrieve authentication information from basic auth. Returned value will be passed in 'token_info' parameter of your operation function, if there is one. 'sub' or 'uid' will be set in 'user' paramete...
python
#! /usr/bin/env python2 import os filepath = os.path.join( str(os.environ.get("GITHUB_WORKSPACE")), str(os.environ.get("FILE_TO_MODIFY")) ) with open(filepath) as f: newText = f.read().replace( str(os.environ.get("FIND")), str(os.environ.get("REPLACE")) ) with open(filepath, "w") as f: f.writ...
python
# -*- coding: utf-8 -*- from django.db import models from django.contrib import admin from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.test.utils import override_settings, modify_settings from django_dyna...
python
""" tests.support.pytest.fixtures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The purpose of this fixtures module is provide the same set of available fixture for the old unittest test suite under ``test/integration``, ``tests/multimaster`` and ``tests/unit``. Please refrain from adding fixtures to this module ...
python
import torch import numpy as np def colormap(N=256): def bitget(byteval, idx): return ((byteval & (1 << idx)) != 0) dtype = 'uint8' cmap = [] for i in range(N): r = g = b = 0 c = i for j in range(8): r = r | (bitget(c, 0) << 7-j) g = g | (bitget(...
python
""" Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: — Média abaixo de 5.0: REPROVADO — Media entre 5.0 e 6.9: RECUPERAÇÃO — Média 7.0 ou superior: APROVADO """ nt1 = float(input('Digite a nota da primeira avaliação: ')) nt2 = float(...
python
STARS = {"Alpheratz": {'sidereal': '357d41.7', 'declination': '29d10.9'}, "Ankaa": {'sidereal': '353d14.1', 'declination': '-42d13.4'}, "Schedar": {'sidereal': '349d38.4', 'declination': '56d37.7'}, "Diphda": {'sidereal': '348d54.1', 'declination': '-17d54.1'}, "Achernar": {'sidereal...
python
import UnitTest class WithTest(UnitTest.UnitTest): class Dummy(object): def __init__(self, value=None, gobble=False): if value is None: value = self self.value = value self.gobble = gobble self.enter_called = False self.exit_called...
python
import sys import os import select import socket import errno import logging try: BrokenPipeError except NameError: BrokenPipeError = None def ignore_broken_pipe(fn, *args): try: return fn(*args) except OSError as e: if e.errno == errno.EPIPE: return None raise ...
python
from __future__ import absolute_import from sentry.api.base import Endpoint from sentry.api.permissions import assert_perm from sentry.models import Group, GroupBookmark from rest_framework.response import Response class GroupBookmarkEndpoint(Endpoint): def post(self, request, group_id): group = Group.o...
python
from collections import deque water_reserve = int(input()) names = deque() while True: name = input() if name == "Start": while True: input_row = input() if input_row.startswith("refill"): # add litters to water_reserve water_reserve += int(input_...
python
#!/usr/bin/env python #============================================================================== # python3_test.py #------------------------------------------------------------------------------ # description :This is a basic python script example with a file header # author :l-althueser # # usage ...
python
#!/usr/bin/env python from nose.tools import assert_equal, assert_true, assert_almost_equal, nottest, assert_false from os.path import isdir,isfile from os import listdir import os import sys import subprocess import pandas as p file_path = os.path.realpath(__file__) test_dir_path = os.path.dirname(file_path) tmp_dir_...
python
import os import Threshold import UsersBuilding import Cluster import configparser import json from collections import defaultdict def get_project_path(file_name="README.md", actual_path=None): """ :param file_name: name of a file in the top level of the project :param actual_path: actual path, if not sp...
python
import os import logging import pytest log = logging.getLogger(__name__) from .testutils import check_serialize_parse def _get_test_files_formats(): skiptests = [] for f in os.listdir("test/n3"): if f not in skiptests: fpath = "test/n3/" + f if f.endswith(".rdf"): ...
python
import math import torch from torch.autograd import Variable from core.model_tools.deformations.exponential import Exponential from core.models.abstract_statistical_model import AbstractStatisticalModel from core.models.model_functions import create_regular_grid_of_points, compute_sobolev_gradient from core.observati...
python
#!/usr/bin/env python import os, os.path, sys import socket if __name__ == "__main__": PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',)) print "PROJECT_ROOT=", PROJECT_ROOT sys.path.append(PROJECT_ROOT) # Add virtualenv dirs to python path host = socket.gethostn...
python