content
stringlengths
0
894k
type
stringclasses
2 values
from wafw00f.main import WafW00F from wafw00f.lib.evillib import oururlparse from util.http_util import http_client __plugin__ = "Subdomain Scanner" SEQUENCE = 2 URL = "https://www.virustotal.com/vtapi/v2/domain/report" API_KEY = "a0283a2c3d55728300d064874239b5346fb991317e8449fe43c902879d758088" async def run(ur...
python
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose import astropy.units as u from astropy.io import fits from gammapy.irf import Background3D, EffectiveAreaTable2D, EnergyDispersion2D class TestIRFWrite: def setup(self): self.energy...
python
link='https://www.giveindia.org/certified-indian-ngos' def List_of_Indian_NGOs_to_donate(url): from bs4 import BeautifulSoup import pprint import requests page = requests.get(url) soup = BeautifulSoup(page.text,"html.parser") man_class=soup.find('table',class_='jsx-697282504 certified-ngo-table') list1=[] for ...
python
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
python
import types __all__ = ["lzip", "lfilter", "lfilternone", "copy_func", "find_in_bases"] def lzip(*iterables): r""" Shorthand for list(zip(*iterables)) """ return list(zip(*iterables)) def lfilter(func, iterable): r""" Shorthand for list(filter(func, iterable)) """ return list(filter(func, iterable)) def lfi...
python
from pathlib import Path from statistics import median_high, mean import tensorflow as tf from metrics.base import Metric class SATAccuracy(Metric): def __init__(self) -> None: self.mean_acc = tf.metrics.Mean() self.mean_total_acc = tf.metrics.Mean() def update_state(self, model_output, st...
python
class Dimensions(): """ Two dimensions: width and height """ def __init__(self, width, height): self.width = int(width) self.height = int(height)
python
import numpy as np import pandas as pd from scipy import stats from math import isnan def apply(series, period, func, category=None, return_as_cat=None) -> pd.Series: """ Apply 'func' to rolling window grouped by 'category' :param series: time-series :param period: rolling window period :param fun...
python
""" python consumer, consume messages from amqp and execute python code """ __version__ = '0.1.0'
python
import numpy as np import matplotlib.pyplot as plt from open_spiel.python.egt import dynamics from open_spiel.python.project.part_1.visualization import paths from open_spiel.python.project.part_1.visualization.probarray_visualization import prepare_plot payoff_matrix_prisoners_dilemma = np.array([[[3,0],[5,1]],[[3...
python
from django.db import models class Mod(models.Model): fld = models.IntegerField() class M2mA(models.Model): others = models.ManyToManyField('M2mB') class M2mB(models.Model): fld = models.IntegerField()
python
from math import prod import qiskit import numpy as np from generate_training_set import insert_pauli from qiskit import QuantumCircuit from random import sample, seed from itertools import product def get_measuring_circuit(basis_list: list) -> QuantumCircuit: qc = QuantumCircuit(len(basis_list[0][1])) # Find...
python
""" The `domain` package provides a data structure for representing multi-zone meshes and their related data. The goal is to be able to represent all concepts from CGNS, though not necessarily in the same way. It also provides functions for obtaining flow values across a mesh surface and reading/writing in files vario...
python
# -*- coding: utf-8 -*- # @Time : 2019-11-03 13:04 # @Author : ljj0452@gmail.com import datetime from mongoengine import ( Document, StringField, DateTimeField, IntField, FloatField, BooleanField, EmbeddedDocument, EmbeddedDocumentListField ) class WorkerDetail(EmbeddedDocument): ...
python
import csv import argparse data = [] parser = argparse.ArgumentParser(description='file input for parse bank information') parser.add_argument('--file', metavar='str', type=str) args = parser.parse_args() with open(args.file, 'rb') as csvfile: reader = csv.reader(csvfile) i = 0 for row in reader: ...
python
#!/usr/bin/env python from __future__ import print_function import sys import glob import time import os, os.path import doctest import unittest try: import coverage except ImportError: print("No 'coverage' module found. Try:") print(" sudo apt-get install python-coverage") sys.exit(1) import logg...
python
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.5.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np from scipy i...
python
a = float(input()) b = float(input()) media = ((a*3.5) + (b*7.5)) / 11 print('MEDIA = {:.5f}'.format(media))
python
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def homePageView(request): return HttpResponse('OK!')
python
"""Error handling utils.""" import nestor_api.lib.io as io from nestor_api.utils.logger import Logger def non_blocking_clean(path: str, *, message_prefix: str = None): """Try to clean directory/file at path but don't raise an error if it fails (only log it).""" message = "Error trying to clean temporary ...
python
from flask import Flask, jsonify, render_template, request from flask_sqlalchemy import SQLAlchemy from random import choice app = Flask(__name__) # Connect to Database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Cafe TABLE...
python
from random import randint def quicksort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: ...
python
# https://packaging.python.org/en/latest/distributing.html from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( # details nam...
python
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # #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...
python
class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums or k==0: return [] n=len(nums) queue=collections.deque() res=[] """ using the dequ...
python
from django.core.cache import cache from django.views.generic import TemplateView class IndexView(TemplateView): template_name = "verspaeti/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) verspaeti_data_cache = cache.get('verspaeti_data') ...
python
from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import User from .authentication import token_expire_handler, expires_in class UserSerializer(serializers.HyperlinkedModelSerializer): money_deposits = serializers.HyperlinkedRelatedField( many=True, rea...
python
# example environment, rolegroup, and role defs environmentdefs = { "environment1": ["host1", "host2"], } roledefs = { "role1": ["host1"], } componentdefs = { "role1": ["component1"], }
python
import json from climate_simulation_platform.db import save_revision, save_step from climate_simulation_platform.message_broker import send_preprocessing_message from climpy.interactive import ValueChanger import panel as pn import xarray as xr import numpy from scipy.ndimage import measurements import holoviews as h...
python
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 10:56:00 2020 @author: Jimit.Dholakia """ import feedparser import time import urllib.parse import os os.environ['TZ'] = 'Asia/Kolkata' time.tzset() #updated ='Last Updated on: ' + time.strftime('%b %d, %Y %X %Z', time.localtime()) current_time = ...
python
import re from argparse import ArgumentParser from dodo_commands.dependencies import yaml_round_trip_dump from dodo_commands.framework.singleton import Dodo def _args(): parser = ArgumentParser(description="Print the full configuration.") parser.add_argument("key", nargs="?") args = Dodo.parse_args(parse...
python
# -*- coding: utf-8 -*- """ Created on Thu Feb 2 10:56:02 2017 @author: FuckYouMicrosoft """ high = 100 low = 0 ans = (high+low)//2 print('Please think of a number between 0 and 100') print('Is your secret number '+ str(ans)+'?') userInput = str(input("Enter 'h' to indicate the guess is too high. Enter '...
python
import numpy as np import tkinter import matplotlib.pyplot as pyplot from matplotlib.path import Path import matplotlib.patches as patches class GridWorldMDP(object): # Construct an GridWorld representation of the form # # 20 21 22 23 24 # 15 x 17 18 19 # 10 x 12 x 14 # 5 ...
python
from django import forms from .models import Loan from books.models import Book class LoanForm(forms.ModelForm): code = forms.CharField(label='Book Code') class Meta: model = Loan fields = [ 'to', ]
python
from time import sleep from operator import itemgetter oficial = str(input('Palpite oficial: ')).strip().split("/") jogadores = int(input('Quantos jogadores vão participar na rodada ? ')) print ('-'* 50) print ('Analizando',end=' ') sleep(1) print ('.',end=' ') sleep(1) print ('.',end=' ') sleep(2) print('.', end=' //...
python
# -*- coding: utf-8 -*- """ Created on Sun Mar 15 19:58:26 2020 @author: Ravi """ from collections import Counter def gameOfThrones(s): odd = 0 se = Counter(s) for i in se.values(): if i%2!=0: odd+=1 if odd>1: return 'NO' return 'YES' s = in...
python
"""Simple heartbeat library""" import logging from datetime import timedelta from typing import Optional import requests import isodate heartbeat_app_url = "http://localhost:5000/" __VERSION__ = "0.1.2" __AUTHOR__ = "Joshua Coales" __EMAIL__ = "dr-spangle@dr-spangle.com" __URL__ = "https://github.com/joshcoales/simp...
python
# Generated by Django 3.0.6 on 2020-10-15 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('limb', '0004_metalsite_ion'), ] operations = [ migrations.AddField( model_name='metalsite', name='ready_for_presenta...
python
# Generated by Django 2.2 on 2019-06-28 12:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20190628_1200'), ] operations = [ migrations.RenameModel( old_name='Roles', new_name='Role', ), ...
python
from conftest import data_path from kitt.image.objdetect.annotation import AnnotationType from kitt.image.objdetect.voc import voc_to_annotated_image def test_load_voc_xml(): annotated = voc_to_annotated_image(data_path("example.xml")) width, height = annotated.width, annotated.height assert width == 500...
python
import numpy as np import glob, os import random from imageio import imread, imwrite import shutil from skimage import img_as_ubyte, img_as_float from math import ceil, sqrt, pi from scipy.signal import convolve2d import tensorflow as tf from tensorflow.keras.layers import UpSampling2D def generate_patches_pngs(noisy_...
python
import os from landolfio.settings.base import * # noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"] SESSION_COOKIE_SE...
python
import sys import json from mlscratch.measurer import ProbsMeasurer, Measurer from sacnn.core import SacnnModel, get_arch, compute_labels_accuracy, ConfusionMatrixMeasurer from sacnn.core.fs_utils import load_np_tensor def get_test_data(num_labels): load_folder = 'data_reduced' if num_labels == 3 else 'data' ...
python
"""Auto-generated file, do not edit by hand. AM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_AM = PhoneMetadata(id='AM', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[148]\\d{2,4}', possible_length=(3, 4, ...
python
import numpy as np import sys sys.path.insert(0, '../QLearning/' ) from simpleQLearning import QLearningAgent import matplotlib.pyplot as plt import os import random from collections import deque class ReplayBuffer(object): def __init__(self, size): """ Create Replay buffer. Parameters ...
python
class ChromeSpider(object): pass
python
class TestExample: def test_me(self): assert True def but_me(self): assert True class DescribeExample: def it_has_some(self): assert True
python
# -*- coding: utf-8 -*- """Indexing hdf5 files""" ext = '.h5' import os from .. import csutil from .interface import SharedFile class FileManager(object): file_class = SharedFile def __init__(self, store=False): if store is False: self.log = csutil.FakeLogger() else: ...
python
import numpy as np from utils import * def main(): DIMS = (500, 500) data_path = './data/' # load 4 cat images img1 = img_to_array(data_path + 'cat1.jpg', DIMS) img2 = img_to_array(data_path + 'cat2.jpg', DIMS, view=True) # concat into tensor of shape (2, 400, 400, 3) input_img = np.con...
python
import sys import pygame from checkerboard import * import ai_minmax as am def _get_init_player(): flag = input("输入 0(人)/ 1(电脑)指定先手(执黑): ") if flag == "0": return BLACK_CHESSMAN, 0 elif flag == "1": return WHITE_CHESSMAN, 1 else: return None, None def _get_next(cur_runner): ...
python
""" Useful functions for making pretty plots in matplotlib of accuracy of stock predictions. @author: Riley Smith Created: 1-21-2021 """ import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np from utils import COLORS def plot_predicted_close(ticker, pred, true, save_to=None): ""...
python
from threading import Semaphore import threading, random from arg import args from profe import profesor,Materias,profesores mutexP = [Semaphore(1) for i in range(args.profeso)] listA = [Semaphore(0) for i in range(args.profeso)] contadorA= 0 mutexC= Semaphore(1) class Alumno(threading.Thread): def __init__(self,...
python
from datetime import date history_date = {'上期标准仓单交易正式上线': [date(2018, 5, 28), date(2018, 6, 1)], '中东局势动荡': [date(2018, 4, 10), date(2018, 4, 20)], '中国对美国加征关税': [date(2018, 4, 4), date(2018, 4, 11)], '美国再次开启贸易战': [date(2018, 6, 15), date(2018, 6, 30)], '中美...
python
#!/usr/bin/env python """ BehaviorModule ^^^^^^^^^^^^^^ .. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de> Starts the body behavior """ import actionlib import os import rospy from geometry_msgs.msg import PoseWithCovarianceStamped from tf2_geometry_msgs import PoseStamped from humanoid_league_ms...
python
# https://adventofcode.com/2018/day/6 def dist(a,b): return abs(b[0]-a[0]) + abs(b[1]-a[1]) def find_single_closest(x,y, points): closest_points = [] closest_dist = -1 for p in range(len(points)): d = dist(points[p], (x,y)) if d < closest_dist or closest_dist == -1: closest...
python
import eventlet import eventlet.event import logging logger = logging.getLogger(__name__) class GreenletRace: def __init__(self, tasks): self._event = eventlet.event.Event() self._tasks = [eventlet.spawn(self._wrap, fn) for fn in tasks] def _resolve(self, value=None): if not self._ev...
python
import pytest from ceph_deploy.cli import get_parser SUBCMDS_WITH_ARGS = ['push', 'pull'] class TestParserConfig(object): def setup(self): self.parser = get_parser() def test_config_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('config --help'.split...
python
import sqlite3 import os import random, string def randomword(length): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length)) class DBWrapper: def __init__(self): self.dbname = randomword(16) + ".db" os.system("touch " + self.dbname) self.conne...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Course : GTI770 — Systèmes intelligents et apprentissage machine Project : Lab # X - Lab's name Students : Names — Permanent Code Group : GTI770-H18-0X """ from __future__ import division, print_function, absolute_import import tensorflow as tf imp...
python
# coding=utf-8 from argparse import ArgumentParser import os from torchvision import models import cv2 import torch import shutil from torchvision import transforms as T from torch.autograd import Variable car_label = ["GMC_SAVANA", "Jeep(进口)_大切诺基(进口)", "Jeep(进口)_牧马人", "Jeep(进口)_自由侠(海外)", "MINI_MINICOUNTRYMAN", "smart...
python
# adjuster.py Demo of Adjusters linked to Labels # Released under the MIT License (MIT). See LICENSE. # Copyright (c) 2021 Peter Hinch # hardware_setup must be imported before other modules because of RAM use. import hardware_setup # Create a display instance from gui.core.ugui import Screen, ssd from gui.widgets.l...
python
from copy import copy NL_type = 'NEWLINE' INDENT_type = 'INDENT' DEDENT_type = 'DEDENT' PAREN_OPENERS = 'LPAR', 'LBRACE', 'LSQB' PAREN_CLOSERS = 'RPAR', 'RBRACE', 'RSQB' class Tok(): def __init__(self, type=None, value=None, lexer=None): self.type = type self.value = value self.lineno = N...
python
import numpy as np import matplotlib.pyplot as plt import os import glob def matlab_multiply(Array_A, Array_B): '''perform matlab style matrix multiplication with implicit expansion of dimesion''' assert np.ndim(Array_A)==1 & np.ndim(Array_B)==1 NewArray = np.zeros((len(Array_B), len(Array_A))) fo...
python
from .run import _reifiers from .unify import _converters, _occurs_checkers, _unifiers def register(key, *, convert=None, unify=None, occurs=None, reify=None): if convert: _converters.add(key, convert) if unify: _unifiers.add(key, unify) if occurs: _occurs_checkers.add(key, occurs)...
python
# -*- coding: utf-8 -*- """ :Author: Jaekyoung Kim :Date: 2018. 8. 24. """ from unittest import TestCase from pandas.util.testing import assert_frame_equal from ksif import * class TestBenchmark(TestCase): def test_benchmark(self): pf = Portfolio() # The return of Portfolio.benchmark should be...
python
from collections import Counter from datetime import datetime import os import requests from subprocess import Popen, PIPE from pathlib import Path import json from typing import Dict, Union, TYPE_CHECKING from kipoi_utils.external.torchvision.dataset_utils import download_url if TYPE_CHECKING: import zenodoclien...
python
"""Nearly empty __init__.py to keep pylint happy.""" from __future__ import annotations
python
from Rules import Rules import random import copy class Montecarlo: def __init__(self, n=1000): self.iterations = n self.game = Rules() def gameOver(self): winner = self.game.get_winner(end=True) if winner == 1: print('AI Winner') elif winner == 0: ...
python
import sys import re import os from setuptools import setup from setuptools import find_packages PY_VER = sys.version_info if PY_VER < (3, 6): raise RuntimeError("asynceth doesn't support Python version prior 3.6") install_requires = [ 'regex', 'ethereum', 'eth_abi>=2.0.0-beta.1' ] tests_require = [...
python
from hashlib import md5 from os.path import join, dirname, exists, samefile from os import walk, unlink, chmod, rename, link, symlink, stat from logging import info, error from tempfile import mktemp from stat import S_ISREG, S_IWUSR class Database(dict): def add(self, path, size, ino, dev, mtime): # dev...
python
# Run this if you want to see that a simple network can be set up and left idle # Just tries to make a CH and a CM and have them connect to each other import CM,CH import time from common import handlers if __name__ == "__main__": head = CH.ClusterHead(CH.UDPHandler,CH.TCPHandler,spoofContract=True) mem = CM.C...
python
nome=input('Digite o nome do aluno: ') n1=float(input('Digite a nota da primeira prova: ')) n2=float(input('Digite a nota da segunda prova: ')) n3=float(input('Digite a nota da terceira prova: ')) nt=(n1+n2+n3) md=(nt/3) print('A nota final do aluno(a) {} foi de {:.2f}.'.format(nome,md))
python
import tensorflow as tf def model_softmax(x,batch_size,total_speakers): print('I/P shape ',x.get_shape()) x=tf.reshape(x,[batch_size,-1,64,1]) with tf.variable_scope('conv2D_A'): x=tf.layers.conv2d(x,filters=32,kernel_size=5, strides=(2,2),padding='SAME',kernel_initializer=tf.contrib.layers.x...
python
# (C) Datadog, Inc. 2022-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # This file is autogenerated. # To change this file you should edit assets/configuration/spec.yaml and then run the following commands: # ddev -x validate config -s <INTEGRATION_NAME> # ddev -x va...
python
import datetime import logging from typing import Any, Dict, Optional, List, Generic, TypeVar from urbanairship import common, Airship logger = logging.getLogger("urbanairship") ChannelInfoType = TypeVar("ChannelInfoType", bound="ChannelInfo") class ChannelInfo(object): """Information object for iOS, Android, ...
python
import requests import os from forms.utils import get_config_dict, send_message def create_formatted_message(response, breaks='\n'): config = get_config_dict(response['Config']) question_mapping = {} for count, question in enumerate(config['questions'], 1): question_mapping[question['title']] = ...
python
import tkinter as tk import mysql.connector import tkinter.font as tf from tkinter import * def search_user_account(): mydb = mysql.connector.connect( host="localhost", user="root", password="aniket123", database='project_dbms' ) mycursor = mydb.cursor() ...
python
# Demonstration of a magnifier on a map import simplegui # 1521x1818 pixel map of native American language # source - Gutenberg project image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg") # Image dimensions MAP_WIDTH = 1521 MAP_HEIGHT = 1818 # Scal...
python
def call(g): next(g)
python
import sys Height = 48 Width = 128 def is_too_far(cell): dist_sqrt = cell.real*cell.real + cell.imag * cell.imag return dist_sqrt > 4 def iterations(x,y): c = complex(x,y) z = 0 for i in range(0,250): if is_too_far(z): return i z = z*z + c return 256 def plot(): start_posX = -3.0 end_posX = 1.0 ...
python
############################################################ # -*- coding: utf-8 -*- # # # # # # # # # ## ## # ## # # # # # # # # # # # # # # # ## # ## ## ###### # # # # # # # # # Python-based Tool for interaction with the 10micron mounts # GUI with PyQT5 fo...
python
import string import re import nltk class LimpiadorDeTexto(): def __init__(self,dir_stopwords): """ Inicializa y carga lista de stopwords desde el path recibido """ arc = open(dir_stopwords, "r", encoding='utf-8') self.stp_wrds = [line.strip() for line in arc] ...
python
import requests import facebook from Reposter.utils.logger import logger import urllib.request import os class PostSubmitter: def __init__(self, page_id, token, message=False): self.page_id = page_id self.oauth_access_token = token self.message = message ...
python
import textwrap import wx from utils.logger import get_logger from utils.utils import SetIcon2Frame logger = get_logger(__name__) class QRcodeFrame(wx.Frame): def __init__(self, image, meeting_dict, *args, **kwds): self.image = image self.config = args[0].config self.icon_path = args[0]....
python
"""This script deletes all duplicate sentences in a parallel corpus of two languages, L1 and L2. A sentence is considered to be duplicate if the same string appears in L1 in two lines and if in the same two lines in L2, the strings are also the same (with regard to each other only in L2). This means if the L1 corpus e...
python
""" dmt/data/loading/oto_loader.py OTO = OneToOne. Meaning 1 subject loads exactly 1 batch example. Daemon loader wraps torch's Dataloader by continuously loading into a queue. 'Daemon' here refers to its original software interpretation (not Python's) where a process works continuously in the background. Added Func...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: test_package_pool :Synopsis: :Author: servilla :Created: 7/26/20 """ from dateutil import tz from pathlib import Path import pytest from sniffer.config import Config from sniffer.package.package_pool import PackagePool ABQ_TZ = tz.gettz("America/De...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Django Markdownx documentation build configuration file, created by # sphinx-quickstart on Fri Mar 10 22:41:38 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in ...
python
""" Since our development environment is controlled completely by passing environment variables from one process to its children, in general we allow all variables to flow freely. There are, however, a few circumstances in which we need to inhibit this flow. Maya and Nuke, for example, add to the :envvar:`python:PYTH...
python
import os import time def os_walk(folder_dir): for root, dirs, files in os.walk(folder_dir): files = sorted(files, reverse=True) dirs = sorted(dirs, reverse=True) return root, dirs, files def time_now(): '''return current time in format of 2000-01-01 12:01:01''' return time.strft...
python
from setuptools import find_packages, setup with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='RailgunS', version='0.56', author='NY', author_email='nyssance@icloud.com', description='Only My Railgun', long_description=long_description, long_descr...
python
from django import forms from loginApp.models import User, Profile class smsForm(forms.ModelForm): field_10_student = forms.MultipleChoiceField(required=False, label='دانش آموزان پایه دهم') field_10_mom = forms.MultipleChoiceField(required=False, label='مادر دانش آموزان پایه دهم') field_10_dad = forms.Mul...
python
#!/usr/bin/env python # -*-coding:utf8 -*- ''' 合并webface数据集和vggface2数据集 注意相同类别的进行合并 ''' import os from PIL import Image def read_overlap(file): # 读取overlap文档,输出对应的dict simi_dict = {} with open(file, 'r') as f: alllines = f.readlines() for line in alllines: line_split = line.str...
python
import numpy as np import math c = 2.9979 * pow(10,8) #Practice test question 1 Type def MagneticField(): dielecConst = float(input("Input the Dielectric Constant: ")) Speed = (c / math.sqrt(dielecConst)) * pow(10,-8) print("Speed:", Speed , "x10^8 m/s") MagneticField()
python
# -*- coding: utf-8 -*- import maths.parser import util.html from .AstNode import * from .IdentifierNode import * from .NumberNode import * from .StringNode import StringNode class BinOpNode(AstNode): """Binary (two operands) operator node left -- left operand (AstNode) right -- right operand (AstNode...
python
import sys import unittest import mock from datetime import datetime import json from .messages import HipchatMessage def setup_mock_request(mock_method, status_code, json_data): mock_response = mock.Mock() mock_response.read.return_value = json.dumps(json_data) mock_response.getcode.return_value = status...
python
class ColourImage(object): def __init__(self,r,g,b): self.r=r self.g=g self.b=b def _determineColorValue(self): return str("#%02x%02x%02x" % (self.r, self.g, self.b)) # return ("hello")
python
#!/usr/bin/env python import os import socket import requests server = os.environ.get("RATSERVER", "localhost") port = os.environ.get("RATPORT", "8000") username = os.environ.get("USER", "") hostname = socket.gethostname() data = { "user": username, "host": hostname, } def rat(message): data["message...
python
import tensorflow as tf from layers import SparseDense, KWinner, SparseConv2D def dense_mlp(): inputs = tf.keras.Input(shape=(784,)) dense1 = tf.keras.layers.Dense(128, activation='relu')(inputs) dense2 = tf.keras.layers.Dense(64, activation='relu')(dense1) logits = tf.keras.layers.Dense(10)(dense2) ...
python
from .base import SampleExtension from application.src.misc.health import ReceivedTreatment, PriorInfection class PatientTreatment(SampleExtension): submit_table_name = "samples_patient_treatment" clean_keys_strings = ["date_of_prior_antiviral_treat", "date_of_prior_sars_cov_2_infe...
python