content
stringlengths
0
894k
type
stringclasses
2 values
from rest_framework import serializers from .models import * class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'workspace', 'assigned_to', 'priority', 'task_status', 'description', 'planned_start_date', 'planned_end_date', 'file'] class WorkSpa...
python
import json import random from django.utils.safestring import SafeString # debug ''' 1. Step 1: Put your libraries in the same directory as views.py 2. Step 2: Import your libraries here with a '.' ''' from .completeness_class import * from .outlier import * from .IntegrateFunction import * from dashboard.forms impo...
python
""" Released under the MIT-license: Copyright (c) 2010 Earl Marcus 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, modif...
python
""" argparse interface """ from argparse import ArgumentParser as _Parser from argparse import ArgumentDefaultsHelpFormatter as _HelpFormatter def parser(cmd_str, arg_lst): """ an argparse parser object :param cmd_str: the command string :type cmd_str: str :param arg_lst: args and kwargs for Argument...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 27 13:40:04 2017 @author: DangoMelon0701 """ import numpy as np class Funciones(object): def __init__(self,nombre,apellido,edad): self.name = nombre self.lastname = apellido self.age = edad def puto(self): ...
python
from .base_classes import Attack from .closest_distance import ClosestDistanceAttack from .direct_linkage import DirectLinkage from .groundhog import Groundhog from .utils import load_attack
python
from django.shortcuts import render,redirect from oauth_backend import OauthBackend from django.http import HttpResponse, HttpResponseForbidden from django.http import Http404 from django.utils.crypto import get_random_string from django.conf import settings from django.contrib.auth import authenticate, login from tuke...
python
from pyramid.view import view_defaults from pyramid.response import Response from pyramid.httpexceptions import HTTPOk from pyramid.httpexceptions import HTTPNotFound, HTTPInternalServerError from .. catalog import install_package from .. logger import getLogger logger = getLogger(__name__) @view_defaults(route_na...
python
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec from sklearn.metrics import accuracy_score # Plot some details about the dataset and show some example points def showDatasetExamples(xTrain, yTrain, xTest, yTest): fig = plt.figure(figsize=(6, 6)) fig.ca...
python
from rest_framework.serializers import ModelSerializer from backend.models import Video, Like class VideoCreateSerializer(ModelSerializer): class Meta: model = Video fields = [ 'id', 'owner', 'video_bucket_id', 'title', 'description', ...
python
import aiml from django.shortcuts import render, redirect kernel = aiml.Kernel() kernel.learn("./botbrains/*.aiml") kernel.saveBrain("siabrain.brn") def index(request): text = "" textreply = "" text = chat.text textreply = kernel.respond(str(text)) if textreply is not None: return render...
python
import falcon.asgi from .api.tilt_resource import * # swagger ui - NO ASGI SUPPORT YET #from falcon_swagger_ui import register_swaggerui_app # register swagger ui - NO ASGI SUPPORT YET #register_swaggerui_app(api, SWAGGERUI_URL, SCHEMA_URL, page_title=PAGE_TITLE, #favicon_url=FAVICON_URL, # config={'supported...
python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data def mlp_model(x, n_input, n_hidden_1, n_hidden_2, n_class): weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Va...
python
#encoding:utf-8 import word_util import numpy as np import codecs def transform_wordseq_to_phrase_weighted(word_seq,word2vec_map,word_weighted_value = None,word_keys = None): phrase_distributed = np.zeros(256) word_freq = {} for word in word_seq: #print("0") if not word_keys: if ...
python
#!/usr/bin/env python3 import contextlib import sys from pathlib import Path from typing import List, Type import pytest from qemu import QemuVm, VmImage, spawn_qemu from nix import notos_image, busybox_image from root import TEST_ROOT from vmsh import spawn_vmsh_command, VmshPopen sys.path.append(str(TEST_ROOT.pare...
python
# -*- coding: utf-8 -*- """ SPARQL Wrapper exceptions @authors: U{Ivan Herman<http://www.ivan-herman.net>}, U{Sergio Fernández<http://www.wikier.org>}, U{Carlos Tejo Alonso<http://www.dayures.net>} @organization: U{World Wide Web Consortium<http://www.w3.org>} and U{Foundation CTIC<http://www.fundacionctic.org/>}. @...
python
import warnings from otp.ai.passlib.tests.test_crypto_builtin_md4 import _Common_MD4_Test __all__ = [ 'Legacy_MD4_Test'] class Legacy_MD4_Test(_Common_MD4_Test): descriptionPrefix = 'passlib.utils.md4.md4()' def setUp(self): super(Legacy_MD4_Test, self).setUp() warnings.filterwarnings('ignore...
python
""" leetcode 15 Three Sum """ from typing import List """ simple solution T: O(N^3) S: O(1) result: time out """ def threeSum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] for i in range(len(nums) - 2): for j in range(i, len(nums) - 1): for k in rang...
python
# This file was auto generated; Do not modify, if you value your sanity! import ctypes try: # 3 from can_settings import can_settings from canfd_settings import canfd_settings from s_text_api_settings import s_text_api_settings except: from ics.structures.can_settings import can_settings from ics.s...
python
class Grid: """ Creates a 2D array specified by row and column """ def __init__(self, X_SIZE, Y_SIZE, item=""): self.x_size = X_SIZE self.y_size = Y_SIZE self._grid = [[item for x in range(X_SIZE)] for y in range(Y_SIZE)] def __len__(self): re...
python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head dummy = List...
python
import os import sys import csv import json OUTPUT_FORMATS = ('csv', 'json', 'yara', 'autofocus') def getHandler(output_format): output_format = output_format.lower() if output_format not in OUTPUT_FORMATS: print("[WARNING] Invalid output format specified.. using CSV") output_format = 'csv' ...
python
# CONVERSION OF LINKED LIST TO ARRAY class Node: def __init__(self, value): self.value = value self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def add_last(self, value): temp = Node(value) if self.head==Non...
python
from dataclasses import dataclass, field from typing import List, Any, Optional @dataclass() class Type: """ Abstract base representation of a data type. All intermediate representations of data types will either be instances of Type, or instances of subclasses of Type. All scalar data types are insta...
python
# -*- coding: utf-8 -*- # Created by crazyX on 2018/7/7 from ojcrawler.crawlers.poj import POJ from ojcrawler.crawlers.hdu import HDU from ojcrawler.crawlers.codeforces import Codeforces supports = { 'poj': POJ, 'hdu': HDU, 'codeforces': Codeforces, }
python
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = u"David Pärsson" __copyright__ = u"Copyright 2015, David Pärsson" __license__ = "MIT" __version__ = "1.0.0" __status__ = "Development" import re import sys import argparse def renumber(input_filename, output_filename): with open(input_filename, 'r') as ...
python
# Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the S...
python
#!/usr/bin/env python import scapy.all as scapy from mac_vendor_lookup import MacLookup #for printing arguments help and available options for users import optparse # for coloring the terminal from termcolor import cprint, colored import subprocess import socket # For detecting the OS the script is w...
python
import os import numpy as np # Precursor charges and m/z's considered. mz_interval = 1 charges, mzs = (2, 3), np.arange(50, 2501, mz_interval) # Spectrum preprocessing. min_peaks = 5 min_mz_range = 250. min_mz, max_mz = 101., 1500. remove_precursor_tolerance = 0.5 min_intensity = 0.01 max_peaks_used = 50 scaling = ...
python
from discord.ext import commands import discord import pymongo from codecs import open from cogs.utils import Defaults, Checks, OsuUtils class Vote(commands.Cog): def __init__(self, bot): self.bot = bot self.db_users = pymongo.MongoClient(bot.database)['osu-top-players-voting']['users'] @Ch...
python
from unittest import TestCase import pytest from hubblestack.audit import util from collections import defaultdict from hubblestack.exceptions import ArgumentValueError, HubbleCheckValidationError class TestProcess(): """ Class used to test the functions in ``process.py`` """ def test__compare_raise...
python
import numpy as np def digest_indices(indices): if type(indices)==str: if indices in ['all', 'All', 'ALL']: indices = 'all' else: raise ValueError() elif type(indices) in [int, np.int64, np.int]: indices = np.array([indices], dtype='int64') elif hasattr(indi...
python
# -*- coding: utf-8 -*- # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for SDK stages.""" from __future__ import print_function import json import os import unittest import six fro...
python
from app.core.exceptions import BaseException class ValidationError(BaseException): def __init__(self, error_message): self.error_message = error_message super(BaseException, self).__init__(error_message) class AuthenticationError(BaseException): def __init__(self, error_message): se...
python
#!/usr/bin/env python # Django environment setup: from django.conf import settings, global_settings as default_settings from django.core.management import call_command from os.path import dirname, realpath, join import sys # Detect location and available modules module_root = dirname(realpath(__file__)) # Inline set...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: test_async :Synopsis: :Author: servilla :Created: 4/22/21 """ import asyncio from datetime import datetime import re from typing import List import daiquiri import pendulum from soh.config import Config import soh.asserts.server from soh.server.serve...
python
# Calculates heatwaves using Nairn's methodology # Nairn et al. (2009). Defining and predicting Excessive Heat events, a National System import numpy as np # Defines runing mean functions: def moving_average_3(x, N=3): return np.convolve(x, np.ones((N,))/N)[(N-1):] def moving_average_30(x, N=30): return np...
python
#!/usr/bin/env python2.7 import os def system_dependency(name): print "installing system dependency {}".format(name) os.system('sudo apt-get install %s' % name) print "done!"
python
import sys import os import shutil import re import glob import struct import math import collections import argparse import csv from lib import csv_classes fpath=os.path.realpath(__file__) py_path=os.path.dirname(fpath) endian = "little" pack_int = '<i' INT_BYTES=4 STR_BYTES=20 def parseError(error_string, line, i...
python
# -*- coding: utf-8 -*- """ Import Modules Configure the Database Instantiate Classes """ if settings.get_L10n_languages_readonly(): # Make the Language files read-only for improved performance T.is_writable = False get_vars = request.get_vars # Are we running in debug mode? settings.check_debug...
python
from __future__ import annotations import numpy as np from nn_recipe.NN.ActivationFunctions.__factory import ActivationFunctionFactory from nn_recipe.NN.Layers.__layer import Layer from nn_recipe.NN.__function import Function class Linear(Layer): """ This Class represents a Linear Layer (Dense - Fully connec...
python
{ 'targets': [ { 'target_name': 'binding', 'includes': [ 'deps/snappy/common.gypi' ], 'include_dirs': [ '<!(node -e "require(\'nan\')")', 'deps/snappy/<(os_include)' ], 'dependencies': [ 'deps/snappy/snappy.gyp:snappy' ], 'sources': [ 'src/binding.cc' ] } ] }
python
import numpy as np import math import matplotlib.pyplot as plt from sklearn import metrics import argparse from functools import partial def distance_from_unif(samples, test='ks'): sorted_samples = np.sort(samples, axis=1) try: assert (np.greater_equal(sorted_samples, 0)).all(), np.min(sorted_samples) ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayUserElectronicidUserbarcodeCreateModel(object): def __init__(self): self._cert_id = None self._expire_time = None @property def cert_id(self): return self._...
python
# coding=utf-8 import time, json, io, datetime, argparse item_type = ('EVENT', 'INFO', 'AD') categories = ('pregon', 'music', 'food', 'sport', 'art', 'fire', 'band') places = { 'Alameda':(41.903501, -8.866704), 'Auditorio de San Bieito':(41.899915, -8.873203), 'A Cruzada':(41.897817, -8.874520), 'As...
python
raise NotImplementedError("ast is not yet implemented in Skulpt")
python
import pylab as PL x0 = 0.1 samplingStartTime = 1000 sampleNumber = 100 resultA = [] resultX = [] r = 0 da = 0.005 def f(x): return r * x * (1 - x) while r <= 4.0: x = x0 for t in range(samplingStartTime): x = f(x) for t in range(sampleNumber): x = f(x) resultA.append(r) ...
python
from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.core.urlresolvers import reverse from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_pro...
python
import numpy as np import pandas as pd from EstimatorSpectrum import TSVD from Generator import LSW from SVD import LordWillisSpektor from test_functions import kernel_transformed, BIMODAL, BETA, SMLA, SMLB replications = 10 size = [2000, 10000, 1000000] max_size = 100 functions = [BETA] functions_name = ['BETA'] tau...
python
# Futu Algo: Algorithmic High-Frequency Trading Framework # Copyright (c) billpwchan - All Rights Reserved # Unauthorized copying of this file, via any medium is strictly prohibited # Proprietary and confidential # Written by Bill Chan <billpwchan@hotmail.com>, 2021 import argparse import importlib from multipro...
python
def binarySearch(array,l,r,x): while l <=r: mid = l + (r-1)//2 if array[mid] == x: return mid elif array[mid] > x: r = mid-1 else: l = mid +1 return -1 array = [2,4,5,6,7,9,10,23,53] item = 23 result = binarySearch(array, 0, len(array)-1...
python
__title__ = "playground" __author__ = "murlux" __copyright__ = "Copyright 2019, " + __author__ __credits__ = (__author__, ) __license__ = "MIT" __email__ = "murlux@protonmail.com" from logging import Logger from typing import Dict from playground.util import setup_logger class SimulationIntegrator: """ Main ...
python
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
python
import gym from garage.baselines import LinearFeatureBaseline from garage.theano.baselines import GaussianMLPBaseline from garage.baselines import ZeroBaseline from garage.envs import normalize from garage.envs.box2d import CartpoleEnv from garage.envs.mujoco import SwimmerEnv from garage.theano.algos.capg_corrected im...
python
#!/usr/bin/env python3 import os import sys import glob import shutil import subprocess from re import search def remove_dir(dir_path): try: if os.path.isdir(dir_path): shutil.rmtree(dir_path) except OSError as e: print("Failed removing {}: {}".format(dir_path, e)) else: ...
python
import argparse __all__ = ('arg_parser') arg_parser = argparse.ArgumentParser(description='Converts JSON files to HTML files') arg_parser.add_argument('source', type=str, action='store', help='Source JSON file') arg_parser.add_argument('--dest', type=str, action='store', help='Output HTML filename', default=None, des...
python
import pickle import json import argparse import string import os from zhon import hanzi from collections import namedtuple import nltk def makedir(root): if not os.path.exists(root): os.makedirs(root) def write_json(data, root): with open(root, 'w') as f: json.dump(data, f) ImageMetaData...
python
jobname="manuscript"
python
from rest_framework.response import Response from rest_framework.views import status def validate_request_data_photo(fn): def decorated(*args, **kwargs): title = args[0].request.data.get("title", "") photo = args[0].request.data.get("photo", "") if not title or not photo: retur...
python
"""Test the houdini_package_runner.discoverers.package module.""" # ============================================================================= # IMPORTS # ============================================================================= # Standard Library import argparse import pathlib # Third Party import pytest # ...
python
# -*- coding: utf-8 -*- # Author: Óscar Nájera # License: 3-clause BSD r""" Test Sphinx-Gallery """ from __future__ import (division, absolute_import, print_function, unicode_literals) import codecs from contextlib import contextmanager from io import StringIO import os import sys import re imp...
python
from .ish_report_test import ish_report_test from .ish_parser_test import ish_parser_test from .ComponentTest import SnowDepthComponentTest, SkyCoverComponentTest, SolarIrradianceComponentTest from .ComponentTest import SkyConditionObservationComponentTest, SkyCoverSummationComponentTest from .Humidity_test import Humi...
python
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib SKIDL_lib_version = '0.0.1' RFSolutions = SchLib(tool=SKIDL).add_parts(*[ Part(name='ZETA-433-SO',dest=TEMPLATE,tool=SKIDL,keywords='RF TRANSCEIVER MODULE',description='FM ZETA TRANSCEIVER MODULE, OPTIMISED FOR 433MHZ',ref_prefix='U',num_units=1,do_erc=True...
python
#!/usr/bin/env python3 from serial import Serial import bitarray import time ser = Serial('/dev/ttyUSB0', 115200) for i in range(1,100): for a in range(0,16): ser.write(b'\xcc') ser.write((1<<a).to_bytes(2, byteorder='big')) #ser.write(b.to_bytes(1, byteorder='big')) ser.write(b'\...
python
from aws_cdk import core, aws_events as events, aws_events_targets as targets from multacdkrecipies.common import base_alarm, base_lambda_function from multacdkrecipies.recipies.utils import CLOUDWATCH_CONFIG_SCHEMA, validate_configuration class AwsCloudwatchLambdaPipes(core.Construct): """ AWS CDK Construct ...
python
from serial import * from tkinter import * import tkinter.ttk as ttk import serial import serial.tools.list_ports import threading # for parallel computing class myThread(threading.Thread): def __init__(self, name,ser): threading.Thread.__init__(self) self.name = name self...
python
"""Unit tests for nautobot_ssot_ipfabric plugin."""
python
import torch import torch.nn as nn import torch.nn.functional as F class Cnn1d(nn.Module): def __init__(self, *, nx, nt, cnnSize=32, cp1=(64, 3, 2), cp2=(128, 5, 2)): super(Cnn1d, self).__init__() self.nx = nx self.nt = nt cOut, f, p = cp1 self.conv1 = nn.Conv1d(nx, cOut, f...
python
import sys try: from sp.base import Logging except Exception as e: print "couldn't load splib" sys.exit(1)
python
import configparser import os basedir = os.path.abspath(os.path.dirname(__file__)) config = configparser.ConfigParser() config.read("txdispatch.conf") SECRET_KEY = config.get("app", "secret_key") VERSION = config.get("app", "version") SERVICES = { "http": {}, "sockets": {}, "websockets": {} } for service,...
python
import re import json import requests from Bio import SeqIO from Bio.Seq import Seq from pathlib import Path from tqdm.notebook import trange from Bio.SeqRecord import SeqRecord from function.utilities import fasta_to_seqlist from function.utilities import find_human_sequence def uniprot_id_consistance_check(fasta_p...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
python
import pydantic as _pydantic class CreditWalletConversion(_pydantic.BaseModel): credit_wallet_type: str rate: float currency_code: str class Config: orm_mode = True
python
#!/usr/bin/env python #----------------------------------------------------------------------- # # Core video, sound and interpreter loop for Gigatron TTL microcomputer # - 6.25MHz clock # - Rendering 160x120 pixels at 6.25MHz with flexible videoline programming # - Must stay above 31 kHz horizontal sync --> 200 cy...
python
from typing import Any, Sequence, Tuple, List, Callable, cast, TYPE_CHECKING from argparse import ArgumentParser as OriginalAP from argparse import Namespace as OriginalNS from .namespace import Namespace if TYPE_CHECKING: from hiargparse.args_providers import ArgsProvider class ArgumentParser(OriginalAP): "...
python
from hytra.pluginsystem import feature_serializer_plugin from libdvid import DVIDNodeService try: import json_tricks as json except ImportError: import json class DvidFeatureSerializer(feature_serializer_plugin.FeatureSerializerPlugin): """ serializes features to dvid """ keyvalue_store = "f...
python
import sys from PySide6.QtCore import QCoreApplication from PySide6.QtWidgets import QApplication from folder_watcher import FolderWatcher from main_dialog import MainDialog if __name__ == "__main__": # QCoreApplication.setOrganizationName("DiPaolo Company") QCoreApplication.setOrganizationDomain("dipaolo.co...
python
from peewee import SqliteDatabase db = SqliteDatabase(None)
python
import socket target_host = socket.gethostname() target_port = 9999 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host, target_port)) client.send(b'Hello World!!') response = client.recv(4096) client.close() print(response.decode())
python
# coding: utf-8 """ AVACloud API 1.17.3 AVACloud API specification # noqa: E501 OpenAPI spec version: 1.17.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ExecutionDescriptionDto(object): """NOTE: This class ...
python
"""STACS Exceptions. SPDX-License-Identifier: BSD-3-Clause """ class STACSException(Exception): """The most generic form of exception raised by STACS.""" class FileAccessException(STACSException): """Indicates an error occured while attempting to access a file.""" class InvalidFileException(STACSExceptio...
python
import unittest from andes.utils.paths import list_cases import andes import os class TestPaths(unittest.TestCase): def setUp(self) -> None: self.kundur = 'kundur/' self.matpower = 'matpower/' self.ieee14 = andes.get_case("ieee14/ieee14.raw") def test_tree(self): list_cases(se...
python
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, JSON from sqlalchemy.orm import relationship from open_needs_server.database import Base class DomainModel(Base): __tablename__ = "domains" def __repr__(self) -> str: return f"[{self.id}]{self.title}" id = Column(Integer, prim...
python
# -*- coding: utf-8 -*- #!/usr/bin/env python """ @author: Noah Norman n@hardwork.party """ import json def load_file(): with open('data.json') as data_file: return json.load(data_file) def verbose(): return DATA['verbose'] def fade_in(): return DATA['switch_on_fadein'] def fade_out(): retu...
python
from __future__ import absolute_import import random def RandomService(services): if len(services) == 0: return None index = random.randint(0, len(services) - 1) return services[index]
python
import requests import sys from firecares.firestation.models import FireDepartment from django.core.management.base import BaseCommand from optparse import make_option def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = 'Verifies that the thumbnails f...
python
# -*- coding: utf-8 -*- ''' :file: utils.py :author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/04 23:45:40 ''' class ObjectDict(dict): """:copyright: (c) 2014 by messense. Makes a dictionary behave like an object, with attribute-style access. """ def __getattr__(self, key...
python
import subprocess import sys class ProcessManager(object): """ Implements a manager for process to be executed in the environment. """ def __init__( self, command, working_directory, environment_variables, ): """ Initializes the mana...
python
#! /usr/bin/env python # # Copyright (c) 2011-2012 Bryce Adelstein-Lelbach # # SPDX-License-Identifier: BSL-1.0 # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # TODO: Rename to jobs? # TODO: More typechecking? # TOD...
python
import unittest from unittest.mock import patch, MagicMock from requests import Response from pylaunch.dial import Dial class TestDial(unittest.TestCase): @patch("pylaunch.core.requests.get") def setUp(self, response): with open("tests/xml/dd.xml") as f: response.return_value = MagicMock...
python
import frappe from frappe.utils import data from frappe.utils import cstr, add_days, date_diff, getdate from frappe.utils import format_date @frappe.whitelist() def get_cl_count(from_date,to_date): dates = get_dates(from_date,to_date) data = "" for date in dates: contractors = frappe.get_all('Contr...
python
import os import sys import argparse import torch sys.path.append(os.getcwd()) import pickle import src.data.data as data import src.data.config as cfg import src.interactive.functions as interactive #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT...
python
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import sklearn from sklearn import preprocessing def readdate(name): df = pd.read_csv('gene_mutation.txt', sep=',', header=None) return df if __name__ == "__main__": df=readdate('gene_mutation.txt') del df[0] t2...
python
import numpy as np import pax import torchvision IMAGENET_MEAN = np.array((0.485, 0.456, 0.406)) IMAGENET_STD = np.array((0.229, 0.224, 0.225)) def convert_conv(conv, name=None): """Return a pax.Conv2D module with weights from pretrained ``conv``.""" weight = conv.weight.data.contiguous().permute(2, 3, 1, 0)...
python
import tensorflow as tf from transformers import TFDistilBertForQuestionAnswering model = TFDistilBertForQuestionAnswering.from_pretrained('distilbert-base-uncased-distilled-squad') input_spec = tf.TensorSpec([1, 384], tf.int32) model._set_inputs(input_spec, training=False) # For tensorflow>2.2.0, set inputs in the...
python
"""Library for the ingress relation. This library contains the Requires and Provides classes for handling the ingress interface. Import `IngressRequires` in your charm, with two required options: - "self" (the charm itself) - config_dict `config_dict` accepts the following keys: - service-hostname (requi...
python
import nltk import re import shutil import os from urllib.parse import urlparse from coalib.bears.GlobalBear import GlobalBear from dependency_management.requirements.PipRequirement import PipRequirement from coala_utils.ContextManagers import change_directory from coalib.misc.Shell import run_shell_command from coali...
python
import dnslib.server import dnslib import time import binascii import struct NAME_LIMIT_HARD = 63 A = ord("A") Z = ord("Z") a = ord("a") z = ord("z") ZERO = ord("0") FIVE = ord("5") ir1 = lambda c: c <= Z and c >= A ir2 = lambda c: c <= z and c >= a ir3 = lambda c: c <= FIVE and c >= ZERO BASE32_SRC = b"abcdefghijk...
python
# Generated by Django 3.1.11 on 2021-05-20 12:58 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion import server.utils.model_fields class Migration(migrations.Migration): initial = True dependencies = [ migration...
python
from distutils.command.install import install as install_orig from distutils.errors import DistutilsExecError from setuptools import setup class install(install_orig): def run(self): try: self.spawn(['make', 'install']) except DistutilsExecError: self.warn('listing directo...
python