content stringlengths 5 1.05M |
|---|
# multiprocessing örneği
# kodlaması diğerlerine göre daha kolaydır
# Session nesnesinin kullanımına ise dikkat edilmelidir
# Process başına nasıl ayarlandığı başka ortak nesne kullanan senaryolar için yol göstericidir
import requests
import time
import multiprocessing
# Pool içindeki her process kendi bellek alanınd... |
import os
import unittest
from .smart_excel import (
SmartExcel,
validate_position
)
children_things = [
{
'parent_id': 42,
'result': 'yes'
},
{
'parent_id': 42,
'result': 'no'
},
{
'parent_id': 43,
'result': 'oui'
},
{
'paren... |
from .file_source import FileSource
from .json_source import JSONSource
from .toml_source import TOMLSource
from .yaml_source import YAMLSource
|
#!/usr/bin/env python
from ttastromech import TTAstromech
import time
if __name__ == '__main__':
r2 = TTAstromech()
try:
r2.run() # make random astromech sounds
time.sleep(2)
except KeyboardInterrupt:
print('bye ...')
|
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(threshold=np.inf)
import fusion
# Kinect module
import pyk4a
from helpers import convert_to_bgra_if_required
from pyk4a import Config, PyK4A
from pyk4a import PyK4APlayback
from icp_modules.ICP_point_to_plane import *
from ic... |
import logging
from typing import Dict
from carball.json_parser.game import Game
from carball.generated.api import game_pb2
from carball.generated.api.game_pb2 import mutators_pb2 as mutators
from carball.generated.api.player_pb2 import Player
log = logging.getLogger(__name__)
def create_dropshot_ball_events(game: G... |
"""
1. Store data long-term, slower access speed, on a magnetic disk, like documents
2. Store data short-term, faster access speed, like games or in-progress documents
3. Crunch numbers to make the computer run and do work
4. RAM is volatile, it dissapears when the power is cut. HDDs are non-volatile, the data remains ... |
"""
This module handles classes related to reading, modifying and writing 2DA files.
"""
from __future__ import annotations
from contextlib import suppress
from copy import copy
from enum import Enum
from typing import List, Dict, Optional, Any, Type
class TwoDA:
"""
Represents a 2DA file.
"""
def _... |
"""
========
Fractals
========
Fractals are geometric structures that are self-similar at any scale. These
structures are easy to generate using recursion. In this demo, we'll be
implementing the following fractals:
- Sierpinski Tetrahedron or Tetrix
- Menger Sponge
- Moseley Snowflake
Let's begin by importing some ... |
from datetime import datetime
from protean import BaseAggregate
from protean.core.value_object import BaseValueObject
from protean.fields.basic import DateTime, String
from protean.fields.embedded import ValueObject
class SimpleVO(BaseValueObject):
foo = String()
bar = String()
class VOWithDateTime(BaseVal... |
import sys
import math
import torch
import random
import numpy as np
import torch.nn as nn
import sim_utils as su
import model_utils as mu
import torch.nn.functional as F
from dataset_3d import get_spectrogram_window_length
sys.path.append('../backbone')
from select_backbone import select_resnet
from convrnn import... |
from flask_admin import expose
from flask_login import current_user
from secure_views import SecureBaseView
from dashboards import user_dash
class UserDashView(SecureBaseView):
def is_visible(self):
return current_user.is_authenticated
def __init__(self, *args, **kwargs):
self.app = kwargs.p... |
from typing import List, Optional
from modpath.dtypes import ModpathOptions
from modpath.funcs import segment, recombine
from modpath.errors import ArgumentError, PathOpError
def check_args(args):
if args.old_ext and args.multidot:
raise ArgumentError("Cannot use --old-ext with --multidot option")
def m... |
import json
import subprocess
import webbrowser
from abc import ABC, abstractmethod
from sys import platform
try:
import requests
from pylatex import NoEscape, Document, Package
except ModuleNotFoundError:
pass
class ReportBase(ABC):
def __init__(self):
super().__init__()
def make_tex(se... |
"""Routines for getting halo properties and links, and data derived from them, starting with a Halo or other object
"""
from __future__ import absolute_import
import sqlalchemy
from . import data_attribute_mapper
class HaloPropertyGetter(object):
"""HaloPropertyGetter and its subclasses implement efficient metho... |
import json
import re
import sys
from collections.abc import Mapping, KeysView, ValuesView, Callable
from datetime import datetime, date, timedelta
from pathlib import Path
from struct import calcsize, unpack_from, error as StructError
from traceback import format_tb
from types import TracebackType
from typing import U... |
funcionarios = []
for i in range(5):
dados=[]
dados.append(input("informe o nome do funcionario:"))
dados.append(input("informe o email do funcionario:"))
funcionarios.append(dados)
print(funcionarios)
|
from rest_framework import serializers
from FuncionariosApp.models import Departamento, Funcionario
class DepartamentoSerializer(serializers.ModelSerializer):
class Meta:
model = Departamento
fields = ('DepartamentoId', 'DepartamentoNome')
class FuncionarioSerializer(serializers.ModelSeria... |
#!/usr/bin/python3
import collections
import csv
import os
import sys
doc_template = """
<!DOCTYPE html>
<html>
<style>
@font-face {{
font-family:'Yandex Sans Display Web';
src:url(https://yastatic.net/adv-www/_/H63jN0veW07XQUIA2317lr9UIm8.eot);
src:url(https://yastatic.net/adv-www/_/H63jN0veW07XQUIA231... |
{
"variables": {
"copy_c_api": "no",
"c_api_path": "<(module_root_dir)/qdb",
},
"targets": [
{
"target_name": "<(module_name)",
"sources": [
"src/qdb_api.cpp",
"src/entry.hpp",
"src/expirable_entry.hpp",
... |
'''
03 - Line plot [3]
Now that you've built your first line plot, let's start working on the data that professor Hans Rosling used to build his beautiful bubble chart. It was collected in 2007. Two lists are available for you:
life_exp which contains the life expectancy for each country and
gdp_cap, which contains t... |
#!/usr/bin/env python3
from aws_cdk import core
from stacks.apiv2_stack import RestfulApiGatewayv2Stack
from stacks.config import conf
app = core.App()
cdk_env = core.Environment(region=conf.aws_region, account=conf.aws_account)
# Using API gateway v1
# from stacks.api_stack import RestfulApiGatewayStack
# RestfulA... |
#!/usr/bin/env python3
from action_msgs.msg import GoalStatus
from hapthexa_msgs.action import MoveLeg
from hapthexa_msgs.msg import ForceSensor
import rclpy
from rclpy.action import ActionClient
phase = 0
def forcesensor_callback(msg, node):
# node.get_logger().info('{0}'.format(msg.z))
if phase == 2 and... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import os
import re
import codecs
import tempfile
import types
import warnings
from mecabwrap.domecab import do_mecab, do_mecab_vec, do_mecab_iter
from mecabwrap.utils import detect_mecab_enc, find_dictionary
class TestDomecab(unittest.TestCase):
def ... |
"""
Support code for the test suite.
There's some Python 2.x <-> 3.x compatibility code here.
Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
"""
from __future__ import with_statement
import sys
import threading
import pickle
import Pyro4
__all__ = ["tobytes", "tostring"... |
from example_pkg import a
from example_pkg import b
print(a.name)
print(a.__path__)
print(b.name)
print(b.__path__)
|
from django.db import models
from django.utils.translation import gettext_lazy as _
# As django docs sugest define CHIOCES by suitably-named constant
# Field with restricted choices only are good when you need predefined filter
class Form(models.Model):
#
SIMPLE = "SP"
CIRCLE = "CB"
SPLIT_WITH_ICON = ... |
# SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
import adafruit_board_toolkit.circuitpython_serial
comports = adafruit_board_toolkit.circuitpython_serial.repl_comports()
if not comports:
raise Exception("No CircuitPython boards found")
# Pri... |
#!/usr/bin/python
# coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# 驼峰转下划线
def camel_to_underline(camel_format):
underline_format = ''
if isinstance(camel_format, str):
for _s_ in camel_format:
underline_format += _s_ if _s_.islower() else '_' + _s_.lowe... |
import random
import unittest
from pytm.pytm import (
TM,
Actor,
Boundary,
Data,
Dataflow,
Datastore,
Process,
Server,
Threat,
)
class TestUniqueNames(unittest.TestCase):
def test_duplicate_boundary_names_have_different_unique_names(self):
random.seed(0)
object... |
import uuid
from django.db import models
from django.utils import timezone
from django.core.mail import send_mail
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.base_user import BaseUserManager
from django.contrib... |
from django.db.models import Sum
from utils import constants
def shop_cart(request):
"""当前用户的购物车信息"""
user = request.user
cart_list = []
cart_total = {}
cart_count = 0
if user.is_authenticated:
# 我的购物车商品列表
cart_list = user.carts.filter(
status=constants.ORDER_STATU... |
from rest_framework import generics
from rest_framework.permissions import (
SAFE_METHODS, BasePermission, IsAuthenticated
)
from posts.models import Post
from .serializers import PostSerializer
class PostUserPermissions(BasePermission):
message = "Only the author of this post can edit or delete"
def ha... |
# -*- coding:utf-8 -*-
"""
@Author : g1879
@Contact : [email protected]
@File : session_page.py
"""
import os
import re
from pathlib import Path
from random import random
from time import time
from typing import Union, List
from urllib.parse import urlparse, quote
from requests_html import HTMLSession, HTMLRespon... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mlp
import seaborn as sns
mlp.style.use("seaborn")
df=pd.read_pickle("../data/df.pkl")
df['E10'] = df['Real Earnings'].rolling(window=120, min_periods=120).mean()
df["P/E10"] = df['Real Price'] / df['E10']
# Plot P
plt.plot(df[... |
import re
import inflect
from itertools import product
_parse_csv_line = lambda x: (x.split(','))
def flatten_tuple_results(results):
# Convert tuple results to a list of of CSV strings
result_arr = [item for sublist in results for item in sublist]
result_arr = [x.strip() for x in result_arr]
result... |
#encoding=utf-8
## SOLVED 2014/04/10
## 5777
# It was proposed by Christian Goldbach that every odd composite number can be
# written as the sum of a prime and twice a square.
# 9 = 7 + 2×12
# 15 = 7 + 2×22
# 21 = 3 + 2×32
# 25 = 7 + 2×32
# 27 = 19 + 2×22
# 33 = 31 + 2×12
# It turns out that the conjecture was false... |
# -*- coding: utf-8 -*-
#
# Copyright 2015-2015 Spotify AB
#
# 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... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: DeepSeaVectorDraw
class LineJoin(object):
Miter = 0
Bevel = 1
Round = 2
|
# Projeto: VemPython/exe041
# Autor: rafael
# Data: 16/03/18 - 10:49
# Objetivo: TODO A configuração Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e
# mostre sua categoria, de acordo com a idade.
# Até 9: MIRIM
# Até 14: INFANTIL
# Até 19: JUNIOR
# Até 20: SENIOR
# Acima: Master
... |
class Person:
def quack(self):
print("I say 'Quack'")
def walk(self):
print("Person walking")
class Duck:
def quack(self):
print("Quack!")
def walk(self):
print("Duck walk")
def feathers(self):
print("Ducks have feathers")
def InTheForest(duck):
duck.qua... |
from .. import TransformerAcceptanceTest
class TestNormalizeSettingName(TransformerAcceptanceTest):
TRANSFORMER_NAME = "NormalizeSettingName"
def test_normalize_setting_name(self):
self.compare(source="tests.robot")
def test_normalize_setting_name_selected(self):
self.compare(
... |
from ssaw import SettingsApi
from . import my_vcr
@my_vcr.use_cassette()
def test_settings_globalnotice(session):
"""Tests an API call to get/set global settings"""
SettingsApi(session).set_globalnotice('aaa')
r = SettingsApi(session).get_globalnotice()
assert r == 'aaa'
@my_vcr.use_... |
import os
import sys
import pytest
from pavo_cristatus.interactions.pavo_cristatus_status import PavoCristatusStatus
from pavo_cristatus.interactions.symbol_signature_replacer_interaction.symbol_signature_replacer_interaction import interact
from pavo_cristatus.module_symbols.module_symbols import ModuleSymbols
from ... |
"""
this program stores book information
A book has the following attributes
title,author,year,ISBN
User can:
view all records
search an entry
add entry
update entry
delete
close
"""
from tkinter import *
import backend
window=Tk() #creates a window object
window.wm_title("BookStore") #for naming your window
l1=Labe... |
import csv
import pandas
import json
class TermData:
def __init__( self ):
self._frequency = 1
self._documents = []
def incrementFrequency(self):
self._frequency = self._frequency + 1
def addDocument( self, doc_id ):
if doc_id not in self._documents:
self._docum... |
"""
Original Author:
Madrone (Jeff Kruys)
Created on:
2021-01-23
Purpose:
This script takes a feature class that contains Age in years (VRI, etc) and adds the binned ages (classes) to each overlapping polygon in the TEM feature class.
Usage:
Add_Age_Class_Data_To_tem.py bfc afc afl [-h] [-l] [-ld]
P... |
"""Tests for the ConsoleEnvironment and Console helper."""
from j5.backends.console import Console
def test_console_instantiation() -> None:
"""Test that we can create a console."""
console = Console("MockConsole")
assert type(console) is Console
assert console._descriptor == "MockConsole"
asser... |
from app.models import *
#Room states
for state in ['rented', 'reserved', 'avaliable', 'need_cleaning', 'need_repair']:
db.session.add(Room_state(state_name=state))
db.session.commit()
#Room types
for r_type in [2, 3, 4]:
db.session.add(Room_type(r_type=r_type))
db.session.commit()
# Add some rooms
db.sess... |
from pydbus import SystemBus
from gi.repository import GLib
import paho.mqtt.publish as publish
import json
import logging
logging.basicConfig(level=logging.DEBUG)
def mqtt(topic, payload, hostname="127.0.0.1", retain=False):
logging.debug('sending to mqtt: topic=%s payload=%s' % (topic, payload))
publish.singl... |
SOCIAL_AUTH_TWITTER_KEY = 'EGmxjE55yVQigPCPWoMqdRsNp'
SOCIAL_AUTH_TWITTER_SECRET = '9rnyiG5HRHH187hkaaCaSADHNP4tRAD4Ob7SZiCJb9lSbWw3Pg'
SUPERVISOR_USER = 'user'
SUPERVISOR_PASSWORD = '123'
SUPERVISOR_URI = 'http://'+SUPERVISOR_USER+':'+SUPERVISOR_PASSWORD+'@127.0.0.1:9001'
DATABASES = {
'default': {
'ENGI... |
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
import mxnet as mx
import argparse
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from mxnet import autograd
import numpy as np
import logging
from datetime import datetime
import os
import time
def fill_buf(buf, i, img... |
"""
montecarloDistribution.py
Created by Luca Camerani at 02/09/2020, University of Milano-Bicocca.
([email protected])
All rights reserved.
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library),
and is released under the "BSD Open Source License".
"""
from collections im... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 20:08:59 2019
@author: admin
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits.mplot3d import Axes3D
### scikit-learn库实现机器学习 ###
## iris数据集 ##
from sklearn import datasets
iris = datas... |
try:
from ysharp.ysharp_lexer import YsharpLexer
from ysharp.errors import syntax_error
except ModuleNotFoundError:
from ysharp_lexer import YsharpLexer
from errors import syntax_error
from sly import Parser
import pprint
import logging
class YsharpParser(Parser):
tokens = YsharpLexer.... |
import pytest
from deal_solver import Conclusion
from ..helpers import prove_f
@pytest.mark.parametrize('check', [
# compare
'{1, 2, 3} == {1, 2, 3}',
'{1, 2, 3} != {1, 2, 3, 4}',
'{1, 2, 3} == {3, 1, 2}',
'{1, 2, 3} == {3, 2, 1, 1, 2}',
'set() != {1}',
'{1} != set()',
'set() == set(... |
import argparse
class GshCommandParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
self.errored = False
return super().__init__(*args, **kwargs)
def exit(self, *args, **kwargs):
self.errored = True
def parse_args(self, *args, **kwargs):
res = super().p... |
class MoveFilter(object):
def _common_handle(self, moves, rival_move):
new_moves = list()
for move in moves:
if move[0] > rival_move[0]:
new_moves.append(move)
return new_moves
def filter_type_1_single(self, moves, rival_move):
return self._common_han... |
# profile settings elements
ELEMENTS = [
## Settings ##
## Account
# cover image enter
{
"name": "coverImage",
"classes": ["g-btn.m-rounded.m-sm.m-border"],
"text": ["Upload cover image"],
"id": []
},
# cover image cancel button
{
"name": "coverImage... |
import glob
import numpy as np
import torch
from ignite.contrib.handlers import param_scheduler
from ignite.contrib.handlers import ProgressBar
import monai
from monai.apps import load_from_mmar
from monai.transforms import (
CastToTyped,
ToTensord
)
from utils.logger import log
def _get_transforms(transf... |
import logging.config
import os
import uuid
from datetime import datetime
import pytz
from pynwb import NWBHDF5IO, NWBFile
from pynwb.file import Subject
from rec_to_nwb.processing.builder.originators.associated_files_originator import AssociatedFilesOriginator
from rec_to_nwb.processing.builder.originators.camera_de... |
# ------------------------------------------------------------------------------ #
# Author: Zhenwei Shao (https://github.com/ParadoxZW)
# Description: This is a 2D Cosine Attention Module inspired by
# [cosFormer: Rethinking Softmax in Attention](https://arxiv.org/abs/2202.08791).
# -----------------------------------... |
# Copyright 2014: Mirantis 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 b... |
# Import ROS2 libraries
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from rclpy.action import ActionClient
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
# Import message files
from geometry_msgs.msg import PoseStamped
from nav_ms... |
import asyncio
import json
import traceback
from datetime import datetime, timedelta
from nonebot import require
from nonebot.adapters.cqhttp import Bot
from nonebot.log import logger
from ..bilibili.activity import ActivityList, H5Activity, activity_list
from ..common import CONF, get_bot, send_exception_to_su
from ... |
# -*- coding: utf-8 -*-
__version__ = '0.1.6'
__all__ = ['read', 'reads']
__author__ = 'Alex Revetchi <[email protected]>'
import os
import io
import re
import sys
import copy
import json
from jcson import jpath
from jcson import jfixer
from collections import defaultdict, OrderedDict
if sys.version_info[0] ... |
"""CoreNLP-related utilities."""
def rejoin(tokens, sep=None):
"""Rejoin tokens into the original sentence.
Args:
tokens: a list of dicts containing 'originalText' and 'before' fields.
All other fields will be ignored.
sep: if provided, use the given character as a separator instead of
th... |
from __future__ import annotations
from typing import Tuple, Union
import numpy
from amulet.world_interface.chunk.translators import Translator
from PyMCTranslate.py3.translation_manager import Version
class JavaNumericalTranslator(Translator):
def _translator_key(
self, version_number: int
) -> Tu... |
# https://leetcode.com/problems/next-greater-element-i/
# ---------------------------------------------------
from collections import deque
from typing import List
# Runtime Complexity: O(nums2 + nums1)
# Space Complexity: O(nums2), if we don't count res
class Solution:
def nextGreaterElement(self, nums1: List[in... |
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV),
# copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
import numpy as np
import unittest
import logging
from p3iv_utils_probability.distributions import... |
"""
# trans-tool
# The translation files checker and syncing tool.
#
# Copyright ©2021 Marcin Orlowski <mail [@] MarcinOrlowski.com>
# https://github.com/MarcinOrlowski/trans-tool/
#
"""
from configparser import ConfigParser
from pathlib import Path
from typing import Dict, List
from transtool.config.config import Co... |
from lib.sentence2vec import Sentence2Vec
model = Sentence2Vec('./data/job_titles.model')
# turn job title to vector
print(model.get_vector('Uber Driver Partner'))
# not similar job
print(model.similarity('Uber Driver Partner',
'Carpenter/ Modular building installer'))
# a bit sim... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2014-2017 Alex Forencich
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... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from .. import... |
from flask import url_for
from flask_wtf import FlaskForm
from wtforms import ValidationError
from wtforms.fields import (
SubmitField,
IntegerField,
DateField,
StringField,
HiddenField
)
from wtforms.fields.html5 import EmailField
from wtforms.validators import Email, EqualTo, InputRequired, Length... |
import os, os.path
import contextlib
from . import verbose
from . import descr
from . import revision_sql
from . import receivers
from . import pg_role_path
from . import scr_env
from . import init_sql
def init_cmd(args_ctx, print_func, err_print_func):
verb = verbose.make_verbose(print_func, err_print_func, args_... |
import Quandl
def economic_indicator(source, country, indicator, **kwargs):
dataset = "{source}/{country}_{indicator}".format(
source=source.upper(),
country=country.upper(),
indicator=indicator.upper()
)
return Quandl.get(dataset, **kwargs)
class Fundamentals(object):
... |
import numpy as np
import os
import torch
from isaacgym import gymutil, gymtorch, gymapi
from isaacgym.torch_utils import *
from tasks.base.vec_task import VecTask
from isaacgymenvs.utils.torch_jit_utils import *
import time
class CubeBot_TargPos(VecTask):
def __init__(self, cfg, sim_device, graphics_device_id, h... |
from dataclasses import dataclass
from enum import Enum
class TokenType(Enum):
NUMBER = 0
PLUS = 1
MINUS = 2
MULTIPLY = 3
DIVIDE = 4
LPAREN = 5
RPAREN = 6
POWER = 7
MOD = 8
INTDIV = 9
LS = 10
RS = 11
GT = 12
ST = 13
EQU = 14
@dataclas... |
"""
Functions for generating bootstrapped error bars
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Governm... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
"""
Enumerate Hidden Markov Model
=============================
This example is ported from [1], which shows how to marginalize out
discrete model variables in Pyro.
This combines MCMC with a variable elimination algorithm, where we
... |
#!/usr/bin/env python
# coding: utf-8
# # QUESTION ONE (1)
# # DATA LOADING
# In[1]:
# I would have required to use dask which is a parallel form of data loading if
# the size of the data were heaavier to increase time efficiciency and avoiding loading
# all the data into the memory. An alternative is to chunk t... |
import pytest
from protoseg import Config
configs = {'run1':{},
'run2':{}}
def test_len():
config = Config(configs=configs)
assert(len(config), 2)
def test_index():
config = Config(configs=configs)
assert(config[0], 'run1')
assert(config[1], 'run2')
def test_iterator():
count = 0... |
from AbstractClasses.AbstractController import AbstractController
class ConsoleController(AbstractController):
def __init__(self, io_controller=None):
super(ConsoleController, self).__init__(io_controller)
def make_guess(self, line_number=None):
return super(ConsoleController, self).make_gues... |
# -*- coding: utf-8 -*-
import os
import pytest
from scout.utils.scout_requests import fetch_refseq_version, get_request
TRAVIS = os.getenv("TRAVIS")
def test_get_request_bad_url():
"""Test functions that accepts an url and returns decoded data from it"""
# test function with a url that is not valid
ur... |
# Exercise 1.8
# Author: Noah Waterfield Price
from math import pi
h = 5.0 # height
b = 2.0 # base
r = 1.5 # radius
area_parallelogram = h * b
print 'The area of the parallelogram is %.3f' % area_parallelogram
area_square = b ** 2
print 'The area of the square is %g' % area_square
area_circle = pi * r ** 2
prin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket
import string
import os
HOST = 'chat.freenode.net'
PORT = 6667
NICK = 'irCri'
IDENT = 'MM'
REALNAME = 'Mihai Maruseac'
OWNER = 'Mihai Maruseac'
CHANNELINIT = '#mm_test'
readbuffer = ''
s=socket.socket()
s.connect((HOST, PORT))
s.send('NICK ' + NI... |
# Copyright 2015, Pinterest, 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 writ... |
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
import pylab as plt
import numpy as np
import os
import sys
from astrometry.util.fits import fits_table
from astrometry.libkd.spherematch import match_radec
from astrometry.util.plotutils import PlotSequence
from legacyanalysis.ps1cat impor... |
import numpy as np
import matplotlib.pylab as plt
from scipy import interpolate
fig= plt.figure()
fig.suptitle('Estimated SOC and Real SOC Comparation',fontsize=14,fontweight='bold')
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Time(s)')
ax.set_ylabel('SOC')
calSOC=[]
dischargeSOC=[]
x=[]
y=[]
x1=[]
y1=[]
error=[]
disch... |
import pymysql as mdb
import traceback
class MyDB():
def __init__(self):
self.connection = None
self.cursor = None
def connect(self):
self.connection = mdb.connect('192.168.100.93', 'username', 'password', 'gestioip')
self.cursor = self.connection.cursor(mdb.cursors.DictCursor)
return self
def execute... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_leaflet as dl
import dash_leaflet.express as dlx
import db
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from dash.dependencies import Output, Input
from dash_extensions.javascript import assign
fr... |
# coding=utf-8
try:
from urllib2 import Request, urlopen, URLError, HTTPError
except Exception as e:
from urllib.request import Request, urlopen, URLError, HTTPError
import os
import netifaces
deviceId = None
gourpId = None
device_id_file_path = os.environ.get('DEVICE_UUID_FILEPATH','/dev/ro_serialno')
group_... |
import os
import random
import dialogflow_v2 as dialogflow
# path to the Google API credentials file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="path to your Google API credetials file"
# Google project ID from the agent settings page
PROJECT_ID = "your dialogflow project ID"
# the language your agent is trained on... |
import csv, argparse, os, re
parser = argparse.ArgumentParser()
parser.add_argument(
"--data_file", default=None, type=str, required=True, help="The input data file (a text file)."
)
parser.add_argument("--output_dir", default=None, type=str, required=True)
args = parser.parse_args()
with open(args.data_f... |
import datetime
from abc import ABC
from fedot.core.log import Log, default_log
class Timer(ABC):
def __init__(self, max_lead_time: datetime.timedelta = None, log: Log = None):
self.process_terminated = False
if not log:
self.log = default_log(__name__)
else:
self.l... |
"""Implementations of grading abstract base class managers."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and include ... |
from setuptools import setup
setup(
name="nnhealpix",
version="0.3.0",
description="",
url="",
author="Nicoletta Krachmalnicoff, Maurizio Tomasi",
author_email="[email protected], [email protected]",
license="MIT",
packages=["nnhealpix", "nnhealpix.layers"],
package_dir={"nnhea... |
import os, sys
import subprocess
from time import sleep
usage_string = """
Usage: python3 control_chrome.py <COMMAND>
<COMMAND>s available:
>> goto URL - Navigates the tab to 'URL' specified
>> previous - Go back in history
>> forward - Go forward in history
>> reload - Reloads current tab
>> close - Closes curr... |
# -*- coding: utf-8 -*-
import logging
from os import makedirs
from os.path import join, exists
from textlytics.sentiment.document_preprocessing import \
DocumentPreprocessor
from textlytics.sentiment.io_sentiment import Dataset
from textlytics.sentiment.io_sentiment import to_pickle
from textlytics.sentiment.lex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.