content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
:mod:`dbsettings`
===========================================================================
:synopsis: default data and constants for the database
:author: Roberto Magán Carrión
:contact: roberto.magan@uca.es, rmagan@ugr.es, robertomagan@gmail.com
:organization: Un... |
def ana(t1,t2):
anas=[]
anas1={}
ana1=[]
ana2=[]
if len(t1)==len(t2):
for x in t1.lower():
ana1.append(x)
ana1.sort()
print(ana1)
for i in t2.lower():
ana2.append(i)
ana2.sort()
print(ana2)
if ana1==ana2:... |
import bs4 as bs
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
import os
import pandas as pd
import pandas_datareader.data as web
import pickle
import requests
style.use('ggplot')
### Date range
start = dt.datetime(2000,1,1)
end = dt.datetime(2016,12,31)
### Nu... |
# coding: UTF-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Config(object):
"""配置参数"""
def __init__(self, dataset, embedding):
self.model_name = 'TextRNN_Att'
self.train_path = dataset + '/data/train.txt' # 训练集
... |
import distutils.sysconfig
import os
def generate(env):
try:
cgi = os.environ['CGAL_INCLUDE']
if cgi.startswith('-I'):
cgi = cgi.lstrip('-I')
cgd = os.environ['CGAL_DIR']
if cgd.endswith('/CGAL'):
cgd = cgd.rstrip('/CGAL')
if cgd:
env.Ap... |
from repository.solution import *
class SolutionService:
@classmethod
def get_codis_filtered_gender(self, gender):
return get_styles_gender(gender)
|
import sys
import pytest
try:
from abc import ABC
except ImportError:
from abc import ABCMeta
class ABC:
__metaclass__ = ABCMeta
from pyfields import autofields, field, copy_value, autoclass
@pytest.mark.skipif(sys.version_info < (3,), reason="This test does not yet reproduce the exception in... |
'''
1.创建三个函数,分别的功能是, 求得斐波那契数列的第n项, 求n的阶乘,求n的前n项和
请比较三个函数单线程分别调用,和三个函数多线程并发的效率(相差多长时间)
假定n的值是15
'''
from time import sleep,ctime
import threading
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
def getfibo(n):
sleep(2)
print(fibo(n), ctime())
def jiecheng(n):
if ... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
from typing import List, Tuple
import numpy as np
INPUT_MASK = np.ndarray
TRUTH_TABLE = np.ndarray
NODE_NAME = str
CONTROL_FLAG = bool
PBN_DATA = List[Tuple[INPUT_MASK, TRUTH_TABLE, NODE_NAME, CONTROL_FLAG]]
LOGIC_FUNC = List[Tuple[str, float]]
LOGIC_FUNC_DATA = Tuple[List[NODE_NAME], List[LOGIC_FUNC]]
... |
class InvalidSubcommand(Exception):
def __init__(self,subcommand_invalid):
self.message = f"""❗ This subcommand `{subcommand_invalid}` is not exist !
Please look the [wiki](https://github.com/NaulaN/Escarbot-py/wiki/Commandes) or execute this command -> `!help` or `/help` for a fast documentation."... |
from setuptools import setup
setup(name='DescribeLinearModel',
version='1.0.1',
description='class for calculating and visualizing a regression line',
author='Eugen Iftimoaie',
packages=['DescribeLinearModel'],
setup_cfg=True,
zip_safe=False)
|
import unittest
import mock
from jira import JIRA
from cloudimized.core.jiranotifier import configure_jiranotifier, JiraNotifier, JiraNotifierError, logger
from cloudimized.gitcore.gitchange import GitChange
class JiraNotifierTestCase(unittest.TestCase):
def setUp(self) -> None:
kwargs = {"test_field": ... |
import numpy as np
from torch.nn import functional as F
import torch as t
from torch import nn
from model.utils.bbox_tools import generate_anchor_base
from model.utils.creator_tool import ProposalCreator
class RegionProposalNetwork(nn.Module):
def __init__(self, in_channels=512, mid_channels=512, ratio... |
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1, bias=False):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=bias)
def conv1x1(in_planes, out_planes, stride=1, bias=False):
return nn.Conv2d(in_planes,... |
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2019, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
"""
Description: Servo cartesian
"""
import os
import sys
import time
import datetime
sys.path.append(os.path.join(os.path.... |
BATCH_LIMIT = 100
DEFAULT_LOCALE = "en_US"
|
from agents import Direction
def test_move_forward():
d = Direction("up")
l1 = d.move_forward((0,0))
assert l1 == (0,-1)
d = Direction(Direction.R)
l1 = d.move_forward((0,0))
assert l1 == (1,0)
d = Direction(Direction.D)
l1 = d.move_forward((0,0))
assert l1 == (0,1)
d = Directio... |
#!/usr/bin/python
# Copyright (c) 2015 Mirantis, 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... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from control import Control
from rectangle import Rectangle
from objects import NONE, HORIZONTAL, VERTICAL
class Separator(Rectangle):
"""This class represents a box separator"""
def __init__(self):
Rectangle.__init__(self)
self.hidden = F... |
"""
Given two strings A and B, return whether or not A can be shifted some number of times to get B.
Example;
if A is 'abcde' and B is 'cdeab' return true
"""
def is_possible(source: str, target: str) -> bool:
if not source and not target:
return True
if not source or not target:
return Fa... |
class Design(object):
def __init__(self, top_name):
self.top_name = top_name
self.lib_name = "gscl45nm"
self.rtl_file = "gcd.v"
#self.hdl_path = "./design/gcd/hdl"
#self.lib_path = "./design/lib"
self.mmmc_file = "flow.view"
self.lef_file = "gscl45nm... |
#!/usr/bin/env python
"""Test utilities for RELDB-related testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import functools
import sys
import mock
from grr_response_core.lib.util import compatibility
from grr_response_server import data_store
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
self.l1=l1
self.l2=l2
summ=self.l1.val + self.l2.val
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Classifier(nn.Module):
def __init__(self):
super(Classifier, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=8, kernel_size=5, stride=4)
self.conv2 = nn.Conv2d(in_channels=8, out_channels=16, kerne... |
from artm.scores import (
BaseScore as BaseArtmScore,
PerplexityScore as ArtmPerplexityScore,
)
from typing import List
from .base_default_score import BaseDefaultScore
class PerplexityScore(BaseDefaultScore):
def __init__(self, name: str, class_ids: List[str] = None):
super().__init__(name, high... |
"""Day 1: Report Repair"""
from typing import Tuple
import numpy as np
def read(file_: "str") -> "np.array":
"""Read data from file."""
return np.genfromtxt(file_, dtype="int")
def find_two_entries(data: "np.array") -> Tuple["int", "int"]:
"""Check array for the two entries that sum to 2020."""
fo... |
from django.urls import path
from . import views
urlpatterns = [
path('accounts/login/', views.login, name='login'),
path('accounts/logout/', views.logout, name='logout'),
] |
from intermol.decorators import *
from abstract_bond import *
class HarmonicPotential(AbstractBond):
@accepts_compatible_units(None, None, units.nanometers, units.kilojoules_per_mole * units.nanometers**(-2))
def __init__(self, atom1, atom2, length, k):
"""
"""
AbstractBond.__init__(se... |
import requests
import json
import warnings
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
from .const import mist_login_url, mist_logout_url, mist_timeout_connection, mist_timeout_getpost, mist_sessionid_cookie, \
mist_csrftoken_cookie, mist_login_headers, mist_login_body, mist_cookie_header... |
import sys
from datetime import datetime, timedelta
# for plotting
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
# gitply imports
from maps import NullUserMap, FileUserMap
from core import GitCLIBackend, GitlabBackend
from core.utils import weeks_in_year
def ... |
# Copyright (C) 2018 Igalia S.L.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.... |
from distutils.core import setup
long_description = """
BDT
===
This is a simple library to implement Binary decision Trees.
In computer science, a binary decision diagram (BDD) or branching
program is a data structure that is used to represent a Boolean
function. On a more abstract level, BDDs can be considered as... |
import collections
doubleEndedQueue = collections.deque('123456')
print(f'Q: {doubleEndedQueue}') # deque(['1', '2', '3', '4', '5', '6'])
for item in doubleEndedQueue:
print(f'Item: {item}')
print(f'Left: {doubleEndedQueue[0]}') # 1
print(f'Middle: {doubleEndedQueue[3]}') # 4
print(f'Right: {doubleEndedQueue[... |
# -*- coding: utf-8 -*-
""" Utilities providing new custom assertions to support unit tests.
"""
from nose.tools import assert_false, assert_true
from app_common.traits.has_traits_utils import is_has_traits_almost_equal, \
is_val_almost_equal
def assert_has_traits_almost_equal(obj1, obj2, **kwargs):
""" Comp... |
"""Methods and classes for storing and manipulating the global
geometry of the physical problem.
"""
import numpy as np
from pydft.base import testmode
cell = None
"""Cell: default geometry to use globally throughout the code when no other
geometry is explicitly specified.
"""
def get_cell(cell_=None):
"""Returns t... |
#!/usr/bin/python
#coding:utf8
from algorithms.common.sortbase import Key, IntNode, SortBase
class BubbleSort(SortBase):
@staticmethod
def sort(a):
length = len(a)
for i in range(length):
flag = True
for j in range(length - i - 1):
if SortBase.less(a[j+... |
from django.test import TestCase
from pricefinderapp.models import Currency, Store
class SetupTests(TestCase):
def setUp(self):
self.currency = Currency.objects.create(name='AUD')
def test_str(self):
store = Store.objects.create(name='Woolworths', currency=self.currency)
self.assert... |
valid = 0
invalid = 0
with open("input", "r") as file:
for row in file.readlines():
parts = row.split(':')
password = parts[1][1:]
ruleParts = parts[0].split(' ')
ruleRange = ruleParts[0]
ruleStr = ruleParts[1]
ruleMin = int(ruleRange.split('-')[0])
ruleMax... |
"""
Imports for bottle
"""
import argparse
import bottle
from bottle import request, run, static_file
"""
Imports for API
"""
import tensorflow as tf
from db import get_model, new_model, save_model, delete_model, clear_thread_cache
from keras.backend.tensorflow_backend import clear_session
from model import ModelStatus... |
# Generated by Django 2.2.9 on 2020-01-14 18:41
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),
('mpdb_api', '0006_auto_20... |
name->Seven 0
name->Seven 1
name->Seven 2
|
from .reporting import generate_report
__all__ = [generate_report]
|
""" Script used to generate ncbi_subset_tax.json
NCBI taxonomy downloaded in 2019 July 1st.
"""
from taxonomy import Taxonomy
tax = Taxonomy.from_ncbi("nodes.dmp", "names.dmp")
new_tax = tax.prune(remove=['28384', '12908', '10239', '2', '2157'] + [t for t in tax.children("2759") if t != "543769"])
with open("new_ta... |
version = "4.3.5"
|
# Generated by Django 3.0.8 on 2020-07-22 15:03
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coder', '0011_question_iscorrect'),
]
operations = [
migrations.AlterField(
model_name='question',
na... |
#!/usr/bin/env python
import rospy
import socket
from std_msgs.msg import String
from time import sleep, strftime
from datetime import datetime
from lcdbackpack import LcdBackpack
# Initialize LCD (must specify pinout and dimensions)
#lcd = Adafruit_CharLCD(rs=26, en=19,
# d4=13, d5=6, d6=5, d... |
import logging
import random
import shutil
import copy
import os, subprocess
from pylons import config, request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from webenmr.lib.base import *
from mimetypes import guess_type
import fileinput
import os
import sys
import shut... |
from app import db
class Entry(db.Model):
id = db.Column(db.String(20), primary_key=True)
tweet = db.Column(db.String(1000), nullable=False)
url = db.Column(db.String(500))
sarcasm = db.Column(db.Boolean)
relevant = db.Column(db.Boolean, default=False)
sentiment = db.Column(db.Integer, default=... |
import sys
import shlex
import pysam
import subprocess
import multiprocessing
import os
def is_nonempty_file(path):
return os.path.isfile(path) and os.path.getsize(path)
def submit_mdist(tup):
ss, ks, sketchfns, ofn = tup
subprocess.check_call("mash dist -p 1 %s > %s" %
(" ".jo... |
DB_SETTINGS = {
"db_name": "surfaces",
"host": "localhost",
"user": "science",
"password": "posgres",
"port": 5432
}
GENERATION_TRIES = 1000
DOTS_COUNT = 10
DEVIATION = 0.2 # ДОПУСК - стандартное отклонение
MU = 0 # Математической ожидание
SIGMA = 0.2 / 6 # Сигма, берем 6*сигма как в маш-нии
|
#
# PySNMP MIB module VERILINK-ENTERPRISE-NCMGENERIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VERILINK-ENTERPRISE-NCMGENERIC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:26:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... |
import logging
import itertools
import numpy as np
from scipy.optimize import OptimizeResult, minimize_scalar
import scipy.constants
from .util import find_vertex_x_of_positive_parabola
def scalar_discrete_gap_filling_minimizer(
fun, bracket, args=(), tol=1.0, maxfev=None, maxiter=100, callback=None, verbos... |
"""Module containing the project's exceptions."""
class DutyFailure(Exception): # noqa: N818
"""An exception raised when a duty fails."""
def __init__(self, code: int):
"""
Initialize the object.
Arguments:
code: The exit code of a command.
"""
super().__... |
from ctypes import (
sizeof,
c_bool,
c_uint8,
c_int64,
c_double,
c_char,
Structure,
)
from volpe_types import int1, int64, flt64, char, VolpeObject, VolpeClosure, VolpeArray, unwrap
from target import target_data
ENCODING = "ascii"
DEBUG_BUFFER = False
def get_repr(val):
if hasattr(v... |
x=set()
y=set()
include=[]
for i in range(8):
a,b=map(int,input().split())
include.append((a,b))
x.add(a)
y.add(b)
flag=1
if len(x)!=3 or len(y)!=3:
flag=0
else:
notinclude=[]
x=sorted(x)
y=sorted(y)
for i in x:
for j in y:
if (i,j) not in include:
... |
key_a = 0x04
key_b = 0x05
key_c = 0x06
key_d = 0x07
key_e = 0x08
key_f = 0x09
key_g = 0x0A
key_h = 0x0B
key_i = 0x0C
key_j = 0x0D
key_k = 0x0E
key_l = 0x0F
key_m = 0x10
key_n = 0x11
key_o = 0x12
key_p = 0x13
key_q = 0x14
key_r = 0x15
key_s = 0x16
key_t = 0x17
key_u = 0x18
key_v = 0x19
key_w = 0x1A
key_x = 0x1B
key_y = ... |
from .Speech import *
from .Lighting import *
from .Head import *
from .Lift import *
|
fixo = {}
outro = {}
rendimentos = {}
def gastoFixo():
print("\n------------------------------------")
nome = input("ENTER --> Menu Inicial\n\nNome do gasto: ")
while(nome != ""):
valor = float(input("Valor do gasto: R$"))
fixo[nome] = valor
if entrada() - (saidaFixo() + sai... |
import torch
"""
Custom collate function.
We need to reorder the batch based on lengths of the sentences.
Since pytorch requires an ordered tensor for the lstm.
lengths, sort_id = torch.Tensor([x for x in lengths]).sort(descending=True)
"""
def custom_collate(batch):
output = {k: [] for k in batc... |
#ISR performance auto tester by micro:bit
#features:
# use user-defined waveform to test controller ISR performance
# user select target_cnt and delay parameters
#test case: OpenCR
#Usage:
# button_a pressed to start test, test pass show "1", fail show "0"
# FS - microbit(P0) - EXTI_0( 0: Arduino PIN 2, EXTI_... |
from typing import List
class PagedQueryResult:
offset: int
limit: int
count: int
total: int
results: List
# facets - Object containing FacetResults - Optional
def __init__(self, offset: int, limit: int, count: int, total: int, results: List, facets=None):
self.offset = offset
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-11-04 07:58
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... |
#!/usr/bin/python
""" The example of using xmpppy's Ad-Hoc Commands (JEP-0050) implementation.
"""
import xmpp
from xmpp.protocol import *
options = {
'JID': 'circles@example.com',
'Password': '********',
}
class TestCommand(xmpp.commands.Command_Handler_Prototype):
""" Example class. You should read source if you... |
from django.shortcuts import render
from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate, login, logout
from django.views.generic import View, ListView, DetailView,TemplateView
from django.urls import reverse
from django.http import HttpResponseRedirect,HttpRequest, HttpRes... |
# -*- coding: utf-8 -*-
import scrapy
import json
class AlibabaSpider(scrapy.Spider):
name = 'alibaba'
allowed_domains = ['job.alibaba.com']
start_urls = ['http://job.alibaba.com/']
positionUrl = 'https://job.alibaba.com/zhaopin/socialPositionList/doList.json'
totalPage = 0
pageIndex = 1
... |
import os
import numpy as np
import cv2
import sys
import math
import utils
from utils.attack import setup_attack_graph, get_adv_target, get_print_triplets
from utils.model import YadavModel
from utils.dataproc import read_img, preprocess_yadav, write_img
from utils.eval import top3_as_string
import tensorflow as tf... |
# main
import argparse
import re
import numpy as np
from collections import Counter
from progress.bar import Bar
# local imports
import get_meta
import gen_stats
import gen_pure_star
def main():
# parse arguments
parser = argparse.ArgumentParser(description='Analyze conformational compositions of protei... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Multipletau provides a multiple-τ algorithm for Python 2.7 and
Python 3.x with :py:mod:`numpy` as its sole dependency.
Multiple-τ correlation is computed on a logarithmic scale (less
data points are computed) and is thus much faster than conventional
correlation on a ... |
from tkinter import *
from tkinter.simpledialog import *
from tkinter.filedialog import *
import csv
import json
import os
import os.path
import xlrd
import xlwt
import sqlite3
import pymysql
import glob
import numpy as np
import tensorflow as tf
from sklearn import svm, metrics
from sklearn.model_selection import trai... |
# -*- coding: utf-8 -*-
import os
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import Ten... |
#import du module
#variables couleurs
couleurs ={
"cyan" : (51, 255, 255) ,
"rouge" : ( 255, 0, 0) ,
"vert" : ( 0, 255, 0) ,
"bleu" : ( 0, 0, 255) ,
"noir" : (0 , 0, 0) ,
"blanc" : (255, 255, 255)
}
|
# proxy module
from traitsui.wx.enum_editor import *
|
from libddog.dashboards import HLayout, Note, NotePreset
from libddog.dashboards.layouts import HLayoutStack, HLayoutWrapping
def test_hlayoutstack__one_layer() -> None:
# two widgets in a single row
fst = Note(content="this is a note")
snd = Note(content="this is another note")
stack = HLayoutStack(... |
#!/usr/bin/env python
#pylint: disable=E1101,E1103,C0103,R0902
"""
DefaultConfig.py
Sample configuration for generating workflow.
"""
import os
try:
import cPickle as pickle
except ImportError:
import pickle
from WMCore.Agent.Configuration import Configuration
config = Configuration()
config.section_('G... |
import os
from core.utils.strings import snake_casify
def import_classes(package_name, class_names):
package = __import__(package_name, fromlist=class_names)
return [getattr(getattr(package, class_name), class_name) for class_name in class_names]
def get_file_names(main_dir, path):
abspath = os.path.join(... |
## this script helps to copy misclassified images to another folder
# which allows a better overfiew on the images
# as an imput it takes the printed output of the retrain.py
import argparse
import os
import shutil
def process(misfile, outdir):
with open(misfile) as f:
lines = f.readlines()
for line ... |
from libcloud.common.exceptions import BaseHTTPError
from libcloud.common.types import InvalidCredsError
from requests.exceptions import RequestException
from cloudie import cli
from .helpers import ClickTestCase
class TestGroup(ClickTestCase):
def test_not_implemented(self) -> None:
@cli.cli.command()
... |
import re
from django import template
from django.template.defaultfilters import stringfilter, force_escape
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.models import ContentType
from annotatetext.models import Annotation
from annotatetext.forms import NewAnnotationForm
register = t... |
import tkinter as tk
from pathlib import Path
class AmountSelector(tk.Frame):
def __init__(self, parent, item):
super().__init__(parent)
self.minus_image = tk.PhotoImage(file = ".\images\minus.png")
self.plus_image = tk.PhotoImage(file = ".\images\plus.png")
self.item = item
... |
from poker import getDeck
number = [2,3,4,5,6,7,8,9,10]
deck1 = getDeck(number)
def player(name):
name = name
card = deck1[0:17]
del deck1[0:17]
return {"name": name, "card":card}
# def isLord(player):
# if(deck1 == []):
# return False
# for i in range(3,10,1):
# count = 0
# ... |
# using line_profiler to test
# kernprof -l test_primes.py
# python3 -m line_profiler test_primes.py.lprof
import itertools
@profile # come from line_profiler
def primes():
n = 2
primes = set()
while True:
for p in primes:
if n % p == 0:
break
else:
... |
# -*- coding: utf-8 -*-
import scrapy
class ToScrapeSpiderXPath(scrapy.Spider):
name = 'toscrape-xpath'
start_urls = [
'https://twitter.com/GeertReyniers',
]
def parse(self, response):
User = response.xpath("//div[@class='ProfileHeaderCard']")
yield {
'URL ':User.x... |
#!/usr/bin/env python
# Copyright 2021 Alibaba Group Holding Limited. 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
... |
"""
Summary
-------
Simulate multiple periods of ordering and sales for a dual sourcing inventory problem.
"""
import numpy as np
import scipy.stats as scs
from base import Model, Problem
class DualSourcing(Model):
"""
A model that simulates multiple periods of ordering and sales for a single-staged,
dua... |
#!/usr/bin/env python2
#
# vim: ts=4 sw=4 nowrap
#
# ChannelHandler
# ReceiveChannel
# SendChannel
#
# SocketDispatcher
# Loop
# Poll
# ReadEvent
# WriteEvent
#
import sys, re, time, thread, os
import getopt
import exceptions
import select
import string
import socket
import StringIO
import traceback
from ... |
from dash import Dash, html, Output, Input
import dash_mantine_components as dmc
from time import sleep
def test_accordion_simple(dash_duo):
app = Dash()
app.layout = html.Div(
[
dmc.Accordion(
children=[
dmc.AccordionItem(
childr... |
import torch
import torch.nn as nn
import torch.nn.functional as torchfunc
from robo_rl.common.utils.nn_utils import no_activation
from torch.distributions.categorical import Categorical
class LinearNetwork(nn.Module):
def __init__(self, layers_size, final_layer_function, activation_function, is_layer_norm=False... |
from search_master import SearchMaster
import requests
import bs4
class Craiglist(SearchMaster):
def __init__(self, urls, s3_filename, slack_token):
super().__init__(urls, s3_filename, slack_token)
def pull_results(self, urls):
results = []
for url in urls:
try:
... |
from selenium import webdriver
import time
import sys
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
dr... |
#!/usr/bin/env python
from binyard.etcetera import input_until_correct
import matplotlib
import numpy as np
from numpy import loadtxt
import re
#gui_envs = ['GTKAgg','TKAgg','Qt4Agg','WXAgg']
#for gui in gui_envs:
# try:
# matplotlib.use(gui,warn=False, force=True)
# from matplotlib import pyplot as ... |
#appliable for grep,sed,sort,readelf
import sys,os
from pathlib import Path
WORKDIR=sys.argv[1]+'/'
KEYWORD=sys.argv[2]
Path(WORKDIR+'dfg/bak').mkdir(parents=True, exist_ok=True)
for x in os.listdir(WORKDIR+'/dfg'):
if not os.path.isfile(WORKDIR+'/dfg/'+x):continue
if x.endswith('run.log'):
xx=open(WORKDIR... |
'''
A window with a unicode textfield where the user can e.g. edit
the contents of an article
'''
#
# (C) Rob W.W. Hooft, 2003
# (C) Daniel Herding, 2004
# Wikiwichtel
# (C) the PyWikipediabot team, 2008-2010
#
# Distributed under the terms of the MIT license.
#
__version__='$Id$'
from Tkinter import *
from Scrol... |
from __future__ import annotations
import logging
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List, Optional, Dict, TYPE_CHECKING
if TYPE_CHECKING:
from framework.lane_keeping_test.test_protocol import Snapshot
@dataclass
class Location:
"""Hilfsklass... |
# 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... |
"""
####################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : multi_recog_seq_head.py
# Abstract : Recognize text in a batch.
# Current Version: ... |
import os
import sys
import traceback
import subprocess
import json
from kafka import KafkaProducer, KafkaConsumer, TopicPartition
import logging
import logstash
import codecs
import requests
import time
from flask import Flask, request, jsonify
from config import config
app = Flask(__name__)
# logging
logger = logg... |
import time
import random
import csv
import pandas as pd
import numpy as np
import gym
from stable_baselines3 import PPO
from stable_baselines3.ppo import MlpPolicy
from stable_baselines3.common.callbacks import EvalCallback
from gym import spaces, ObservationWrapper, RewardWrapper, ActionWrapper
import matplotlib.pypl... |
from contextlib import contextmanager
@contextmanager
def opened(filename, mode="r"):
f = open(filename, mode)
try:
yield f
finally:
f.close()
with opened("toss_coins.py") as f:
for line in f:
print(line.strip())
|
"""
A set of tests for using the QCEngine project
"""
import numpy as np
import json, os, shutil
from . import addons
import geometric
import pytest
localizer = addons.in_folder
@addons.using_qcengine
@addons.using_rdkit
def test_run_json_rdkit_water(localizer):
# create a test input json file
qc_schema_inpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.