content stringlengths 5 1.05M |
|---|
import os
import unittest
from programytest.client import TestClient
class TelecomsMinutesTestsClient(TestClient):
def __init__(self):
TestClient.__init__(self, debug=True)
def load_storage(self):
super(TelecomsMinutesTestsClient, self).load_storage()
self.add_default_stores()
... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, 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
#
# ... |
import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
###############################... |
from django.conf.urls import include, url
from django.views.generic import RedirectView, TemplateView
from django.conf import settings
from django.http import HttpResponse
from .views import TextPlainView, VCardTemplateView, HomepageView
urlpatterns = [
url(r'^$', HomepageView.as_view()),
url(r'^contact/', in... |
from SentimentNetwork import SentimentNetwork
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines()))
g.close()
print ("Initializing Neural Network...")
sn = S... |
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
sender = forms.EmailField()
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea(attrs={'class': 'contact-textbox'}), max_length=2000) |
#execute函数可以执行scrapy脚本
from scrapy.cmdline import execute
#需要sys获得工程目录
import sys
import os
#需要设置工程目录,设置完工程目录之后调用execute函数才会生效
print(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
#execute相当于执行命令
execute(["scrapy","crawl","jobbole"]) |
from django.shortcuts import render, redirect
from django.db import connection
from .forms import ProfileForm, LocationForm, SearchLocationForm
import populartimes
import datetime
import math
from mycrawl import popCrawl
def index(request):
# Render the HTML template index.html with the data in the context varia... |
# text_extractor_image.py
# from text_extractor_image import extract_text_from_image
import tempfile
import subprocess
import os
# from PIL import Image
# import io
def ocr(path) -> str:
# path is an on-disk file
temp = tempfile.NamedTemporaryFile(delete=False)
process = subprocess.Popen(['tesseract', p... |
#Using list as a quesue
stock_price_queue = []
stock_price_queue.insert(0, 131)
stock_price_queue.insert(0,132)
stock_price_queue.insert(0, 133)
stock_price_queue.pop()
#Using collections.deque as a queue
from collections import deque
q = deque()
q.appendleft(5)
q.appendleft(8)
q.appendleft(10)
q
q.pop()
from coll... |
"""
Module Description
"""
import glob
import json
import logging
import os
import os.path as path
import sqlite3
import subprocess
import uuid
from typing import TextIO, Dict, FrozenSet, List
from test_info import TestInfo
from queue import Queue
from test_suite_information import TestSuiteInformation
from trace impo... |
import os
import time
def write_v_input(output_path,jobid,basic_v_dict):
v_input_map_dict = {}
mufa_v_input_file = output_path+ '/' + jobid + '/mufa/' + jobid + '_mufa_variant.input'
fw = open(mufa_v_input_file,'w')
fw.write('index\n')
for i in range(len(basic_v_dict)):
info = basic_v_dict[i]
#10:100008701:G... |
__all__ = ["SQSQueuePolicyNotPrincipalRule", "SQSQueuePolicyPublicRule", "SQSDangerousPolicyActionsRule"]
import logging
from typing import Dict, Optional
from pycfmodel.model.resources.sqs_queue_policy import SQSQueuePolicy
from cfripper.config.regex import REGEX_HAS_STAR_OR_STAR_AFTER_COLON
from cfripper.model.enu... |
from math import sqrt
def is_prime(pp: int) -> bool:
"""
Returns True if pp is prime
otherwise, returns False
Note: not a very sophisticated check
"""
if pp == 2 or pp == 3:
return True
elif pp < 2 or not pp % 2:
return False
odd_n = range(3, int(sqrt(pp) + 1), 2)
... |
import json
import os
from pkg_resources import resource_string
from .showit import (tile, image)
def get_version():
try:
# decode('utf-8') is used for python3.4, which reads all files as bytes.
version_json = json.loads(
resource_string(__name__, "VERSION").decode('utf-8'))
excep... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: al
@file: cluster_da.py
@time: 2020/5/16 23:20
@desc: cluster DA
'''
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.ta... |
from socket import *
import cv2
import threading
import struct
import numpy
class Camera_Connect_Object:
def __init__(self, D_addr_port=("192.168.0.105", 9901)):
self.resolution = [640, 480]
self.addr_port = D_addr_port
self.fps_protocol = 30 # 传输帧数
self.interval = 0 # 图片播放时间间隔
... |
# 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... |
import numpy as np
np.set_printoptions(suppress=True)
class GridWorld:
def __init__(self,GRID_SIZE=50):
self.grid_size = GRID_SIZE
self.num_states = self.grid_size**2
self.rewards = np.random.choice([0,-1],p=[0.67,0.33],size=(self.grid_size,self.grid_size))
self.rewards[0,self.grid... |
#!/usr/bin/env python
import sys
import os
import math
# ensure that the kicad-footprint-generator directory is available
#sys.path.append(os.environ.get('KIFOOTPRINTGENERATOR')) # enable package import from parent directory
#sys.path.append("D:\hardware\KiCAD\kicad-footprint-generator") # enable package import fro... |
# example class
class Auth:
def __init__(self):
self.is_auth = False
def set_is_auth(self, is_auth):
self.is_auth = is_auth
def get_is_auth(self):
return self.is_auth |
from torch import optim
from torch.optim import lr_scheduler
from .train import train
from .test import test
def learner(model, train_loader, test_loader, lambda_l1, epochs, device):
train_losses = []
test_losses = []
train_acc = []
test_acc = []
optimizer = optim.SGD(model.parameters(), lr=0.01... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Kun Huang <academicgareth@gmail.com>
import argparse
import importlib
def run(parser):
config = parser.__dict__
modstr = "scalpels.cli.actions.%s" % config.pop("action")
mod = importlib.import_module(modstr)
func = getattr(mod, "run")
return f... |
# -*- coding: utf-8 -*-
#
from .dobrodeev1970 import Dobrodeev1970
from .dobrodeev1978 import Dobrodeev1978
from .hammer_stroud import HammerStroud
from .stroud import Stroud
from .stroud1957 import Stroud1957
from .stroud1966 import Stroud1966
from .stroud1967a import Stroud1967a
from .stroud1967b import Stroud1967b
... |
import inspect
from abc import abstractmethod
from typing import Any, Dict, List, Sequence, Tuple, Union, cast
import pytorch_lightning as pl
import torch
from pytorch_lightning.trainer.optimizers import (
TrainerOptimizersMixin,
_validate_scheduler_optimizer,
)
from pytorch_lightning.utilities.model_helpers i... |
"""
This file is a script that launch all the Continuous Integration tools in the
tamarco project
"""
import os
import subprocess
PROJECT_ROOT = "."
REPORT_PATH = os.path.join(PROJECT_ROOT, "reports")
FLAKE8_REPORT_HTML_DIR = os.path.join(REPORT_PATH, "flake8-html")
FLAKE8_REPORT_FILE = os.path.join(REPORT_PATH, "fl... |
# -*- coding: utf-8 -*-
##
# \file init_tlm_ground.py
# \title Definition of the numerical parameters for the TLM method for the
# grid convergence sudy. The satial is an input parameter.
# The updated scheme that gives the pressure
# at each time iteration is defined in the upd_tlm... |
src = []
if aos_global_config.compiler == 'armcc':
component = aos_arch_component('armv7m', src)
component.add_global_asflags('--cpreproc')
component.add_sources('panic/panic_c.c', 'panic/panic_armcc.S')
if aos_global_config.arch == 'Cortex-M3':
component.add_sources('armcc/m3/port_c.c', '... |
import os
filepath = '/Users/khashiffm/Documents/Research/Cathylab/metagenomes/nifH/masterdata_17May2021/'
Carbohydrates_general = {"COG1653","COG1879","COG3839","COG1175","COG0395","COG1129","COG2211","COG0738","COG1134","COG1682","COG2271","COG5037","COG3822","COG1762","COG1925","COG2213","COG2893","COG3730","COG37... |
""" Code is generated by ucloud-model, DO NOT EDIT IT. """
from ucloud.core.typesystem import schema, fields
from ucloud.services.cube.schemas import models
""" Cube API Schema
"""
"""
API: CreateCubeDeployment
创建Cube的Deployment
"""
class CreateCubeDeploymentRequestSchema(schema.RequestSchema):
"""CreateCub... |
#!/usr/bin/env python3
import psutil
import os
import sys
import datetime
#subprcess.call ('ls -al', shell=True)
def find_ibofos_coredump_and_renaming():
core_dir_path = "/etc/pos/core"
file_list = os.listdir(core_dir_path)
for path in file_list:
filename = os.path.basename(path)
test_dir... |
from experiments.runner import *
from globalParams import *
import sys
#source_path = source_dir + "gas/extracted_gas.out.part2"
source_path = source_dir + "gas/data.csv"
def run_multiple_adam():
stats, labels = run_multiple(source_path,
[
[
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
_
/ | | __ _ __ _
/ | / |_||_|| ||
/ | / | |\ | ||_
/____ |__/\ . | | \|_|\_|
__________________________ .
Created on Mon Nov 12 14:52:58 2018
@author: chrisunderwood
Produce the spectrum of electrons from the... |
from unittest import TestCase
from unittest import mock
import netscan
TIME1 = 235135.31352
TIME_CHANGE_OLD = 12345
TIME_CHANGE_NEW = 246810
TIME_CHANGE_OLD_STR = 'Thu Jan 01 11:25:45'
TIME_DIFF = '2 days, 17:07:45'
timeMock1 = mock.MagicMock(return_value=TIME_CHANGE_NEW)
HOSTS_NEW1 = {
"mac1": {'ip': 'ip... |
"""Quick scripts that helps adding fake datas into
db for tests purposes"""
# /usr/bin/env python3
from sys import exit as sexit, path as spath
from os import getenv
import os.path
# import re
from random import randint
from time import time
from argparse import ArgumentParser
from pymongo import MongoClient # type:... |
import numpy as np
def is_int(value):
is_number = True
try:
int(value)
except ValueError:
is_number = False
return is_number
def is_float(value):
is_number = True
try:
float(value)
except ValueError:
is_number = False
return ... |
from deep_translator import LingueeTranslator
res = LingueeTranslator(source="de", target="en").translate("laufen", return_all=False)
print(res)
|
from datetime import datetime
from Custom_Class import CAM, DENM, BEACON, RepeatedTimer, CAMSEM
from Queue import Empty
last_coord = [0, 0, 'N']
def create_and_send_denm(queue, identifier, state):
dt = str(datetime.now())
ttl = 5
msg = DENM(identifier, state, dt, ttl)
print("Send DENM message")
... |
import addpath
import dunlin as dn
import dunlin._utils_model.dun_string_reader as dsr
if __name__ == '__main__':
#Test preprocess_string
print('Test preprocess_string')
new = dsr.preprocess_string('a')
assert new == 'a'
new = dsr.preprocess_string('a,')
asse... |
import os
import webbrowser
import requests
from requests_oauthlib import OAuth2Session
from credentials import g_client_id, g_client_secret, refresh_token
from email.mime.text import MIMEText
auth_uri = 'https://accounts.google.com/o/oauth2/auth'
token_uri = 'https://accounts.google.com/o/oauth2/token'
redirect_uri =... |
"""Code to work with sensor data."""
import logging
_LOGGER = logging.getLogger('cs_esphome')
def parse_by_location(sensors):
"""Returns a dictionary of devices organized by the location."""
location_directory = {}
for sensor in sensors.values():
location = sensor.get('location', None)
... |
"""
compiler.py
----------------------------------------
This module contains the implementation of the
Scheme compiler for Schemey. It takes in one
or more expressions(a list of Pair objects), and generates
a code object ready for serialization and/or direct
execution by the virtual machine.
"""
from .bytecode impo... |
from flask import request, abort
from flask_restful_swagger_3 import Resource, swagger
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from models.user import User, validate_user, filter_user_response
from database.manager import db
import sqlite3
class UserAPICreate(Resource):
@swagger.doc({
... |
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
__author__ = 'weichen2046@gmail.com'
import logging
import os
import struct
from storage import StorageManager
from tcpserver.handler import NetworkCmdHandler
class SendFileHandler(NetworkCmdHandler):
def on_handle(self, net_ver, data):
self.netver = net_... |
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
"""Tests for the `CpParser`."""
import pytest
from aiida import orm
from aiida.common import AttributeDict
@pytest.fixture
def generate_inputs(generate_structure):
"""Return only those inputs that the parser will expect to be there."""
return Att... |
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pylab
import torch
from torchvision import transforms
def plot_labels(img,
labels,
color_dict={},
cmap="rainbow",
save_to=None,
axis=False,
... |
import boto3
import os
import simplejson as json
import uuid
from datetime import datetime, timezone
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html
def handler(event, context):
taskTable = os.environ['TASK_TABLE_NAME']
parameters = event['pathParameters']
taskId... |
import re
import sys
single_line_comment = re.compile(r'//.+$')
multi_line_comment_start = re.compile(r'/\*')
multi_line_comment_end = re.compile(r'\*/')
multi_line = False
for line in sys.stdin:
if multi_line:
print(line.strip())
comment = multi_line_comment_end.search(line)
... |
import logging
import os
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional
import docker
def format_container_output(output: bytes) -> str:
"""
Format the output of a Docker container for printing or logging.
Args:
output: Raw bytes output by the container.
... |
from urllib.parse import urlsplit
from django.contrib.sites.models import Site
def get_email_context():
site: Site = Site.objects.get_current()
send_email_kwargs = {"from_email": site.settings.default_from_email}
email_template_context = {
"domain": site.domain,
"site_name": site.name,
... |
#
# Copyright (c) 2018, Matthias Urlichs
#
"""asyncari client
"""
import urllib.parse
import anyio
from async_generator import asynccontextmanager
from asyncswagger11.http_client import AsynchronousHttpClient, ApiKeyAuthenticator
from asyncari.client import Client
@asynccontextmanager
async def connect(base_url, a... |
"""
About:
This python script is to convert a FIRMS csv export and add weather data to each point using the meteostat python library.
Meteostat imports weather data including average temperature (C), min and max temperature(C), precitpation, wind speed and direction and more by date and coordinates
The Meteostat pyth... |
# import socket
import os
from catalog.models import Author, Book, BookInstance, Genre
from django.shortcuts import render
from django.views import generic
from django.views.generic import ListView
def index(request):
"""View function for home page of site."""
# Generate counts of some of the main objects
... |
# pylint: disable=missing-module-docstring
from typing import Iterable
from .model import Pause
from .model import String
from .model import Tone
from .model import Element
def parse(string: str) -> String:
"""
Parses a dial string into an equivalent object representation.
"""
elements = _parse_ele... |
from model.json_model import JsonModel
class Legislation(JsonModel):
def __init__(self, file_num, file_link, legislation_type,
status, file_created,
final_action, title):
super().__init__()
self.file_num = file_num
self.fi... |
# Copyright 2014 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2015, ML4AAD"
__license__ = "3-clause BSD"
__maintainer__ = "Marius Lindauer"
__email__ = "lindauer@cs.uni-freiburg.de"
__version__ = "0.0.1"
import numpy as np
from smac.configspace import pcs
class InputReader(object):
"""
reading all input fil... |
#!/usr/bin/env python
import pytest
import rospy
from time import sleep
from sensor_msgs.msg import Image
def test_depth_ros():
is_ros_depth_publishing=False
def callback(data):
global is_ros_depth_publishing
is_ros_depth_publishing = True
rospy.init_node('test_ros_rgb')
ros... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='locate-darkness',
version='1.0',
description="Locate image file that have already been processed and move them to a directory.",
author="Visgean",... |
"""Module used to handle a API Server."""
import json
import logging
import os
import shutil
import sys
import warnings
import zipfile
from datetime import datetime
from glob import glob
from http import HTTPStatus
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, urlretrieve
from flask ... |
# class HyperParameters(object):
# START_TOKEN = 0
# END_TOKEN = 0
# VOCAB_LEN = 0
# MAX_WORD = 40
# TOKENIZER_MAX_WORDS = 100000
# MAX_GRADIANT_NORM = 5.0
# EMB_DIM = 300
# LEARNING_RATE = 0.001
# SEED = 47
# AE_LSTM_UNITS = 256
# KEEP_PROB = 0.95
# DECAY_RATE = 0.96
# ... |
import os
import json
import numpy as np
import argh
import boto3
from argh import arg
from tqdm import tqdm
from scipy.spatial import distance
from plotting_funcs import *
s3 = boto3.client('s3')
def compute_dist(img_embeds, dist_func=distance.euclidean, obj='Vehicle:1'):
dists = []
inds = []
for i in im... |
from immutablecollections import immutableset
ENGLISH_DETERMINERS = immutableset(["the", "a"])
DETERMINERS = immutableset(
[
"the",
"a",
"yi1_ge4",
"yi1_jang1",
"yi1_ben3",
"yi1_jyan1",
"yi1_lyang4",
"yi1_bei1",
"yi1_ba3",
"yi1_jr1",
... |
import sublime
import sublime_plugin
import re
import subprocess
import os
class GLShaderError:
""" Represents an error """
region = None
message = ''
def __init__(self, region, message):
self.region = region
self.message = message
class ANGLECommandLine:
""" Wrapper for ANGLE C... |
from recolo.math_tools.complex_step_diff import dF_complex_x, dF_complex_y, ddF_complex_x, ddF_complex_xy, ddF_complex_y
import numpy as np
from scipy.ndimage import gaussian_filter, gaussian_filter1d
from copy import copy
from collections import namedtuple
import logging
class FieldStack(object):
def __init__(se... |
from typing import Optional
import torch
from torch import nn, einsum
from einops import rearrange, repeat
class MultiheadAttention(nn.Module):
def __init__(
self,
in_dim: int,
*,
heads: int = None,
kv_dim: int = None,
head_dim: int = None,
proj_dim: i... |
# yacon.views.left_control.py
# blame ctrudeau chr(64) arsensa.com
#
# Left pane of Nexus control panel. Contains Site drop-down and the site
# tree.
#
import logging, json
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404
from yacon.decorators import superuser_required
fr... |
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Appointment
from .serializers import AppointmentSerializer
class AppointmentViewSet(viewsets.ModelViewSet):
serializer_class = AppointmentSerializer
queryset = App... |
from typing import Optional
from markdown import Markdown
from .grid_object import GridObject
from .mixin import SlideMixin
from .._utils import check_type
class TextBox(GridObject):
"""Represents a textbox on the slide.
Parameters
----------
content: str
A string containing the content of ... |
from .kmer_TextRank import km_text_rank
from .revkmer_TextRank import rev_km_text_rank
from .mismatch_TextRank import mismatch_text_rank
from .subsequence_TextRank import subsequence_text_rank
from .tng_TextRank import tng_text_rank
from .dr_TextRank import dr_text_rank
from .dt_TextRank import dt_text_rank
from ..util... |
import argparse
from codes.basic_functions.transferability import (interaction_reduced_attack,
leave_one_out)
from set_config import set_config
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--p", type=str, ... |
""" Data objects """
class DictProxy(dict, object):
""" Dictionary with attributes proxied to indicies (except for those starting with '_') """
def __init__(self, *args, **kwargs):
super(DictProxy, self).__init__(*args, **kwargs)
def __getattr__(self, key):
if key.startswith('_'):
... |
"""
HaloCatalog recipes
"""
from yt_astro_analysis.halo_analysis.halo_catalog.analysis_operators import add_recipe
def calculate_virial_quantities(
pipeline,
fields,
weight_field=None,
accumulation=True,
radius_field="virial_radius",
factor=2.0,
overdensity_field=("gas", "overdensity")... |
"""
Tensorflow - Keras Sequential RNN (GRU)
"""
import logging
from tensorflow.keras.optimizers import RMSprop # pylint: disable=import-error
import tensorflow as tf
from tensorflow_privacy.privacy.optimizers.dp_optimizer import (
make_gaussian_optimizer_class as make_dp_optimizer,
)
from tensorflow_privacy.priva... |
"""The tests for the IPMA weather component."""
from unittest.mock import patch
from collections import namedtuple
from homeassistant.components import weather
from homeassistant.components.weather import (
ATTR_WEATHER_HUMIDITY,
ATTR_WEATHER_PRESSURE,
ATTR_WEATHER_TEMPERATURE,
ATTR_WEATHER_WIND_BEARIN... |
def str_to_list(string: str, delim: str=',', trim: bool=True):
"""Convert a string to a list.
Returns an empty list if the string is ``None``.
Parameters
----------
1. string : str
- The input string to convert.
2. delim : str
- The delimiter between list items in the input str... |
import unittest #importing the unittest module
from account import Account #Importing the accountclass
class TestAccount(unittest.TestCase):
"""
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""... |
"""Scripts used to analyse bcftools roh output."""
import sys
import argparse
from itertools import islice
from operator import itemgetter
def list_mean(list):
"""Calculate the mean of a list with numbers."""
mean = float(sum(list)) / float(len(list))
return mean
def get_roh_regions(roh_file):
"""Cr... |
'''
Split houses
You live in a village. The village can be represented as a line that contains grids. Each grid can be denoted as a house that is marked as or a blank space that is marked as .
A person lives in each house. A person can move to a grid if it is adjacent to that person. Therefore, the grid must be pre... |
print("Calorie Calulator")
FAT = float(input("Enter grams of fat: "))
CARBOHYDRATES = float(input("Enter grams of Carbohydrates: "))
PROTEIN= float(input("Enter grams of Protein: "))
Fatg = 9 * FAT
print("Number of calories from Fat is: " + str(Fatg))
Protieng = 4 * PROTEIN
print("Number of calories from Prote... |
# -*- coding: utf-8 -*-
'''
'''
from __future__ import absolute_import
import logging
from .mail_helper import LoggingMailSender, MailxMailSender, SmtpMailSender
from .model_meta import dashboard_check_cfg
from .model_meta import team_mail_cfg
from . import conf
from . import const
import os
class MailSender(objec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from web import app
if __name__ == '__main__':
app.config['DEBUG'] = True
app.config['PREFERRED_URL_SCHEME'] = 'http'
app.run(host='0.0.0.0', port=8400)
|
from pearce.mocks.kittens import TestBox
from pearce.mocks import tpcf_subregions
import numpy as np
from collections import OrderedDict
from time import time
from scipy.optimize import minimize_scalar
import yaml
config_fname = 'xi_cosmo_trainer.yaml'
RR = np.loadtxt('RR_gg.npy')
with open(config_fname, 'r') as ym... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015 Mikael Sandström <oravirt@gmail.com>
# Copyright: (c) 2021, Ari Stark <ari.stark@netcourrier.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_functio... |
# Count Instances of a Character in a String
# Create a function that takes two strings as arguments and returns the number of times the first string (the single character) is found in the second string.
# char_count("a", "edabit") ➞ 1
def char_count(txt1, txt2):
return len(list(filter(lambda v: v == txt1, list(txt2)... |
# -*- coding: utf-8 -*-
from flask_restplus import Namespace, Resource, fields
from core.utils import paginate, validate_key
from flask import request
from core.connection import conn
from urllib import unquote_plus
import datetime
import settings
api = Namespace('properties', description='Property related operations'... |
import discord
from redbot.core import commands, checks
from typing import Optional
class TrustyBot(commands.Cog):
"""
This is mostly a test cog to try out new things
before I figure out how to make them work elsewhere
Generally for commands that don't fit anywhere else or are
not ... |
from arm.logicnode.arm_nodes import *
class GetMouseMovementNode(ArmLogicTreeNode):
"""Get the movement coordinates of the mouse and the mouse wheel delta.
The multiplied output variants default to -1 to invert the values."""
bl_idname = 'LNGetMouseMovementNode'
bl_label = 'Get Mouse Movement'
arm... |
import boto3
class SimpleStorageServiceDao:
def __init__(self, s3_bucket, s3_path, file_types: tuple):
self.s3_bucket = s3_bucket
self.s3_path = s3_path
self.file_types = file_types
self.s3 = boto3.client("s3")
def get_file_list(self) -> list:
"""
list fi... |
__all__ = ["quadratic-equation-solver"]
|
from ..process_sequence_properties import process_sequence_properties
class Command:
name = "extract_sequence_data"
help = "Process unit tool : Extract and process sequence properties."
def add_basic_arguments(self, parser):
parser.add_argument(
"--rerun", help="rerun the processing",... |
# Copyright 2011 OpenStack Foundation
# 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 requ... |
#!/usr/bin/env python3
import sys
import re
import os
import os.path
import subprocess
BASE_DIR = '/opt/tsadmdev'
sys.path.insert(0, os.path.join(BASE_DIR, 'libexec'))
sys.path.insert(0, BASE_DIR)
import tsadm.config as tsadm_conf
import tsadm.log
import runner
at_cmd = '/usr/bin/at'
runbg_cmd = os.path.join(BASE_... |
from django.urls import path
from .views import *
app_name = "buckets"
urlpatterns = [
path('bucketList/', view_bucket, name="view_bucket"), # 버킷리스트 카테고리 목록
path('write/', write, name="write"), # 버킷리스트 작성
path('create/', create, name="create"), # CREATE
path('update/<int:bucket_id>', update, name="update"), # ... |
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
import os
import sys
import subprocess
import pyspark.sql.functions as func
from pyspark.sql.types import StringType, ArrayType
import re
# from pyspark.sql.functions import col,lit
class Tools(): ... |
import logging.config
from argparse import ArgumentParser
from raconteur.config import config
from raconteur.db import setup_db
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"root": {"level": "INFO", "handlers": ["console"]},
"loggers": {
"gunicorn": {"level": "INFO", "pr... |
#!/usr/bin/env python
import sys, getopt, traceback
from datetime import datetime, timedelta
from flyefitpal import WorkoutSession, FlyefitPal, GymSiteNotFound, WrongTimeSlotException, \
FullyBookedException, AlreadyBookedException, NotYetAvailableException, \
DailyLimitReachedException
help_message =... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
coolDown = sell = 0
hold = float('-inf')
for dailyPrice in prices:
prevCoolDown, prevSell, prevHold = coolDown, sell, hold
coolDown = max(prevCoolDown, prevSell)
sell = prevHold + daily... |
from . import datelock, db, get, feed, output
from bs4 import BeautifulSoup
import aiohttp
import asyncio
import concurrent.futures
import datetime
import re
import sys
class Search:
def __init__(self, config):
self.init = -1
self.initial = -1
self.feed = [-1]
self.count = 0
self.config = config
self.d = ... |
'''
Video game description language -- parser, framework and core game classes.
@author: Tom Schaul
'''
import pygame
from pygame.math import Vector2
import random
from .tools import Node, indentTreeParser, PrettyDict
from collections import defaultdict, UserDict
from .tools import roundedPoints
import math
import nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.