content
stringlengths
0
894k
type
stringclasses
2 values
# # Convert raw output of the Caffe 'time' command # to the CK timing format. # # Developers: # - Grigori Fursin, cTuning foundation, 2016 # - Anton Lokhmotov, dividiti, 2016 # import json import os import re def ck_postprocess(i): ck=i['ck_kernel'] d={} ####################################### c...
python
#!/usr/bin/env python3 import asyncio import time import cryptocom.exchange as cro from cryptocom.exchange.structs import Pair from cryptocom.exchange.structs import PrivateTrade from binance.client import Client class CorecitoAccount: """Configures and runs the right code based on the selected exchange in config"""...
python
#!/usr/bin/env python import sys, os sys.path.append(os.path.realpath("..")) sys.path.append(os.path.realpath("../ElectronicComponents")) sys.path.append(os.path.realpath("../ElectronicModel")) import RPi.GPIO as GPIO ## Import GPIO library import time ## Import 'time' library. Allows us to use 'sleep' from Electroni...
python
""" ********** I2C Device ********** :Author: Michael Murton """ # Copyright (c) 2019-2021 MQTTany contributors # # 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, includin...
python
from rest_framework import serializers from .models import Hero, FAQ, Help, Privacy class HeroSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() class Meta: model = Hero fields = [ "id", "title", "description", ...
python
#!/usr/bin/python import os import matplotlib.pyplot as mplot import itertools from experiments import PATH_RESULTS, RESULT_SEP PATH_PLOTS = 'plots' PLOTS_EXTENSION = '.eps' PLOT_COLORS = itertools.cycle('bgrcmyk') # PLOT_STYLES = itertools.cycle('ov^<>1234sp*hH+xDd|_') PLOT_STYLES = itertools.cycle('op^s+xd|<D1H_>2...
python
import datetime, os, sys import logging, functools import inspect import timeit from .ext_time import time_elapsed from .decorators import apply_decorator_to_all_functions_in_module def apply_logging_to_all_functions_in_module(module): """ To be used after creating a logger with dero.logging.create_logger(),...
python
#!/usr/bin/env python """Demonstrates configurable logging output""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging def main(): """Main function Set arguments, configure logging, run test""" parser = argparse....
python
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-02-09 12:32 from __future__ import unicode_literals from django.db import migrations import mptt import mptt.managers def _add_mptt_manager(cls): manager = mptt.managers.TreeManager() manager.model = cls mptt.register(cls, parent_attr='super_event'...
python
import json with open("./package.json", "r") as f: data = json.loads(f.read()) with open("./package.py", "w") as fw: fw.write( "version = '{0}';stable = {1}".format( data["version"], data["stable"]))
python
from flask import Flask, render_template, request, redirect, url_for from index import Index app = Flask(__name__) @app.route("/", methods=["GET", "POST"]) def form(): return render_template("form.html") @app.route("/search_result", methods=["GET", "POST"]) def search_result(): if request.method == "POST":...
python
# -*- coding: utf-8 -*- from django.urls import * from .views import SuccessResponseView urlpatterns = [ path('preview/<int:basket_id>/', SuccessResponseView.as_view(preview=True), name='pagseguro-success-response'), path('checkout/payment-details/', SuccessResponseView.as_view(prev...
python
from .base_setup import Base from rest_framework import status from django.urls import reverse from django.core import mail from authors.apps.authentication.models import User from authors.apps.profiles.models import Profile from authors.apps.core.cron import EmailNotificationCron class ArticleDeleteUpdateTests(Base...
python
################################################################################# # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License, Version 2.0 (the "License"). ...
python
######################################## # QUESTION ######################################## # This time no story, no theory. The examples below show you how to write function accum: # Examples: # accum("abcd") -> "A-Bb-Ccc-Dddd" # accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" # accum("cwAt") -> "C-Ww-Aaa...
python
# # BSD 3-Clause License # # Copyright (c) 2017 xxxx # All rights reserved. # Copyright 2021 Huawei Technologies Co., Ltd # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain ...
python
import unittest import sklearn.grid_search from spark_sklearn.grid_search import GridSearchCV from spark_sklearn.random_search import RandomizedSearchCV from spark_sklearn.test_utils import fixtureReuseSparkSession # Overwrite the sklearn GridSearch in this suite so that we can run the same tests with the same # param...
python
#!flask/bin/python # # Copyright 2019 XEBIALABS # # 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 rights to use, copy, modify, merge, publish...
python
#Chocolate Distribution #this chocolate function will return the minimum required difference def chocolate(l, no_of_packets, no_of_students) : if no_of_packets < no_of_students : return -1 if no_of_packets == 0 or no_of_students == 0 : return 0 l.sort(); p = len(l) p = p - 1 #last i...
python
import models import logging from google.appengine.api import memcache # Memcache functions. def hitlist_cache(key,couple_key,update=False): # Try to get list on Eatery entity keys from memcache hitlist = memcache.get(key) if not hitlist or update: # Query all Eatery entities whose ancesto...
python
import torch.nn as nn class METValueMLPConverter(nn.Module): def __init__(self, global_average_pooling=True): super().__init__() self.met_regressor = nn.Sequential( nn.Linear(1280, 100), nn.ReLU(), nn.Linear(100, 1), nn.ReLU() ) sel...
python
from audioop import avg import matplotlib.pyplot as plt import matplotlib import numpy as np import sys import re import csv from itertools import groupby import glob from statistics import mean """ This script plots vertical frequency bars for one bandit experiment. Give -c as to load the experiment data from .csv f...
python
from abc import ABC, abstractmethod # Абстрактный класс для дополнения данных class Autocompleter(ABC): def __init__(self): super().__init__() # Получение автодополнений, где # con - соединение # tokens (list) - список лексем # content (str) - содержимое файла # line (int) - строка ...
python
import pandas as exporter import glob def convert(src, dest): read_file = exporter.read_excel(src) read_file.to_csv(dest, index = None, header=True) # convert all files in directory # @param srcDir (list) - source dir path # @param srcExt (string) - source file extension # @param destDir (string) - destination pa...
python
from app.data.database import DB from app.data.skill_components import SkillComponent from app.data.components import Type from app.engine import equations class StatChange(SkillComponent): nid = 'stat_change' desc = "Gives stat bonuses" tag = 'combat' expose = (Type.Dict, Type.Stat) va...
python
__all__ = ('Server', ) from ..traps import Future, skip_ready_cycle class Server: """ Server returned by ``EventThread.create_server``. Attributes ---------- active_count : `int` The amount of active connections bound to the server. backlog : `int` The maximum number of q...
python
import os, sys inFilePath = sys.argv[1] file, ext = os.path.splitext(inFilePath) print ext
python
# -*- coding: utf-8 -*- """The operating system file system implementation.""" import os import platform import pysmdev from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.lib import py2to3 from dfvfs.path import os_path_spec from dfvfs.vfs import file_system from dfvfs.vfs import os_file_entry...
python
#!/usr/bin/env python3 ''' usage: avr-objcump -zS firmware.elf | python avr-cycles.py usage: avr-objcump -zS firmware.elf | python avr-cycles.py --mmcu=<mmcu> @author: raoul rubien 07/2016 ''' import sys import csv import json scriptPath = sys.path[0] config = json.load(open(scriptPath + "/avr-cycle...
python
import sys sys.path.append('..') import os, time import cudf, cupy, time, rmm import dask as dask, dask_cudf from dask.distributed import Client, wait, progress from dask_cuda import LocalCUDACluster import subprocess import core.config as conf workers = ', '.join([str(i) for i in range(conf.n_workers)]) os.environ["...
python
__author__ = 'andre' import sys def main(): n = int(raw_input()) sys.stdout.write("\t") for i in range(27): sys.stdout.write(str(i+1) + "\t") for i in range(27): sys.stdout.write("\n" + str(i+1)+"\t") for j in range(27): if (i+1+(j+1)**2)%n==0: sys....
python
import gym from gym import spaces import numpy as np from gym.utils import seeding class BallInBoxEnv(gym.Env): """Custom Environment that follows gym interface""" metadata = {'render.modes': ['human']} def __init__(self): self.vmax = 1 self.r = 1 self.xmin = -10 self.xmax...
python
from kafka import KafkaConsumer consumer = KafkaConsumer(bootstrap_servers='localhost:9092', enable_auto_commit=False, metadata_max_age_ms=5000, group_id='test-consumer-group') consumer.subscribe(pattern='mytopic.*') try: for msg in consumer: print(msg.value.decode('utf-8'...
python
#!/usr/bin/env python3.8 import sys,os,getopt from atdfPeripherals import extractPeripherals from atdfModules import extractModules from atdfInterrupts import extractInterrupts def normalizeOffsets(peripherals,modules): #Normalize Peripheral and Module offsets for attiny and atmega. Newer Chips like ATMega4808 & fri...
python
#!/usr/bin/env python import sys from embedimg import version from embedimg import entry def embedimg(): sys.exit(entry.cli_start(version.version)) if __name__ == "__main__": embedimg()
python
from asyncio import sleep from datetime import datetime, timedelta from io import BytesIO from os import remove from os.path import isfile from typing import Optional from PIL import Image, ImageFont, ImageDraw, ImageOps from discord import Member, Embed, File from discord.ext.commands import Cog, command, cooldown, B...
python
_item_fullname_='openmm.AmberPrmtopFile' def is_openmm_AmberPrmtopFile(item): item_fullname = item.__class__.__module__+'.'+item.__class__.__name__ return _item_fullname_==item_fullname
python
# Copyright (C) 2021 GreenWaves Technologies, SAS # 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 the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This progr...
python
from matplotlib import pyplot as plt from matplotlib import text import numpy as np import matplotlib as mpl from matplotlib.font_manager import FontProperties #labels7 = ['neutral', 'angry', 'surprise', 'disgust', 'fear', 'happy', 'sad'] #labels6 = ['angry', 'surprise', 'disgust', 'fear', 'happy', 'sad'] #lab...
python
""" ===================================================== Exporting a fitted Earth models as a sympy expression ===================================================== A simple example returning a sympy expression describing the fit of a sine function computed by Earth. """ import numpy from pyearth import Earth from ...
python
from time import sleep from pysphere import VITask, FaultTypes from pysphere.vi_virtual_machine import VIVirtualMachine from pysphere.resources.vi_exception import VIException, VIApiException from pysphere.vi_mor import VIMor from pysphere.vi_task import VITask import ssl import pypacksrc import re, subprocess def ...
python
import numpy as np from ss_generator import geometry def get_internal_coordinates_from_ca_list(ca_list): '''Get the list of ds, thetas and taus from a ca list.''' ds = [] thetas = [] taus = [] for i in range(len(ca_list) - 1): ds.append(np.linalg.norm(ca_list[i + 1] - ca_list[i])) f...
python
from .base_api import BaseApi class CatalogApi(BaseApi): def _build_url(self, endpoint): catalog_endpoint = "/api/catalog_system" return self.base_url + catalog_endpoint + endpoint def get_category(self, category_id=1): endpoint = f"/pvt/category/{category_id}" return self._ca...
python
import cv2 import numpy as np import matplotlib.pyplot as plt import os vid=cv2.VideoCapture('/Users/lazycoder/Desktop/IEEE/video.mp4') #img=cv2.imread('/Users/lazycoder/Desktop/IEEE/Screenshot 2020-11-06 at 7.50.01 PM.png') wht = 320 classFile = '/Users/lazycoder/Desktop/IEEE/coco.names.txt' classNames = [] confTh...
python
# Copyright (C) 2020 FUJITSU # 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...
python
"""2020 - Day 3 Part 1: Toboggan Trajectory.""" from textwrap import dedent import pytest from src.year2020.day03a import solve @pytest.mark.parametrize( "task,expected", [ ( dedent( """ ..##....... #...#...#.. .#....#..#. ...
python
#!/bin/python3 import math import os import random import re import sys # Complete the rotLeft function below. def rotLeft(a, d): print(a) newArray = [ None for i in range(0, len(a)) ] #a is array of integers #d is #rotations for i in range(len(a)-1,-1,-1): newIndex = (i-d) % len(a) ...
python
import httpx from django.conf import settings def hcaptcha_verified(request): if settings.HCAPTCHA_ENABLED: if request.method == "POST": if request.POST.get("h-captcha-response"): # check hCaptcha h_captcha_response = request.POST.get("h-captcha-response") ...
python
# -*- coding: utf-8 -*- import importlib import os import subprocess import sys import pip import pkg_resources import pytest from django.core.management import call_command from django.test import TestCase from io import StringIO from pip._internal.exceptions import InstallationError class PipCheckerTests(TestCase)...
python
#! /usr/bin/env python from bs4 import BeautifulSoup from modules.utils import settings class AhgoraScrapper(object): __source = "" __scrapper = None __table = None def __init__(self, source=""): self.__source = source self.__scrapper = BeautifulSoup(self.__source) ...
python
# first find percentages per_men = (heart_df.sex.value_counts()[1])/(heart_df.sex.value_counts()[0]+heart_df.sex.value_counts()[1]) per_wom = (heart_df.sex.value_counts()[0])/(heart_df.sex.value_counts()[0]+heart_df.sex.value_counts()[1]) per_men, per_wom labels = 'Men', 'Women' explode = (0, 0.1) # only "explode" th...
python
import tensorflow as tf from keras.models import Model from keras.layers import Input, Dense #from keras.utils import to_categorical from keras import backend as K from keras import metrics, optimizers, applications, callbacks from keras.callbacks import ModelCheckpoint from keras.callbacks import LearningRateScheduler...
python
# -*- coding: utf-8 -*- import os DEBUG = True # Assumes the app is located in the same directory # where this file resides APP_DIR = os.path.dirname(os.path.abspath(__file__)) def parent_dir(path): '''Return the parent of a directory.''' return os.path.abspath(os.path.join(path, os.pardir)) PROJECT_ROOT =...
python
def extractBananas(item): """ Parser for 'Bananas' """ badwords = [ 'iya na kao manga chapters', ] if any([bad in item['tags'] for bad in badwords]): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): r...
python
import sys sys.path.append(".") import numpy as np import pytest from text_classification import data @pytest.mark.parametrize('texts, preprocessed_texts', [ ('Hello', 'hello'), ('HELLO', 'hello'), ('Hello, world!', 'hello world'), ('Hello, world!', 'hello world') ]) def test_preprocess_texts(texts,...
python
# coding: utf-8 from __future__ import print_function import platform import sys import os INTERP = platform.python_implementation() IRONPY = "ironpy" in INTERP.lower() PY2 = sys.version_info[0] == 2 if PY2: sys.dont_write_bytecode = True unicode = unicode else: unicode = str WINDOWS = False if platform...
python
#! /usr/bin/env python # Copyright 2018-2019 Mailgun Technologies 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 ap...
python
import numpy as np import h5py import scipy.io as sio import cv2 import glob from PIL import Image def calc_scannetv2(data_root,n_class): masks = [] size = (320,240) with open('./datasets/scannet/scannetv2_{}.txt'.format('train')) as f: scans = f.readlines() scans = [x.strip() for x in scan...
python
from aoc import AOC aoc = AOC(year=2020, day=15) series = aoc.load().numbers_by_line()[0] seen = {} n = 0 for idx, x in enumerate(series[:-1]): seen[x] = idx last = series[-1] n = len(series) while n < 30_000_000: if last in seen: next = n - 1 - seen[last] else: next = 0 seen[last] ...
python
""" Configuration loader using 'git-config'. """ import logging from git_pw import utils LOG = logging.getLogger(__name__) # TODO(stephenfin): We should eventually download and store these # automagically DEFAULT_STATES = [ 'new', 'under-review', 'accepted', 'rejected', 'rfc', 'not-applicable', 'changes-requ...
python
import threading from json import load from time import time, sleep from classes.logger import Logger from classes.product import Product from webbot import Browser class Site(threading.Thread): def __init__(self, tid, config_filename, headless = False): threading.Thread.__init__(self) self.tid ...
python
""" Copyright 2019 Software Reliability Lab, ETH Zurich 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 i...
python
# Copyright (c) Yiming Wang # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import torch from fairseq import metrics, options, search from fairseq.data import ConcatDataset from fairseq.tasks import FairseqTask, r...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import asyncore import socket import pickle import importlib import struct import ipaddress from ClusterInfo import ClusterInfo from Commands import Commands class JobManagerCommandHandler(asyncore.dispatcher): def __init__(self, svr_sock, job_manager): as...
python
import pyglet from pyglet.window import key from ctypes import pointer, sizeof import random from math import * sign = lambda x: copysign(1, x) class field: def __init__(self, dots, func, speed, lifespan, realSize, screenSize, theta=0, shift=(0, 0), imag=False, norm=False): self.num = dots self.F ...
python
from rest_framework import serializers from auth.models import Skill, Social, User class SocialSerializer(serializers.ModelSerializer): class Meta: model = Social fields = ("name", "logo", "link") def __str__(self) -> str: return self.name class SkillSerializer(serializers.ModelSer...
python
""" Implementation of logical and physical relational operators """ from ..baseops import UnaryOp from ..exprs import * from ..schema import * from ..tuples import * from ..db import Mode from ..util import cache, OBTuple from itertools import chain ######################################################## # # Source O...
python
import os import dotenv import errno import click import io import sys import pathlib class Config: """Accommodate config file creation by setting and getting it's class variables.""" user_access_key = "" user_secret_key = "" user_url = "nos.wjv-1.neo.id" user_gmt_policy = "notset" admin_...
python
# coding=utf-8 # Author: Diego González Chávez # email : diegogch@cbpf.br / diego.gonzalez.chavez@gmail.com # # This class controls the: # Radio Frequency Amplifier model 60/20S1G18A # by Amplifier Research # # TODO: # Make documentation import numpy as _np from .instruments_base import InstrumentBase as _InstrumentB...
python
XXXXXX XXXXXXX XXXXXXXBB BBBBBBBBBBBB BB BBBB XXXXXXXXBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBX
python
from hodolbot.classes import View from hodolbot.controllers import covid19_handler class Covid19View(View): command = "코로나" @staticmethod def get(): return covid19_handler()
python
# template script to create some easy plots for the chip problem import numpy as np import matplotlib.pyplot as plt import simnet as sn # set the path for the .npz files base_dir = 'network_checkpoint_chip_2d/val_domain/results/' # load the .npz files pred_data = np.load(base_dir + 'Val_pred.npz', allow_pickle=True)...
python
# -*- coding: utf-8 -*- from model.contact import Contact import random def test_delete_some_contact(app, db): if len(db.get_contacts_list()) == 0: app.contact.create(Contact(firstname="Test delete first contact")) old_contacts = db.get_contacts_list() contact = random.choice(old_contacts) app...
python
# Copyright (c) 2014 Evalf # # 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 rights # to use, copy, modify, merge, publish, distribute, s...
python
import logging import os from checkov.cloudformation import cfn_utils from checkov.cloudformation.checks.resource.registry import cfn_registry from checkov.cloudformation.parser import parse from checkov.common.output.record import Record from checkov.common.output.report import Report from checkov.common.runners.base...
python
# encoding: utf-8 from themonkey import * def calc_wordmetrics(wordfreqdict, charnlpdict): wordmetricdict = {} for word, freq in wordfreqdict.iteritems(): numsylls = word.count("-") + 1 word_nodash = word.replace("-","").replace(" ","").strip() numphones = len(word_nodash) phon...
python
import argparse from time import sleep from datetime import datetime import paho.mqtt.client as mqtt import RPi.GPIO as gpio PIN = 14 TOPIC = "home/power/meter" RECONNECT_DELAY_SECS = 2 DEFAULT_MQTT_PORT = 1883 FLASH_SECS = 0.02 FLASH_TOLERANCE_PCT = 10 def on_connect(client, userdata, flags, rc): print "Conne...
python
""" Test my new feature Some more info if you want Should work with python2 and python3! """ import unittest # if you need data from oletools/test-data/DIR/, uncomment these lines: ## Directory with test data, independent of current working directory #from tests.test_utils import DATA_BASE_DIR class TestMyFeature...
python
#---------------------------------------------------------------------- # Copyright (c) 2011-2015 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including ...
python
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import import sys import random import numpy as np from utils.rank_io import * from layers import DynamicMaxPooling import scipy.sparse as sp import inputs class PairBasicGenerator(object): def __init__(self, data_root, ...
python
""" Copyright (C) 2018, AIMLedge Pte, Ltd. All rights reserved. """ import pickle import os import face_recognition import cv2 import numpy as np from face_recognizer import FaceRecognizer, logger from scipy.spatial import distance FACE_REGISTRY_PATH = os.path.join(os.path.expanduser('~'), ...
python
from typing import Any from django.contrib.auth.models import Group from django.test import TestCase from pgq.decorators import task, JobMeta from pgq.models import Job from pgq.queue import AtLeastOnceQueue, AtMostOnceQueue, Queue class PgqDecoratorsTests(TestCase): def test_using_task_decorator_to_add_to_queu...
python
"""Mapping Vector Field of Single Cells """ from .estimation import *
python
from machine import I2C, Pin from sh1106 import SH1106_I2C import random from time import sleep # Options ROUND_WORLD = True # if True object can move around edges, if False edge is treated as an empty cell USE_USER_SEED = False # if True USER_SEED will be used to settle cells on world map, if False random seed wi...
python
import argparse import io import json import os import sys import zipfile import jinja2 def main(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--output') parser.add_argument('input') options = parser.parse_args() known_solution_tests = set() broken_tests = {} solution_...
python
__all__ = [ "assistant", "event", "error" ]
python
"""This class provides the Forward class""" import attr from ..handlers import CommandHandler, ReactionHandler from ..dataclasses import Thread, ThreadType, Message, Reaction, MessageReaction from .._i18n import _ @attr.s class Forward(object): """ This class provides a system for forwarding messages to a g...
python
from app import app, iam_blueprint, iam_base_url, sla as sla from flask import json, current_app, render_template, request, redirect, url_for, flash, session import requests, json import yaml import io, os, sys from fnmatch import fnmatch from hashlib import md5 from functools import wraps def to_pretty_json(value): ...
python
import sys import logging logging.basicConfig( format="[%(levelname)s] [%(name)s] %(asctime)s %(message)s", level=logging.INFO ) logging.StreamHandler(sys.stdout) logger = logging.getLogger("brev-cli") class Dev: api_url = "http://localhost:5000" log_level = logging.DEBUG cotter_api_key_id = "1902476...
python
# coding=utf-8 """ The Campaign Folders API endpoints Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaign-folders/ Schema: https://api.mailchimp.com/schema/3.0/CampaignFolders/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ...
python
""" This file tests the whole stack of the miura tool. """ import os import shlex import miura from jenkinsapi import jenkins from mock import Mock, patch, call from nose.tools import eq_ class TestMiura(): def setUp(self): self.old_dir = os.path.abspath(os.curdir) self.test_dir = os.path.dirname...
python
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Chemical structure resource. """ from everest.resources.base import Member from everest.resources.descriptors import member_attribute from everest.resources....
python
import gym import numpy as np from tqdm import trange scale = 3 src_prefix = "figures" seed = 100 def get_obs_spec(env_id): env = gym.make("fetch:" + env_id) env.seed(seed) buffer = [] for k, v in env.observation_space.spaces.items(): if hasattr(v, "spaces"): buffer += [f"{k}:"] ...
python
from coolname import generate_slug from flask import Flask, request from flask_cors import CORS from src.users.user_profile import ( get_user_profile, get_user_profiles, create_user_profile, update_user_profile, ) from src.teams.team_profile import ( get_team_profile, get_team_profiles, c...
python
#!/usr/bin/env python """ An example consumer that uses a greenlet pool to accept incoming market messages. This example offers a high degree of concurrency. """ import zlib # This can be replaced with the built-in json module, if desired. import simplejson import gevent from gevent.pool import Pool from gevent import...
python
def site_name(request): return { 'name_of_site': 'Worker Quest Tour' }
python
import pytest from cuenca.resources import CurpValidation, Identity @pytest.mark.vcr def test_identity_retrieve(curp_validation_request): # creating a curp_validation automatically creates the identity curp_validation = CurpValidation.create(**curp_validation_request) assert curp_validation.renapo_curp_m...
python
from hashlib import sha256 from zappa.async import task import hmac from flask import Flask, request, render_template import dropbox from dropbox.files import FileMetadata from dropbox.exceptions import ApiError import os import boto3 from boto.mturk.connection import MTurkConnection from boto.mturk.connection import H...
python
from pathlib import Path from code_scanner.analysis_result import AnalysisResult, AnalyzedFile from code_scanner.file_info import FileInfo from code_scanner.filter_utils import PythonSourceLineFilter def python_code_counter(root: Path, files: [FileInfo]) -> AnalysisResult: filtered_files: [AnalyzedFile] = [] ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved. """Contains a dict to validate the app configs""" VALIDATE_DICT = { "num_workers": { "required": False, "valid_condition": lambda c: True if c >= 1 and c <= 50 else False, "invalid_msg"...
python