content stringlengths 5 1.05M |
|---|
from pyiced import (
Align, container, Message, IcedApp, Length, Settings, Subscription,
text, WindowSettings,
)
class FullscreenExample(IcedApp):
def __init__(self):
self.__fullscreen = False
self.__should_exit = False
class settings(Settings):
class window(WindowSettings):
... |
from setuptools import find_packages, setup
import versioneer
with open('requirements.txt', 'rt') as f:
requirements = f.read().splitlines()
setup(name='happi',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
author='SLAC National Accelerator Laboratory',
packages=fi... |
import time
start_time = time.time()
a = 7
b = 3
c = a + b
print(c) #10
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time) |
import numpy as np
from scipy import integrate
from ..visualize import Logger
class LTI():
"""
This class present state-space LTI system.
Attributes:
dimension (tuple): (n_state, n_input).
model (dict): {A, B, C, D, dimension}.
max_step (float, optional): define max step fo... |
staticfiles_urls = {
# use only url
'my_app/js/jquery-3.2.1.min.js': 'https://code.jquery.com/jquery-3.2.1.min.js',
# or use url and checksum
'my_app/js/jquery-2.2.4.min.js': (
'https://code.jquery.com/jquery-2.2.4.min.js',
'sha384',
'rY/jv8mMhqDabXSo+UCggqKtdmBfd3qC2/KvyTDNQ6PcU... |
import psycopg2
###### HELPERS ######
def getCursor():
conn = psycopg2.connect(
host="localhost",
database="a3database",
port=5432,
user="cmsc828d",
password="password")
cursor = conn.cursor()
return cursor, conn
cursor, conn = getCursor()
#cursor.execute('DROP MA... |
# SPDX-FileCopyrightText: 2020 Robert Cohn
#
# SPDX-License-Identifier: MIT
import pytest
@pytest.mark.skip
def test_record_events(stores_with_home_events):
pass
|
from typing import Any, Dict, List, Optional, Sequence, Set, Union
import numpy
from . import _vroom
from .amount import Amount
from .location import Location, LocationCoordinates, LocationIndex
from .time_window import TimeWindow
class JobBaseclass:
"""Baseclass for all Job classes containing common attribute... |
from .momo import (
MomoPaymentRequest
)
MODELS_SCHEMAS = [
MomoPaymentRequest
]
# Execute model and schema
def ExtraPolate():
for models_n_schema in MODELS_SCHEMAS:
return models_n_schema
ExtraPolate()
|
def iterate_directories(path):
import os
rootdir = 'path'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
def iterate_folder(directory):
import os
files = {}
key = directory[-13:-6]
file_list=[]
for filename in os.listdir(directory):
if filename.e... |
# This file is part of the Reproducible Open Benchmarks for Data Analysis
# Platform (ROB) - Top Tagger Benchmark Demo Template.
#
# ROB is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Main pre-processing routing. Adjust to your spe... |
from typing import Any, Dict, Iterable, Optional
from django.conf import settings as root_settings
from rest_framework.settings import perform_import
class NestedSettings:
def __init__(
self,
user_settings: Optional[Dict[str, Any]],
defaults: Dict[str, Any],
import... |
L, R = map(int, input().split())
ll = list(map(int, input().split()))
rl = list(map(int, input().split()))
lsize = [0]*41
rsize = [0]*41
for l in ll:
lsize[l] += 1
for r in rl:
rsize[r] += 1
ans = 0
for i in range(10, 41):
ans += min(lsize[i], rsize[i])
print(ans)
|
#!/bin/env python
import os
import sys
import yaml
import signal
import time
import signal
import socket
from random import random
from argparse import RawTextHelpFormatter, \
ArgumentParser
from threading import Timer, Thread
import node
from config import config_yaml, \
threading_enabled, \
... |
#!/usr/bin/sage -python
"""Draw dynamical Lakes of Wada on the plane (method of Coudene; project with Weierstrass P function)"""
# This script uses Sagemath for the sole purpose of access to the
# special function "elliptic_f" which allows us to inverrt the
# Weierstrass P function. It would be a good idea to substit... |
import pytorch_lightning as pl
import torch.nn as nn
import torch.nn.functional as F
import torch
from torchmetrics import Accuracy, MetricCollection, F1
from pytorch_lightning.utilities.argparse import add_argparse_args, from_argparse_args
from transformers import BertModel
class BertClassifier(nn.Module):
"""U... |
from typing import Optional
from models.energy_model import EnergyModel
from models.modules.edge_update_net import EdgeUpdateNetWrap
class EdgeUpdateNetWrapper(EnergyModel):
def __init__(
self,
lr: int,
weight_decay: float,
normalize_labels: bool,
mean: Optional[float],
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
vg3k_raw_json_file = './lib/datasets/data/vg3k_bbox2mask/instances_vg3k_raw.json'
coco_minival_json_file = './lib/datasets/data/coco/instances_minival2014.j... |
# Regression analysis using scikit-learn functions
# Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.linear_model as skl
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
import os
# Wh... |
import unittest
from unittest import TestCase
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import StratifiedKFold
from exercies import SKLEARN_DATA
def sort_by_target(mnist):... |
# Copyright (c) 2020 PaddlePaddle Authors. 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 app... |
import pytest
@pytest.fixture
def raw_binlog_status():
"""
Returns base64 of binlog status
{
"master1/binlog/mysqlbin001.bin": {
"time_created": "100500"
},
"master1/binlog/mysqlbin002.bin": {
"time_created": "100501"
},
"master... |
from setuptools import setup, find_packages
setup(name='django_project',
version='0.1',
description='Base Django template for starting projects.',
url='http://github.com/dwdresser/django_project',
author='Doug Dresser',
author_email='dwdresser@wisc.edu',
license='MIT',
package... |
"""Models to represent task types and instances which run commands directly."""
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils import timezone
from tasksapi.constants import SUCCESSFUL, FAILED, EXECUTABLE_TASK
from tasksapi.t... |
# Generated by Django 3.2.4 on 2021-07-02 07:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('support', '0003_auto_202... |
import torch.nn as nn
from .xnor_layers import *
__all__ = ['lenet5']
class LeNet5(nn.Module):
def __init__(self, out_classes = 10):
super(LeNet5, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 20, kernel_size=5, stride=1),
nn.BatchNorm2d(20, eps=1e-4... |
# 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 django.test import TestCase
from django.urls import reverse
from .models import Task
from .forms import TaskForm
class IndexViewTests(TestCase):
def test_no_task(self):
"""
if there are no tasks show the appropriate message.
"""
response = self.client.get("/todo/")
se... |
import tqdm
import time
import pickle
import numpy as np
import torch
from lidardet.models import load_data_to_gpu
def eval_trajectory_prediction(cfg, model, dataloader, logger, dist_test=False, save_to_file=False, result_dir=None):
result_dir.mkdir(parents=True, exist_ok=True)
dataset = dataloader.da... |
import sys
import cv2
import numpy as np
from math import hypot
def distance(p, q):
return hypot(p[0] - q[0], p[1] - q[1])
def get_color_images(input_image):
high_poly = cv2.imread(input_image)
gray_image = cv2.cvtColor(high_poly, cv2.COLOR_BGR2GRAY)
ycbcr_image = cv2.cvtColor(high_poly, cv2.COLOR_RGB... |
from catalog.api.serializers.list_serializers import \
ImageListCreateSerializer, ImageListResponseSerializer, \
ImageListUpdateSerializer
from django.forms.models import model_to_dict
from catalog.api.models import ImageList
from catalog.api.utils.throttle import PostRequestThrottler
from drf_yasg.utils import... |
from kafka import KafkaConsumer
from time import sleep
def consumer_res():
consumer = KafkaConsumer('Reservations', bootstrap_servers = 'localhost:9092')
for msg in consumer:
print(msg)
sleep(5)
if __name__ == '__main__':
consumer_res()
|
# encoding=utf-8
import requests
import lxml
from bs4 import BeautifulSoup
class HTMLParser:
''' Parser '''
def __init__(self):
print('启动解析器')
def parse_a_page(self, download_html_text, data_num):
'''返回每个数据组成的字典 保存工作交给 Output
para: download_html_text为返回 text
da... |
import os
import smtplib
EMAIL = {
'SMTP_SERVER_HOST': os.getenv('SMTP_SERVER_HOST', 'apps.smtp.gov.bc.ca'),
'SMTP_SERVER_PORT': int(os.getenv('SMTP_SERVER_PORT', 25))
}
try:
with smtplib.SMTP(host=EMAIL['SMTP_SERVER_HOST'],
port=EMAIL['SMTP_SERVER_PORT']) as server:
serve... |
# Create your views here.
# -*- coding:utf-8 -*-
import logging
from django.db import transaction
from keystoneauth1 import exceptions as keystone_exceptions
from BareMetalControllerBackend.conf.env import EnvConfig
from common.lark_common.model.common_model import ResponseObj
from common.openstack import context
fr... |
# coding: utf-8
"""
Eclipse Kapua REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
i... |
#!/usr/bin/env python
import socket
import sys
import hashlib
import threading
from threading import Lock
import time
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
import otherfunc
#globally defined
host = []
path = []
tcps = []
port = 80
chunkSize = 10240 #10KB
chunks = [... |
#!/usr/bin/env python3
import sys
import os
import json
sys.path.insert(1, os.path.realpath(os.path.pardir))
import cards
def main() :
craft = 0
if len(sys.argv) == 2:
craft = int(sys.argv[1])
crafts = ['all', 'forest', 'sword', 'rune', 'dragon', 'shadow', 'blood', 'haven', 'portal']
if cra... |
import pymysql
global connection, cursor
try:
connection = pymysql.connect(host='localhost', port=3306, db='classicmodels', user='root', passwd='root')
cursor = connection.cursor()
cursor.execute("SELECT * FROM classicmodels.products limit 10")
record = cursor.fetchall()
# print("Your result : ", r... |
from .preprocessing import * # noqa: |
import ue4_constants
import pathlib
def get_test_profiles(run_config):
build_structures = run_config[ue4_constants.UNREAL_BUILD_SETTINGS_STRUCTURE]
profiles = {}
for each in build_structures.keys():
each_build_profile = build_structures[each]
if "run_scripts" in each_build_profile.keys(... |
# coding: utf-8
"""
Utilities and configuration file parsing.
"""
from __future__ import absolute_import, print_function
import os
import os.path
import sys
import platform
import re
import logging
import warnings
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import SafeCo... |
from __future__ import print_function, absolute_import
from six import iteritems, itervalues
from six.moves import range
from collections import OrderedDict
import xml.etree.ElementTree as ET
import numpy as np
typedefs = {
'integer': '<i8',
'double': '<f8'
}
class Field(object):
... |
from __future__ import print_function
from dataBinder import DataBinder
import torch
import torchvision
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import dataobject as dataobject
import neuralobject as neuralobject
from torch.utils.data import D... |
# coding=utf-8
from constantes import *
from pickle import Pickler, Unpickler
from gui import GUIBulleWaiting, GUIBulleAsking
import debug
from animator import CinematiqueCreator
# Attention, y a du hardcode dans l'air ^^'
class Adventure:
def __init__(self, ecran, font):
self.progress = 0
self.e... |
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Activation
from tensorflow.keras.models import load_model
from tensorflow.keras import optimizers
from tensorflow.keras import backend as K
K... |
"""
This package contains the zkay parser generated with ANTLR.
""" |
""" Scraper implementation """
import asyncio
import base64
import string
import os.path as path
from aiohttp import ClientSession, ClientTimeout
from aiohttp.client_exceptions import InvalidURL, ClientConnectionError
from yarl import URL
from lxml.html import fromstring
import newspaper
from company_scraper.scraper_co... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
from clasificador.herramientas.wiktionary import Wiktionary
class TestWiktionary(unittest.TestCase):
def test_esta_en_wiktionary_consulta_palabra_comun(self):
texto = "hola"
self.ass... |
#!/usr/bin/python
#Take the number 192 and multiply it by each of 1, 2, and 3:
# 192 x 1 = 192
# 192 x 2 = 384
# 192 x 3 = 576
#By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
#The same can be achieved by starting wit... |
#!/usr/bin/env python
#Runtime (690,130,128,128): ?
import cPickle
import networkx
full_output=False
def full_output(cloud_times, cloud_graphs, merges, splits, MC):
cloud_times = tuple(cloud_times)
cPickle.dump(cloud_times, open('pkl/cloud_times.pkl','wb'))
n = 0
clouds = {}
for subgraph in clou... |
import logging
import time
from django.conf import settings
from log_request_id import (
LOG_REQUESTS_SETTING,
REQUEST_ID_RESPONSE_HEADER_SETTING,
local,
)
from log_request_id.middleware import RequestIDMiddleware
from .logfmt import quote_logvalue
from sfdo_template_helpers.addresses import get_remote_ip
... |
import os
import pytest
from src.files.file_opener import FileOpener
def test_open_will_return_given_file(tmpdir):
file_name = 'filename.txt'
file_path = f'{tmpdir}/{file_name}'
expected_file_content = 'This is some test content of the file.\n Really cool!'
file = open(file_path, 'w+')
file.wri... |
from proteus import *
from proteus.default_n import *
from md_trans_p import *
timeIntegration = BackwardEuler_cfl
DT = 0.1
runCFL = 0.3
femSpaces = {0:C0_AffineLinearOnSimplexWithNodalBasis}
elementQuadrature = SimplexGaussQuadrature(nd,gw_quad_order)
elementBoundaryQuadrature = SimplexGaussQuadrature(nd-1,gw_quad_o... |
import numpy
from optimizer._internals.common import findiff
from overloads import bind_checker, difference, dyn_typing
from overloads.shortcuts import assertNoInfNaN
from overloads.typedefs import ndarray
H = numpy.array([[2, 1], [1, 1]])
A = numpy.array([[1, 1]], dtype=numpy.float64)
b = numpy.array([1], dtype=numpy... |
from cloudshell.api.cloudshell_api import CloudShellAPISession
from cloudshell.cli.service.cli import CLI
from cloudshell.cli.session.ssh_session import SSHSession
from cloudshell.cli.service.command_mode import CommandMode
from cloudshell.cli.session.telnet_session import TelnetSession
from cloudshell.shell.core.drive... |
import numpy as np
import matplotlib.pyplot as plt
import chainer
from brancher.variables import RootVariable, ProbabilisticModel
from brancher.particle_inference_tools import VoronoiSet
from brancher.standard_variables import EmpiricalVariable, NormalVariable, LogNormalVariable
from brancher import inference
from bra... |
import re
from typing import Dict, Optional, List
import requests
from dataset_tools import QuestionCase
from .base_entitity_linking_system import EntityLinkingSystem, EntityLinkingDict
from mapping.mapper import MapEntitiesWikipediaToWikidata
from query_tools import WIKIDATA_ENDPOINT_URL
token = ""
TAGME_URL = "ht... |
class Solution:
def maxConsecutiveAnswers(self, answerKey, k):
return max(self.mca(answerKey, 'T', k), self.mca(answerKey, 'F', k))
def mca(self, answerKey, ch, k):
j = count = result = 0
for i, v in enumerate(answerKey):
if v == ch:
count += 1
wh... |
import os
import shutil
from iatv.iatv import Show
from collections import namedtuple
VideoInfo = namedtuple('VideoInfo', ['iatv_id', 'start_time', 'stop_time'])
VIDEO_INFO_LISTS = {
'Ted Cruz': [
VideoInfo(
'CSPAN_20160316_002800_March_15_Primaries_Results_and_Speeches',
8580,... |
from sqlalchemy import desc
from flask import render_template, request
from flask_login.utils import current_user
from web.models import Pastebin
from web.public_pastebins import bp
@bp.route("/public")
def public():
page = request.args.get("page", 1, type=int)
tags = dict()
#Get last 50 pastebins
pas... |
from dataTool import DataTool, DownsamplePointCloud
import os.path as osp
import numpy as np
import torch
from PIL import Image
from multiprocessing import Process
from functools import reduce
from ...utils import master_only
from .base import LoggerHook
import wandb
from collections import OrderedDict
import inspect
... |
# -*- coding: utf-8 -*-
import numpy
import pandas
def handler(event, context):
print(numpy.zeros(1))
print(numpy.ones(1))
s = pandas.Series(numpy.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
print(s)
result = {}
return result
|
import os
import shutil
import pytest
import numpy as np
from stable_baselines3.common.logger import (make_output_format, read_csv, read_json, DEBUG, ScopedConfigure,
info, debug, set_level, configure, logkv, logkvs,
dumpkvs, lo... |
import threading
from time import sleep
N_MAX_CLIENTS_LOGGED_SIMULNANEOUSLY: int = 5
N_CLIENTS: int = 15
N_SEMAPHORE_RELEASE: int = 10 # only in python 3.9
semaphore = threading.Semaphore(value=N_MAX_CLIENTS_LOGGED_SIMULNANEOUSLY)
def client() -> None:
semaphore.acquire()
print(f'\n{threading.current_thread()... |
from fastapi import Request
from app.utils.response import JsonResponse
from app.utils.logger import logger
from pydantic import BaseModel
class Disable(BaseModel):
is_disabled : str
async def disable_account(request : Request, disable : Disable):
try:
decodeToken = request.state.payload
except... |
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2021 Ingwersen_erik
#
# 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 right... |
import time
from lh_lib.constants import RUNNING_MICROPYTHON
def ticks_ms():
if RUNNING_MICROPYTHON:
return time.ticks_ms()
# on CPython we cannot use ticks, but it is assumed fast enough to use time_ns()
# time_ns() is converted to milliseconds with rounding using only integer arithmetic
ret... |
from django.forms import EmailField
from django.core.exceptions import ValidationError
import string
import random
def isEmailAddressValid(email):
try:
EmailField().clean(email)
return True
except ValidationError:
return False
|
'''
Python mapping for the CoreGraphics framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
'''
import sys
import objc
import CoreFoundation
import Foundation
from Quartz.CoreGraphics import _metadata
from Quartz.C... |
"""
Module:
unicon.plugins.hvrp
Authors:
Miguel Botia (mibotiaf@cisco.com), Leonardo Anez (leoanez@cisco.com)
Description:
This module defines the HVRP settings to setup the unicon environment required for generic based unicon connection.
"""
from unicon.plugins.generic import GenericSettings
class Hvr... |
# Generated by Django 2.2.2 on 2019-09-10 21:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pages', '0009_auto_20190911_0029'),
]
operations = [
migrations.RenameField(
model_name='appointment',
old_name='userid',
... |
# coding: utf-8
# pylint: disable=too-many-arguments
"""Widgets for Curses-based CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tvm.tools.debug.cli import debugger_cli_common
RL = debugger_cli_common.RichLine
class NavigationHistoryItem(obje... |
# NOTE: This character encoding is exactly the same as the 05AB1E code page
# (https://github.com/Adriandmen/05AB1E/blob/master/lib/encoding.py) - Copyright (c) 2017 Adnan
# Credit for the initial code goes to Adnan (MIT: https://github.com/Adriandmen/05AB1E/blob/master/LICENSE.txt)
# The following code page consist... |
import nexradaws
import os
import shutil
import tempfile
import sys
def get_month(radar, year, month, odir):
templocation = tempfile.mkdtemp()
conn = nexradaws.NexradAwsInterface()
days = conn.get_avail_days(year, month)
fls = []
for day in days:
print('doing ', day)
# stage to tem... |
import requests
from pathlib import Path
from functools import partial
import torch.multiprocessing as mp
import zipfile, tarfile, shutil
from torchvtk.utils import pool_map
import tqdm
def download(url, target_folder):
" Downloads a file from `url` into the `target_folder`"
path = Path(target_folder)
fn =... |
import streamlit as st
st.set_page_config()
from dotenv import load_dotenv
load_dotenv()
import logging
logging.basicConfig(level=logging.INFO)
from .utils.url import get_open_alias_param
from .pages import short_url, redirect_url
def render():
open_alias = get_open_alias_param()
if open_alias is None:
... |
import re
from datetime import datetime, timedelta
from typing import List
import pytest
from django.urls import reverse
from httpretty import httpretty
from rest_framework.test import APIClient
from core.models import Artifact, ArtifactType, Camera, UserType, User, FlightState, BlockCriteria
class BaseTestViewSet:... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
class State:
def __init__(self, literals):
self.literals = literals
def __eq__(self, other):
result = set(self.literals) == set(other.literals)
return result
def __repr__(self):
return str(self.literals)
def __str__(self):
return str(self.literals)
def sat... |
import kivy
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager, CardTransition
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, ObjectProperty
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.uix.spinner import Spinner
from mazesolver.... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root: return []
nodes = [root]
... |
import bpy
from bpy_extras.mesh_utils import triangle_random_points
import bmesh
import math
from mathutils import Vector, Matrix
from mathutils.geometry import intersect_line_plane, distance_point_to_plane, intersect_point_line
from mathutils.bvhtree import BVHTree
from mathutils.noise import noise_vector, hetero_terr... |
# -*- coding: utf-8 -*-
# file: song_lyrics.py
# author: JinTian
# time: 08/03/2017 10:22 PM
# Copyright 2017 JinTian. 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
#
#... |
import copy
import logging
from .smtlib import solver, Bool
from ..utils.helpers import issymbolic
#import exceptions
from .cpu.abstractcpu import ConcretizeRegister
from .memory import ConcretizeMemory, MemoryException
from ..platforms.platform import *
logger = logging.getLogger(__name__)
class StateException(Ex... |
import io
import json
from google.auth import compute_engine
from google.oauth2 import service_account
def gcp_credentials(service_account_file):
if service_account_file:
with io.open(service_account_file, 'r', encoding='utf-8') as json_fi:
credentials_info = json.load(json_fi)
creden... |
s = float(input("Digite o seu salário atual: "))
print("O salário de {} reais sera aumentado para {} reais.".format(s, (s*1.15))) |
from . import *
from ..utils.constants import NUM_SEARCH_RESULT
def get_course_by_id(course_id):
return Course.query.filter_by(id=course_id).first()
def get_course_by_subject_and_course_num(subject_code, course_num):
return Course.query.filter_by(subject_code=subject_code, course_num=course_num).first()
de... |
import pandas as pd
df = pd.read_csv('ShibuyaUnderground.pts', header=None, sep=' ')
df.to_csv('shibuya_x.chan', header=False, index=False, columns=[0], sep = ' ')
df.to_csv('shibuya_y.chan', header=False, index=False, columns=[1], sep = ' ')
df.to_csv('shibuya_z.chan', header=False, index=False, columns=[2], sep = ' ... |
from PyQt5 import QtWidgets
import sys
class InputBox():
def __init__(self):
self.app = QtWidgets.QApplication(sys.argv)
def getText(self,text):
"""
open a text box and return the input
"""
input, done = QtWidgets.QInputDialog.getText(None, 'Input Dialog', text)
... |
import copy
import json
import collections
import ftrack_api
from openpype_modules.ftrack.lib import (
ServerAction,
statics_icon,
)
from openpype_modules.ftrack.lib.avalon_sync import create_chunks
class TransferHierarchicalValues(ServerAction):
"""Transfer values across hierarhcical attributes.
A... |
import re
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.settings import api_settings
from dmsuMarket.utils.serializers import RedisBaseSerializer
from users.models import UserModel
class UserSerializer(RedisBaseSerializer, serializers.ModelSeria... |
#!/usr/bin/env python
"""RaspiMote_https package setuptools installer."""
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
if __name__ == '__main__':
setuptools.setup(use_scm_version=True)
|
"""Hire URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-20 21:11
from __future__ import unicode_literals
from django.db import migrations
def update_states(apps, schema_editor):
"""
Update from old integer based states to the now more verbose
states
"""
Page = apps.get_model('ostinato_page... |
import numpy as np
import matplotlib.pyplot as plt
import os
import gzip
import random
random.seed(321)
def readMatrix(filename, total_length):
print "reading Rao's HiC "
infile = open(filename).readlines()
print len(infile)
HiC = np.zeros((total_length,total_length)).astype(np.int16)
percentage_fin... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import... |
import ctypes
import os
import pytest
from qcodes.instrument_drivers.AlazarTech.ATS import Buffer
from qcodes.instrument_drivers.AlazarTech.ATS import os as ats_os
pytestmark = pytest.mark.skipif(
os.name != 'nt', reason='These tests are relevant only for Windows')
def test_buffer_initiates_only_on_windows(mo... |
import numpy as np
import pandas as pd
import xarray as xr
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import os
from datetime import datetime
import geocat.viz.util as gvutil
from geocat.viz import cmaps as gvcmaps
# =... |
# This file contains unit tests
from server import app
from databaseApi import DBApi
from text_to_speech import tts
import json
import pytest
from text_to_speech import tts
@pytest.fixture
def client():
app.config['TESTING'] = True
client = app.test_client()
yield client
#Index page displa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.