content stringlengths 5 1.05M |
|---|
# Copyright (c) 2014 Baidu.com, 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 applicable law o... |
from typing import Tuple, List, TypedDict, Union
from enum import Enum
from fpdf import FPDF
from PIL import Image
from .utils import plural
class PageSize(Enum):
"""Page size"""
image = 'image'
A4 = 'A4'
A3 = 'A3'
A2 = 'A2'
A1 = 'A1'
A0 = 'A0'
letter = 'letter'
legal = 'legal'
c... |
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2013-2015 First Flamingo Enterprise B.V.
#
# 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... |
import re
import glob2
class TranslationService:
@staticmethod
def refresh_translatables():
"""
Read through frontend files and extract translatable strings
"""
# Get translatable strings
strings = TranslationService._get_translatables()
# Replace english lan... |
"""Helper for unittests"""
NAME1, NAME2, NAME3, SLASH, SLASH_ = "NAME1", "NAME2", "NAME3", "A/B", "A%2FB"
|
#
# Common inventory-related routines (used by Ansible and Devices)
#
import typing
from box import Box
from ..augment import devices
topo_to_host = { 'mgmt.ipv4': 'ansible_host', 'hostname': 'ansible_host', 'id': 'id' }
topo_to_host_skip = [ 'name','device' ]
def provider_inventory_settings(node: Box, defaults: Box... |
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Profile, Neighbourhood, Business, Post
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['userna... |
# Copyright 2018 Microsoft Corporation
#
# 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... |
from flask_restful import Resource
from .. import api_root, app
from ...service.business.preordered_ngspice_command import get_ngspice_verison
@api_root.resource('/version')
class Version(Resource):
def get(self):
return {
'ngspice': get_ngspice_verison(),
'ngspice-json-cli': app.... |
"""This test is here for legacy reasons. Originally the `pn.layout.divider` was no documented
so I created my own because I did not know better.
The `pn.layout.divider` reference example is now available
(here)[https://panel.holoviz.org/reference/layouts/Divider.html#layouts-gallery-divider]
"""
import awesome_p... |
#!/bin/bash/env
"""
This module is used to parse the xml config and hex file provided by user. It
takes the xml config and extracts the useful settings used during a CTD cast,
and uses that to check and parse the hex file.
"""
import datetime
import re
import struct
import xml.etree.cElementTree as ET
import numpy as... |
#%%
import numpy as np
import pandas as pd
import altair as alt
import anthro.io
# Generate a plot for Potash production
data = pd.read_csv('../processed/IFA_potash_public_2008_2019_processed.csv')
data['year'] = pd.to_datetime(data['Year'].astype(str), format='%Y', errors='coerce')
agg_data = pd.DataFrame()
agg_da... |
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from profiles_api.models import UserProfile
from profiles_api.models import ProfileFeedItem
# Register your models here.
class CustomUserAdmin(UserAdmin):
model = UserProfile
admin... |
from django.contrib import admin
from .models import Foundation, Awareness, Forums, Profile, Comment,Assessment
# Register your models here.
admin.site.register(Foundation)
admin.site.register(Awareness)
admin.site.register(Forums)
admin.site.register(Profile)
admin.site.register(Comment)
admin.site.register(Assessmen... |
# vim: ts=4:sw=4:et:cc=120
#
#
# NOTE the timeout option for get_alerts has to be an int for Redis < version 6
# so we're using integers for now
from typing import Optional
from ace.system.base import AlertingBaseInterface
from ace.exceptions import UnknownAlertSystemError
from ace.time import utc_now
KEY_ALERT_SYS... |
"""Database for indexing MXF files by umid."""
import json
import os
import subprocess
import string
import sqlite3
import tempfile
import warnings
from zipfile import ZipFile, BadZipFile
import zlib
# TO-DO: Why do we keep trying to re-index AS12/MXF/1?
# TO-DO: Fix mxf files that don't index
def get_media_stream(s... |
# 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 agreed to in writing, ... |
#!/usr/bin/env python3
from typing import Tuple
from functools import reduce
from math import sqrt, cos, exp, pi as PI
from time import time
from random import random, randint
from sys import exit
from neighbourhood import NeighbourhoodGenerator
def SalomonFunc(x: Tuple[float]) -> float:
x_length = sqrt(reduce(
... |
#arrays
import array as arr
a1 = arr.array['i',[1,2,3,4,5]]
print(a1) #will print object
for e in a1:
print(e)
#fixed size array generally
#mutable
|
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
import json
import httplib2
# Create your views here.
def index(request):
h = httplib2.Http(".cache")
resp, content = h.request("http://example.org/", "GET")
template = loader.get_template('w... |
"""
Extended SymPy hierarchy.
"""
import numpy as np
import sympy
from sympy import Expr, Integer, Function, Symbol
from devito.symbolics.printer import ccode
from devito.tools import Pickable, as_tuple, is_integer
__all__ = ['CondEq', 'CondNe', 'IntDiv', 'FunctionFromPointer', 'FieldFromPointer',
'FieldF... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import codecs
import nltk
import math
import json
import argparse
import hashlib
import torch
import torch.nn as nn
from misc.dataloader import *
import models.NMT_Models as NMT_Models
from six.... |
import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import random
from models import setup_db, Question, Category
QUESTIONS_PER_PAGE = 10
def paginate_questions(request, selection):
page = request.args.get('page', 1, type=int)
start ... |
import math
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms.functional as TF
import torch.nn.functional as F
from torch.autograd import Variable
from learning.model import convert_bn_to_instancenorm, convert_bn_to_evonorm, convert_bn_to_groupnorm, DeepLabHead, UNe... |
class MET(object):
"""
The Metabolic Equivalent of Task (MET), or metabolic equivalent, is a measure expressing the energy cost of physical activities. METs are defined as the ratio of metabolic rate (and therefore the rate of energy consumption) during a specific physical activity to a reference metabolic rate... |
from random import randint
from time import sleep
print('''\033[0:35mSuas opΓ§Γ΅es:
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] TESOURA\033[m''')
opcao = int(input('Qual Γ© a sua jogada? '))
comp = randint(0, 2)
comp_type = ''
player_type = ''
vencedor = ''
if comp == 0:
comp_type = 'Pedra'
elif comp == 1:
comp_type = 'Pape... |
from django.urls import path
from . import views
# TEMPLATE TAGGING
app_name = 'basic_app'
urlpatterns = [
path('relative', views.relative, name='relative'),
path('other', views.other, name='other'),
] |
def save_dataframe(list_of_dataframes, package_location):
"""
This function saves as CSV files each of the dataframes in the list 'list_of_dataframes' in the path
within the 'docs' folder specified in 'package_location'. It adds the 'easter', 'western' value at the
end of the path to differentiate betwe... |
# (C) Copyright 2015 Hewlett Packard Enterprise Development Company LP
#
# 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 ... |
import configparser
import logging
import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# sns.set()
# sns.set_color_codes()
COLLISION_WT = 5
COLLISION_HEADWAY = 10
VDIFF = 5
class CACCEnv:
def __init__(self, config):
self._load_config(config)
self.ovm = O... |
""" Heap and priority queue implementation. """
__author__ = 'Claus Martinsen'
class Heap:
""" A general purpose heap data structure. Wraps a normal list. """
def __init__(self, lst, heap_size=-1):
self.list = lst
self.heap_size = heap_size
if heap_size < 0:
self.heap_size... |
TABLE = {
'Linac multi-bunch beam energy': 'LI beam energy',
'Linac multi-bunch RF frequency': 'LI rf frequency',
'Linac multi-bunch maximum normalized emittance': 'LI optics maximum normalized emittance',
'Linac multi-bunch maximum rms energy spread': 'LI optics maximum rms energy spread',
'Linac ... |
class CloudshellResourceRemover(object):
def remove_resource(self, session, resource_full_name):
"""
removes resource from session
:type resource_full_name: str
"""
session.DeleteResource(resource_full_name)
|
#!/usr/bin/env python
#
# Copyright 2007 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... |
f = open("./test/s3.2.txt")
class Res(object):
def __init__(self, name, dep=[]):
self.name = name
self.dep = dep
total, phoNum = [int(x) for x in f.readline().split()]
phos = [int(x) for x in f.readline().split()]
maps = []
for i in range(total-1):
a, b = [int(x) for x in f.r... |
#!/usr/bin/env python3
for a in range(1, 1000):
for b in range(1, 1000):
c = 1000 - a - b
if c * c == a * a + b * b:
print(a*b*c)
break
else:
continue
break
|
from transformers import Trainer, TrainerCallback, TrainingArguments, TrainerState, TrainerControl
class KeplerCallback(TrainerCallback):
def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
self.tr_mlm_loss = 0
self.tr_ke_loss = 0
self.... |
import jingo
import forms
from babel.dates import format_date, format_datetime
@jingo.register.function
def BasicSearchForm(request):
if 'term' in request.GET:
data = {'term': request.GET['term']}
else:
data = {'term': 'Search'}
form = forms.SearchForm(data)
return form
@jingo.regist... |
neopixel = Runtime.createAndStart("neopixel","NeoPixel")
def startNeopixel():
neopixel.attach(i01.arduinos.get(rightPort),23,16)
neopixel.setAnimation("Ironman",0,0,255,1)
pinocchioLying = False
def onStartSpeaking(data):
if (pinocchioLying):
neopixel.setAnimation("Ironman",0,255,0,1)
else:
... |
from rest_framework import serializers
from .models import Image, Comment, Like
from nomadgram.users.models import User
class CountImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = (
'id',
'file',
'comment_count',
'lik... |
from mock import call, ANY
from raptiformica.cli import parse_inject_arguments
from tests.testcase import TestCase
class TestParseInjectArguments(TestCase):
def setUp(self):
self.argument_parser = self.set_up_patch('raptiformica.cli.ArgumentParser')
self.parse_arguments = self.set_up_patch('rapti... |
#!/usr/bin/env python
import re
import os
import sys
import shlex
import urllib2
import getpass
import logging
import ConfigParser
import logging.handlers
def verify_key_id(otp):
keys = config.get('keys', os.environ['USER']).split(':')
if otp[0:12] in keys:
log.info('Key ID verified')
retu... |
# Binary search inorder traversal asked by Amazon
# struct Node
# {
# int data;
# Node *right.*left,*random
# }
# Tree should be in-order traversal and random node should keep the in-order transversal path.
class Stack:
def __init__(self):
self.stack = [0]*10
self.head = -1
self.numEle = 0
def push(self... |
import os
import numpy as np
from pymooCFD.setupOpt import *
from pymooCFD.util.handleData import loadCP
def runGen0():
########################################################################################################################
###### RUN GENERATION 0 #######
from pymoo.optimize import m... |
# 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 t... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import datapackage
class Task(object):
"""Base class for Data Quality CLI tasks."""
def __init__(self, config, **kwargs):
... |
# Copyright 2016 Canonical Limited.
#
# This file is part of charm-helpers.
#
# charm-helpers is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3 as
# published by the Free Software Foundation.
#
# charm-helpers is distributed in the hope that ... |
from hypoxia import HashMap
h = HashMap(foo = 'bar')
assert h['foo'].unwrap() == 'bar'
assert h['kazoo'].unwrap_or('vuvuzela') == 'vuvuzela'
h['num'] = 2
assert h['num'].map(lambda x: x ** 2).unwrap_or(0) == 4
assert h['notnum'].map(lambda x: x ** 2).unwrap_or(0) == 0
d = dict(num = 2)
assert d.get('num', 0) ** 2 ... |
from src.controllers.home_controller import HomeController
from src.controllers.admin_controller import AdminController
|
from nose.tools import eq_
from postcrash.models import Signature
from sumo.tests import TestCase
from wiki.tests import document
class SignatureTests(TestCase):
def test_get_absolute_url(self):
doc = document(slug='foo-bar')
doc.save()
sig = Signature(signature='baz', document=doc)
... |
# django
from django import forms
# local django
from exam.models import CustomExam
from exam.validators import CustomExamValidator
from exam import constants
class UpdateCustomExamForm(forms.ModelForm):
"""
Form to edit a custom exam.
"""
description = forms.CharField(widget=forms.Te... |
import time
from .memcached import MemcachedStorage
class GAEMemcachedStorage(MemcachedStorage): # noqa
"""
rate limit storage with GAE memcache as backend
"""
MAX_CAS_RETRIES = 10
STORAGE_SCHEME = ["gaememcached"]
def __init__(self, uri: str, **options):
options["library"] = "goog... |
#!/usr/bin/python
import sys
import json
from pprint import pprint
import subprocess
params = json.load(sys.stdin)
ntpserver = params['ntpserver']
# puppet resource service ntp ensure=stopped
result={}
result['forcesync']={}
result['forcesync']['server']=ntpserver
result['forcesync']['output']=subprocess.check_out... |
import logging
import math
import time
from os import getenv
import os
from threading import Lock, Thread
from concurrent.futures import ThreadPoolExecutor
from stat import S_ISREG
from functools import wraps
from pathlib import Path
from paramiko import Transport, SFTPClient, Message
from paramiko.sftp_attr import SFT... |
#!/usr/bin/python
import getpass
import json
from globalconfig import passwd, url, usr
from vraapiclient import catalog
client = catalog.ConsumerClient(url, usr, passwd)
#Print table
client.getAllResources()
#Get JSON Object
resourcesJSONObject = client.getAllResources(show='json')
#Loop through object and print ... |
import logging
import unittest
from run_refinement import main
logger = logging.getLogger(__name__)
class TestSegmentationRefinement(unittest.TestCase):
def test_segmentation_refinement(self):
# Load data
dir = "./input/0_dataset_027"
config = "./config.yaml"
result_dict = main(... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from botorch.posteriors import Posterior
from ..botorch_test_case import BotorchTestCase
class NotSoAbstractPosterior(Posterior):
@property
def device(self):
pass
@property
def dtype(self):
... |
class BooleanModifier:
double_threshold = None
object = None
operation = None
solver = None
|
"""How to create and add items to dictionaries"""
# DNA_seq = dict()
# DNA_seq['me'] = 'agcta'
# DNA_seq['you'] = 'gtcaa'
# DNA_seq['them'] = 'cctag'
# print(DNA_seq)
# print(DNA_seq['me']) # use the key to access particular values in the dict
# DNA_seq['me'] = DNA_seq['me'] + 'gctagaa'
# print(DNA_seq)
"""Dictiona... |
#Describes properties of the follow-up observations
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from events import event
class followup:
def __init__(self, alert_name):
self.name = alert_name
self.lc_list = self.get_lc_list()
self.events = ... |
#!/usr/bin/env python
"""
Uses breadth-first search to find all valid words in a set of seven letters.
The definition of a "valid" word follows from the rules of the New York Times
Spelling Bee Game:
1. The word contains the "center" letter (designated here as the first letter in the
input list)
2. The word is at lea... |
from dataclasses import dataclass
from typing import List
import virtool.otus.isolates
import virtool.otus.sequences
from virtool.fake.wrapper import FakerWrapper
from virtool.otus.db import create_otu
from virtool.types import App
SEQUENCE = """
GTATTTTTACAACAATTACCAACAACAACAAACAACAAACAACATTACAATTACTATTTACAATTACAATG... |
import webbrowser
import os
import sys
file = sys.argv[1]
floors = sys.argv[2]
src = ''
for floor in range(1, int(floors) + 1):
src += file + str(floor)
os.system('python ifcToxkt.py ' + src)
src = ''
os.system('python htmlGen.py ' + file + ' ' + floors)
|
#!/usr/bin/env python3
'''test verification_code module.'''
from typing import List
import pytest
from verification_code import generate_code
# mypy has conflict with pytest decorations
@pytest.mark.parametrize(
"params, expected",
[
([0, 1, 2, 3, 4, 5, 6, 7, 8], '23456789C2'),
([2, 4, 7, 8,... |
from flask_admin.contrib.sqla import ModelView
from sqlalchemy import func
from bitcoin_acks.models import PullRequests
from bitcoin_acks.webapp.formatters import (
author_link_formatter,
body_formatter,
humanize_date_formatter,
labels_formatter,
last_commit_state_formatter,
line_count_formatte... |
#!/usr/bin/env python
# numpy and scipy
import numpy as np
#from scipy.ndimage import filters
# OpenCV
import cv2, sys
from cv_bridge import CvBridge, CvBridgeError
#ROS Libraries
#import roslib
import rospy
#ROS Messages
#from std_msgs.msg import String #Imports msg
from sensor_msgs.msg import CompressedImage, Ima... |
"""
`contextily`: create context with map tiles in Python
"""
from . import tile_providers as sources
from ._providers import providers
from .place import Place, plot_map
from .tile import *
from .plotting import add_basemap, add_attribution
__version__ = "1.0rc2"
|
# Requires the web browser module to open the image and time...
import webbrowser
import time
import sys
# Define helper function to print the following print on the same line
def print_no_newline(string):
sys.stdout.write(string)
sys.stdout.flush()
# Wait for it
time.sleep(0.5)
print(" Wait for it")
print(... |
def fizz_buzz(n):
'''return fizz when divisible by three
return buzz when divisible by 5
return fizzbuzz when divisible by both three and five
'''
if n % 3 == 0 and n % 5 == 0:
return 'FizzBuzz'
elif n % 3 == 0:
return 'Fizz'
elif n % 5 == 0:
return 'Buzz'
else:
return n
# print(fizz_buzz(3))
# print(... |
'''
Author: Caelin Muir
Contact: muir@ucsb.edu
Version: 210518
This script takes in a file path with one experiment as text file
It clusters with k=2
'''
#Imports
from sklearn.cluster import SpectralClustering
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score as ari
i... |
# Generated by Django 3.0.5 on 2020-05-14 16:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('investment_tracker', '0005_auto_20200514_1518'),
]
operations = [
migrations.RemoveField(
model_name='accountshares',
name='... |
from flask import redirect, url_for
from watch import app
from watch.utils.decorate_view import *
from watch.utils.render_page import render_page
@app.route('/<target>/S/<sid>')
@title('Session')
@template('single')
@columns({"sid": 'int'
, "serial#": 'int'
, "username": 'str'
, "status... |
import sys
import os
import logging
import datetime
import pandas as pd
from job import Job, Trace
from policies import ShortestJobFirst, FirstInFirstOut, ShortestRemainingTimeFirst, QuasiShortestServiceFirst
sys.path.append('..')
def simulate_vc(trace, vc, placement, log_dir, policy, logger, start_ts, *args):
if... |
"""
Class used to parse and update template when tracing is enabled
"""
import logging
from samcli.lib.init.template_modifiers.cli_template_modifier import TemplateModifier
LOG = logging.getLogger(__name__)
class XRayTracingTemplateModifier(TemplateModifier):
FIELD_NAME = "Tracing"
GLOBALS = "Globals:\n"
... |
# Copyright (c) 2019 kamyu. All rights reserved.
#
# Google Code Jam 2019 Qualification Round - Problem D. Dat Bae
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000051705/00000000000881de
#
# Time: O(NlogB)
# Space: O(N)
#
import sys
def dat_bae():
N, B, F = map(int, raw_input().strip().split(... |
from django.db.models.fields import (BooleanField, CharField, DateField, DateTimeField, FloatField,
IntegerField, TextField)
SERIALIZABLE_FIELD_NAMES = [
# Metadata
"date",
"participant_id",
"study_id",
# Data quantities
"accelerometer_bytes",
"ambient_audio_bytes",
"app_log_bytes... |
#!/usr/bin/env python
from gna.expression import *
i0 = Indexed('i0')
print( i0 )
i1 = Indexed('i1', 'i')
print(i1)
i2 = Indexed('i2', 'i', 'j')
print(i2)
j2 = Indexed('j2', 'j', 'k')
print(j2)
op = Indexed('operation_i1_i2_j2', i1, i2, j2)
print( op )
print( 'i1==i2', i1==i2 )
print( 'i1==i1', i1==i1 )
# print... |
import os
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('login.html')
@app.route('/login', methods=['POST'])
def login():
return 'You have successfully logged in'
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
... |
import quipuswap.models as models
from quipuswap.types.quipu_fa2.parameter.transfer import TransferParameter
from quipuswap.types.quipu_fa2.storage import QuipuFa2Storage
from dipdup.context import HandlerContext
from dipdup.models import Transaction
async def on_fa2_transfer(
ctx: HandlerContext,
transfer: T... |
import json
import os.path
class Game:
def __init__(self, json_string):
self.__dict__ = json.loads(json_string)
def toJSON(self):
return json.dumps(
self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
def filename(self):
""" Store the data in ./data with a js... |
from copy import deepcopy
from memory_allocation import MemoryAllocationSimulation
from processes import get_proportional_processes, get_equal_processes
def test():
summary = {}
equal = get_equal_processes(10, 30, 10, 10)
proportional = get_proportional_processes(10, 3, 5, 15)
simulations = {
... |
import datetime as dt
import statistics
import re
# need to set matplotlib backend before importing pyplot,
# else an error occurs if running without gui
import matplotlib
matplotlib.use('Agg')
import pandas
import matplotlib.pyplot as plt
plt.style.use('ggplot')
def id_from_link(link) -> str:
"""create a uniqu... |
#!/usr/bin/env python
# encoding: utf-8
"""
A module to recursively find and remove duplicate files.
A SHA1 hash will be used to calculate identical files.
All state will be pickled to disk so that progress can be resumed.
"""
import argparse
import hashlib
import logging as logging_lib
import os, os.path
import pickl... |
# -*- coding: utf-8 -*-
"""ERP - Sales volumes"""
import logging
from random import randrange
from types import ModuleType
from typing import List, Union
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from directory_tests_shared import URLs
from directory_tests_s... |
"""Tests if all the functions work correctly together"""
import matplotlib.pyplot as plt
from climvis.functions import process_date, era5_pos, variables_to_download
from climvis.functions import clim, yearly_evol, path
from climvis.download import download_era5, dwl_era5_enso
from climvis.plots import final_plot... |
from typing import List, Optional
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.dispatcher.filters.state import State, StatesGroup
from db import RedisDB as InterfaceDB
from config import DB_CONN
### STATES
class RegistrationStates(StatesGroup):
picking_username = State()
... |
import numpy as np
import matplotlib.pyplot as plt
from .utils import *
from .MTM import MTM
class LiverDeform(MTM):
def __init__(self, mesh_filename='liver_matdata_meter.json',E=1e4, v=0.4, gamma=-5, timeinterval=0.1,dt=1e-4,lamu_times=1e-1):
MTM.__init__(self,E=E,v=v,gamma=gamma,timeinterval=tim... |
import logging
import patterns.util.custom_logger as cl
from patterns.pages.base_page import BasePage
from patterns.pages.login_page import LoginPage
from patterns.util.page_loader import require_loaded
class SignUp(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().... |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by ... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../mojo_variables.gypi',
],
'targets': [
{
# GN version: //mojo/edk/system
'target_name': 'mojo_system_impl',
... |
import ibis.expr.operations as ops
from ibis.backends.base.sql.compiler import (
ExprTranslator,
QueryBuilder,
QueryContext,
Select,
SelectBuilder,
TableSetFormatter,
)
from ibis.backends.base.sql.registry import (
binary_infix_ops,
operation_registry,
quote_identifier,
)
def build... |
#!/bin/env python
from openforcefield.utils import *
from openforcefield.typing.engines.smirnoff import get_molecule_parameterIDs
oemols = read_molecules(get_data_filename('molecules/AlkEthOH-tripos.mol2.gz'))
ffxml = get_data_filename('forcefield/Frosst_AlkEthOH.offxml')
parameters_by_molecule, parameters_by_ID = g... |
# -*- coding: utf-8 -*-
from nltk.corpus import words
from itertools import permutations
def wordlist(letter_string, length=None):
"""Generate list of english words formed from letters in letter string.
Arguments:
letter_string {str} -- String of all of the letters that can be used
t... |
from src.premier import start
start() |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 10:43:22 2013
@author: hlampesberger
"""
from base import epsilon, state_generator
import collections
__all__ = ['write_graphviz']
def write_graphviz(vpa, fd, exclude_labels=False,
exclude_states=None):
# header
fd.write("digr... |
"""
File: pylinex/model/TransformedModel.py
Author: Keith Tauscher
Date: 22 Mar 2018
Description: File containing a class representing a model which is a simple
transformation of another model.
"""
import numpy as np
from distpy import castable_to_transform, cast_to_transform
from .Model import Model
cla... |
"""
Created by Minyong Jeong on 20.12.22
ν μ λ ¬μ λΉκ΅κΈ°λ° μ λ ¬ μκ³ λ¦¬μ¦μΌλ‘ μ νμ λ ¬μ ν₯μλ λ²μ μΌλ‘ λ³Ό μ μμ΅λλ€.
μ νμ λ ¬κ³Ό μ μ¬νκ² μ λ ¬λ μμκ³Ό μ λ ¬λμ§ μμ μμμΌλ‘ λλκ³ μ λ ¬λμ§ μμ μμμ κ°μ₯ ν° μμλ₯Ό μΆμΆν ν μ λ ¬λ μμμ μ½μ
ν©λλ€.
μ νμ λ ¬κ³Ό λ€λ₯Έ μ μ ν μ λ ¬μ μ λ ¬λμ§ μμ μμμ μ ννμμ μκ°μ λλΉνμ§ μμ΅λλ€.
μ ꡬνλ ν΅ μ λ ¬λ³΄λ€λ μ€νμλκ° λ€μ λ리며 O(nlogn)μ μκ°λ³΅μ‘λλ₯Ό κ°μ§λλ€.
[μ λ ¬κ³Όμ ]
1. μ λ ¬ν€μΌ ν μμλ€λ‘ μ΅λ ν νΈλ¦¬ λ₯Ό ꡬμ±ν©λλ€. (λ΄λ¦Όμ°¨μμΌλ‘ μ λ ¬μ μ΅... |
"""Tests for the Withings component."""
from unittest.mock import MagicMock, patch
import pytest
import voluptuous as vol
from withings_api.common import UnauthorizedException
import openpeerpower.components.webhook as webhook
from openpeerpower.components.withings import CONFIG_SCHEMA, DOMAIN, async_setup, const
fro... |
from pyspark.sql import SparkSession
import pytest
import atoolbox.spark.functions as tbs
def test_left_join_dataframes(test_data):
df_list = [test_data["dfa"].select("id", "a1"), test_data["dfb"].select("id", "b1"), test_data["dfc"].select("id", "c1")]
expected_cols = ['id', 'a1', 'b1', 'c1']
joined_df ... |
# Copyright (c) 2018 CEF Python, see the Authors file.
# All rights reserved. Licensed under BSD 3-clause license.
# Project website: https://github.com/cztomczak/cefpython
"""
Run all snippets from the examples/snippets/ directory
and display a summary at the end.
"""
from common import *
import glob
import os
impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.