content stringlengths 5 1.05M |
|---|
__all__ = [
"CobaltStrikeCampaignsContentHandler",
"CobaltStrikeTokensContentHandler",
"CobaltStrikeSentEmailsContentHandler",
"CobaltStrikeWebHitsContentHandler",
"CobaltStrikeApplicationsContentHandler",
]
from xml.sax import ContentHandler, parse, SAXNotRecognizedException
from xml.parsers.expat... |
import sys
# Uses the pedigree (.ped) file to create files that will be used by PLINK.
ped_filepath = sys.argv[1]
# Gets the stem of the pedigree file (retaining only the base filename and removing the file extension.
from pathlib import Path
ped_stem = Path(ped_filepath).stem
upid = "{}.{}".format(ped_stem,"update.... |
__all__ = ['acb']
|
"""
Simple Git clone tool
Code readability: cmd, exists, current_dir, change_dir reused from DJANGULAR settings
"""
import os
import shutil
from djangular_cli.terminal.prompt import prompt
from distlib._backport import shutil # noqa F405
from djangular_cli.terminal.custom_prompts import prompt_overwrite, prompt_renam... |
import string
import random
def generate_random_string(length: int = 16) -> str:
return ''.join(
[random.choice(string.ascii_lowercase + string.digits) for n in range(length)]
)
|
#!/usr/bin/env python3
# coding:utf-8
f = open("yankeedoodle.csv")
nums = [num.strip() for num in f.read().split(',')]
f.close()
res = [int(x[0][5] + x[1][5] + x[2][6]) for x in zip(nums[0::3], nums[1::3], nums[2::3])]
print(''.join([chr(e) for e in res]))
|
# FeatherS2 Neo Helper Library
# 2021 Seon Rozenblum, Unexpected Maker
#
# Project home:
# https://feathers2neo.io
#
# Import required libraries
import time
import neopixel
import board
from os import statvfs
from micropython import const
from digitalio import DigitalInOut, Direction, Pull
from analogio import Analo... |
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns =[
# path('',views.index,name='index'),
# path('<int:question_id>/',views.detail, name='detail'),
# path('<int:question_id>/results/', views.result, name='results'),
path('',views.IndexView.as_view(), name ='index'),
pa... |
# cli:commands:create:presets:installable_apps
INSTALLABLE_APPS = {
'allauth': {
'apps': [
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'al... |
# coding=utf-8
import _mysql
from common import db_name_config
from common.mylog import logger
from support.db.mysql_db import doctor_conn, doctor_user_conn, doctor_question_conn
class BaseDao(object):
db_name = ""
table_name = ""
escape_list = [] # 需要转义的list
quot_list = [] # 需要带引号的list
not_app... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2020 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# #*** <License> ************************************************************#
# This module is part of the package GTW.RST.TOP.
#
# This module is licensed under the... |
DIRECTORIES = (
('.',
# 'nosetests -v premailer.test_premailer -m test_parse_style_rules'
'nosetests -v premailer.test_premailer'
# 'nosetests -v premailer.test_premailer -m test_merge_styles',
),
)
|
import pytest
from bmi import create_parser, handle_args
@pytest.fixture
def parser():
return create_parser()
def test_no_args_exits(parser):
# parser.parse_args should raise the exception but in case
# you raised it explicitly further down the stack let's check
# if handle_args raises... |
# coding=utf-8
import inspect
import os
from datetime import datetime
from server_core import HTTPServer, BaseHTTPRequestHandler
class RomaHandler(BaseHTTPRequestHandler):
def do_static(self):
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
url_path = sel... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
# Creating our own User class for future upgrade.
class User(AbstractUser):
is_organisor = models.BooleanField(default=True)
is_agent = models.BooleanField(default=False)
class User... |
__version__ = '10.1'
|
import guppy
from guppy import hpy
import time
import sys
from collections import defaultdict
class Heap():
def __init__(self):
self.array = []
self.size = 0
self.pos = []
def newMinHeapNode(self, v, dist):
minHeapNode = [v, dist]
return minHeapNode
def swapMinHeapNode(self, a, b):
t = se... |
from datetime import datetime
from django.test import TestCase
from tasks.models import Task, Tag
from ..utils import get_tasks_for_individual_report
class IndividualReportsTestUtils(TestCase):
def setUp(self):
Tag.objects.create(name='Test tag')
Task.objects.bulk_create([
Task(date=... |
#!/usr/bin/python -S
# Copyright 2015 Google Inc. 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 ap... |
import bosh_client
import os
import yaml
def do_step(context):
settings = context.meta['settings']
username = settings["username"]
home_dir = os.path.join("/home", username)
index_file = context.meta['index-file']
f = open("manifests/{0}".format(index_file))
manifests = yaml.safe_load(f)
... |
from socket import *
import json
import camera, display, keyboard, audio, pygame
from multiprocessing.connection import SocketClient
import time, random
clock = pygame.time.Clock()
class Manager(object):
__camera = None
__display = None
__keyboard = None
__audio = None
def __init__(self):
self.__camera = cam... |
import datetime
import unittest
from pyvalidator.is_before import is_before
from . import print_test_ok
class TestIsBefore(unittest.TestCase):
def test_valid_before_dates_against_a_start_date(self):
for i in [
['2010-07-02', '08/04/2011'],
['2010-08-04', '08/04/2011'],
... |
#!/usr/bin/python2.4
"""Diff Match and Patch -- Test harness
Copyright 2018 The diff-match-patch Authors.
https://github.com/google/diff-match-patch
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
... |
# XXX Deprecated
from adminapi.filters import * # NOQA F401 F403
|
def paint2dGraph(pl, g):
import matplotlib.pyplot as plt
pointList = []
min_x = pl[0].getPickPosition().getX()
min_y = pl[0].getPickPosition().getY()
max_x = pl[0].getPickPosition().getX()
max_y = pl[0].getPickPosition().getY()
for p in pl:
x = p.getPickPosition().getX()
... |
import sys
import commands
import re
import argparse
import json
from heapq import heappush, heappop
number_articulations = 0
labels = {}
vars = {}
debug = False
cut_id = 0
first_label = ''
last_label = ''
first_var = ''
first_var_bd = ''
last_var = ''
heap_cuts = []
my_graph = {}
def match_names(blocks):
global ... |
import logging
import transformers
from transformers import AutoConfig
logger = logging.getLogger(__name__)
def get_transformers_auto_model(
model_name, num_classes=None, model_type="AutoModel", **kwargs
):
config = AutoConfig.from_pretrained(
model_name, num_labels=num_classes, **kwargs
)
l... |
#!/usr/bin/env python
from setuptools import find_packages
from setuptools import setup
import re
version = re.search(r'__version__ = (.+)\n', open('threddsclient/__init__.py').read()).group(1)
long_description = (
open('README.rst').read() + '\n' + open('AUTHORS.rst').read() + '\n' + open('CHANGES.rst').read()
)... |
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch
def get_loader(root_folder,
batch_size,
num_workers=4):
dataset = dset.ImageFolder(root=root_folder,
transform=transforms.Compose([
... |
import logging
import operator
import itertools
import os
import numpy as np
from typing import Tuple
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from functools import reduce
from data_loader import (
AmericanNationalCorpusDataset,
ObliterateLetters,
ToTensor,
)
from src.di... |
'''
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... |
import requests
url='https://www.python.org'
r = requests.get(url)
print r.status_code
|
#!/usr/bin/python
#
# Usage: plot.py [input_file] [xlabel] [ylabel] [x] [y] [where] [where_values] [groupby]
#
# input_file: Input tsv file where the first row contains column names
# xlabel: Label for plot horizontal axis
# ylabel: Label for plot vertical axis
# x: Name of column to plot on horizontal axis
# y: Name o... |
import gc
import io
import math
import sys
import time
from PIL import Image, ImageOps
import requests
import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from torchvision.transforms import functional as TF
from tqdm.notebook import tqdm
import numpy as np
sys.pat... |
from django.db import models
# Create your models here.
# 首页轮播数据
class Wheel(models.Model):
img = models.CharField(max_length=150)
name = models.CharField(max_length=20)
trackid = models.CharField(max_length=20)
# 首页导航数据
class Nav(models.Model):
img = models.CharField(max_length=150)
name = models.... |
from enum import Enum
import re
class OperatingSystemClasses(Enum):
#ENUM:START
DESKTOP = 1
SERVER = 2
EMBEDDED = 3
#ENUM:END
def parse(self, string):
for j in OperatingSystemClasses:
if (string.lower()).find(j.name.lower())>=0:
return j
return OperatingSystemClasses.DESKTOP
|
import requests
import re
import datetime
from bs4 import BeautifulSoup
import pandas as pd
C_NEWS = "https://cnews.ru/search"
def get_links_with_dates(keyword):
r = requests.get(C_NEWS, params={"search": keyword})
soup = BeautifulSoup(r.text, 'html.parser')
urls = list(map(lambda x: 'https:' + x["href"]... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import os
import argparse
from matplotlib.animation import FuncAnimation
"""
Script to visualize trajectories. Automatically infer datatypes with the following heuristic:
state = plot x-y and values
1d: plot as lines
2d: plot as lines per step
3d: image.... |
"""Execute xCell transformation of gene expression.
This python package gives both a CLI interface and a python module to work with xCell in Python Pandas DataFrames.
Find the official R package here:
https://github.com/dviraran/xCell
And if you find this useful, please cite the authors' publication:
Aran D, Hu Z,... |
from django.apps import AppConfig
class MastersConfig(AppConfig):
name = 'Masters'
|
"""
MIT License
Copyright (c) 2021 Arbri Chili
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import TypedJS
from .settings import app_settings
clas... |
expected_output = {
'id':{
2147483659: {
'encoding': 'encode-xml',
'filter': {
'filter_type': 'xpath',
'xpath': '/if:interfaces-state/interface/oper-status'
},
'legacy_receivers': {
'10.69.35.35': {
'port': 45128,
'protocol': 'netconf'
}
... |
# Generated by Django 3.2 on 2021-04-18 20:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oauth', '0007_profile_profile_photo'),
]
operations = [
migrations.AlterModelOptions(
name='profile',
options={'orderi... |
#python3
from time import sleep
from random import randint
import unicornhat as uh
def rain():
uh.set_layout(uh.PHAT)
uh.brightness(0.5)
r,g,b = 0,0,255
x = randint(0,7)
for y in range(3,-1,-1):
uh.clear()
uh.set_pixel(x,y,r,g,b)
uh.show()
sleep(.2)
return
de... |
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
"""
- request drf封装的请求
- view 应用于那个视图
- obj 对象实例
# SAFE_METHODS包含了'GET', 'HEAD', 'OPTIONS'这三种方法,
# 这三个方法是安全的,下边这个判断就是如果请... |
#!/usr/bin/env python3
import sys
sys.path.append('../../../..')
sys.path.append('..')
import numpy as np
import numpy.random as ra
import xarray as xr
import torch
from maker import make_model, load_data, sf
from pyoptmat import optimize
from tqdm import tqdm
import matplotlib.pyplot as plt
import warnings
warn... |
import argparse
import time
from PIL import Image
import tflite_runtime.interpreter as tflite
import platform
EDGETPU_SHARED_LIB = {
'Linux': 'libedgetpu.so.1',
'Darwin': 'libedgetpu.1.dylib',
'Windows': 'edgetpu.dll'
}[platform.system()]
def make_interpreter(model_file):
model_file, *device = model_file.sp... |
from faker import Faker
header = {
"base_url": "",
"Sandbox-Key": str(Faker().text()),
"Content-Type": "application/json"
}
body = {
"AccessTokenGenerator": {
"client_secret": str(Faker().text()),
"client_id": str(Faker().text()),
"grant_type": str(Faker().text()),
"use... |
from unittest.mock import patch
from django.core.cache import cache
from django.test import TestCase
from constance.test import override_config
from django_redis import get_redis_connection
from crazyarms import constants
from .models import AudioAsset
@patch("autodj.models.random.sample", lambda l, n: list(l)[:n... |
#!/usr/bin/env python
'''
Abstract UNIX daemon process.
The Daemon abstract class handles starting, stopping, and (re)configuring
a daemon process. The class prevents running multiple instances through
the use of a /var/run/<daemon>.pid lock file. The class intercepts SIGHUP
and sets the object's reconfigure variab... |
# coding: utf-8
import time
import pytest
import logging
import hubblestack.status
log = logging.getLogger(__name__)
def sleep_and_return_time(amount=0.1):
time.sleep(amount)
return time.time()
def test_marks_and_timers():
with HubbleStatusContext('test1', 'test2') as hubble_status:
t0 = time.ti... |
from tests.refactor.utils import RefactorTestCase
class TypeVariableTestCase(RefactorTestCase):
def test_type_assing_union(self):
actions = [
(
"""\
import typing
if typing.TYPE_CHECKING:
from PyQt5.QtWebEngineWidgets import QW... |
import logging
from _collections_abc import Iterable
import os
import shutil
from typing import List
from helpers.shell import execute_shell
from synthesis import smt_format
from synthesis.solver_with_query_storage import SmtSolverWithQueryStorageAbstract
class TruncatableQueryStorage_ViaFile:
def __init__(self,... |
import string
from operator import ge as greater_than_or_equal, gt as greater_than
from collections import deque
OPERATOR_PRECEDENCE = {
'(':0,
'+':1,
'-':1,
'*':2,
'/':2,
'^':3,
}
RIGHT_ASSOCIATIVE_OPERATORS = '^'
LEFT_ASSOCIATIVE_OPERATORS = '+-/*'
def pop_operator_queue(operators, output,... |
# -*- coding:utf-8 -*-
# Copyright xmuspeech (Author: JFZhou 2020-05-31)
import numpy as np
import os
import sys
sys.path.insert(0, 'subtools/pytorch')
import libs.support.kaldi_io as kaldi_io
from plda_base import PLDA
class CORAL(object):
def __init__(self,
mean_diff_scale=... |
from utils import get_paths, get_basic_stats
import os
def main():
book_paths = get_paths('../Data/books')
book2stats = {}
for book_path in book_paths:
stats = get_basic_stats(book_path)
book = os.path.basename(book_path).strip('.txt')
print(book, stats)
book2stats[book] = s... |
from app import srv
from app import reply
@srv.route('/hello')
def hello():
return reply.say_hello()
|
# @Author: Tian Qiao <qiaotian>
# @Date: 2016-11-27T10:54:53+08:00
# @Email: qiaotian@me.com
# @Last modified by: qiaotian
# @Last modified time: 2016-11-27T10:54:53+08:00
import sys
print("excuting python script")
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a,b,c=map(int,input().split());d=a-b
print(0 if c==d==0 else '?' if c-abs(d)>=0 else '+' if d>0 else '-') |
from elasticsearch import Elasticsearch,RequestsHttpConnection,NotFoundError
from flask import url_for
import config
import json
es = Elasticsearch(config.ES_HOSTS,connection_class=RequestsHttpConnection)
def create(the_data,the_index,the_doc_type):
try:
results = es.create(index=the_index,
doc_type=the_d... |
# 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 in writing, software
# d... |
#!/usr/bin/env python
"""
"Hashed sequence index" (hsx) file reader (for a fasta file)
-------------------------------------------------------------------
offset 0x00: D2 52 70 95 big endian magic number
.. (95 70 52 D2 => little endian)
offset 0x04: 00 00 01 xx version 1.0 (see note 1)
offset 0x... |
""" Helpers for client-side """
import sys
from urllib import error as urllib_error
from urllib import request
import json
from PIL import Image, ImageTk
from VectorMessenger.MessengerCore.Helpers import Global as h
def iconbitmap_universal(window: object, icon_image=h.ICON_CLIENT_PATH):
""" Cross-platform icon... |
INVALID_OUTPUT_CLASS_DEFINITION = (
"Please set the output_class attribute to the appropriate {base_name} subclass."
)
|
from typing import Dict, List, Tuple
import torch
from torch.utils.data import Dataset
import os
import copy
import numpy as np
import pybullet as pb
import pybullet_data as pb_d
import random
from PIL import Image
import matplotlib.pyplot as plt
from tqdm import tqdm
import pickle
# Reproducing:
# http://a... |
# Copyright 2021 Google LLC
#
# 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 in writing, ... |
from distutils.core import setup
setup(name='yamli',version='0.2',py_modules=['yamli'],
author='val314159',author_email='jmward@gmail.com',
install_requires='pyaml',url='https://github.com/val314159/yamli')
|
from PIL import Image
from PIL import ImageDraw, ImageFont
# 字体位置
BASE_PATH = "/Users/ruiweifang/softwares/images/"
# 处理后图片目录
process_path = "images/process/"
im = Image.open('images/d.jpg')
print(im.format, im.size, im.mode)
draw = ImageDraw.Draw(im)
# 字体 路径 文字大小
fnt = ImageFont.truetype(r'/Users/ruiweifang/softwar... |
from flask import Blueprint
med = Blueprint('med', __name__)
from . import views
|
#!/usr/bin/env python3
from taiseilib.common import (
run_main,
update_text_file,
)
import argparse
import hashlib
import json
import re
from pathlib import Path
meta_re = re.compile(r'(.*loadPackage\()({.*?})(\);.*)', re.DOTALL)
def main(args):
parser = argparse.ArgumentParser(description='Change pa... |
# Copyright (c) MONAI Consortium
# 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 in writing, so... |
from rest_framework import status
from rest_framework.test import APITestCase
from django.urls import reverse
from validate_docbr import CPF
from users.models import User, Address
class AddressTestCase(APITestCase):
def setUp(self):
self.urls = reverse('address-list')
cpf = CPF()
user_cpf... |
# -*- coding: utf-8 -*-
"""
/dms/usermanagementorg/views_group_delete_user.py
.. loescht User mit dem entsprechenden User-Namen
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
... |
from io import BytesIO
import streamlit as st
from arc.arc import Index
from arc.viz import plot
from matplotlib import pyplot
from matplotlib.figure import Figure
def cached_plot(plot_idx: Index, attribute: str | None = None) -> BytesIO:
full_idx = (plot_idx, attribute)
_arc = st.session_state.arc
plot_... |
import numpy as np
from scipy import optimize, stats
def distance_A(A, D):
"""Takes distance matrix D and material attribute/category
matrix A and finds the sum of the pairwise distances of
each entry compared to D. This function should be used
in an optimizer to generate an optimal A matrix.
Imp... |
# Commonly used java library dependencies
def java_base_repositories():
native.maven_jar(
name = "jcip_annotations",
artifact = "net.jcip:jcip-annotations:1.0",
sha1 = "afba4942caaeaf46aab0b976afd57cc7c181467e",
)
native.maven_jar(
name = "com_google_code_gson",
artifact = "com.google.code.gs... |
import os
import shutil
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Sequence, Optional
def make_func_that_creates_cwd_and_out_root_before_running(
out_root: Path, func: Callable[[Path], None]
):
"""
When switching branches, the CWD or target out_root may no ... |
import os
import random
import sys
def usage():
print "{0} <height> [width [range [seed]]]".format(sys.argv[0])
sys.exit(0)
def generate(height, width, range):
map = [[random.randint(-range, range)
for _ in xrange(width)] for _ in xrange(height)]
total = sum([sum(row) for ro... |
import json
class Construct_Lacima_MQTT_Devices(object):
def __init__(self,bc,cd):
self.bc = bc
self.cd = cd
bc.add_header_node("MQTT_DEVICES")
cd.construct_package("MQTT_DEVICES_DATA")
cd.add_redis_stream("MQTT_INPUT_QUEUE",50000)
cd.add_redis_stream... |
import numpy as np
import funcs
def normalize_and_make_homogeneous(x_unnormalized):
"""Modify x_unnormalized to normalize the vector according to standard DLT methods and make homogeneous. Normalization is used to stabilize calculation of DLT
x_unnormalized: 3 or 2 dimensional input data to be normalized
... |
import torch
import ipdb
import random
from torch import nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
import pytorch_lightning as pl
from sklearn.metrics import f1_score as compute_f1_score
MLP_HIDDEN_SIZE1 = 256
MLP_HIDDEN_SI... |
from urllib.parse import urlparse, urlunparse
from traverse_page import get_soup
class GoogleSearch:
def __init__(self, phrase):
self.phrase = phrase
self.phrase = self.phrase.replace(' ', '+')
self.url = f"https://google.pl/search?q={self.phrase}"
def get_soup(self, url=None, parser... |
# -*- coding: utf-8 -*-
import filecmp
import os.path
import unittest
from pseudol10nutil import POFileUtil, PseudoL10nUtil
import pseudol10nutil.transforms
class TestPOFileUtil(unittest.TestCase):
def setUp(self):
self.pofileutil = POFileUtil()
def test_generate_pseudolocalized_po(self):
... |
'''
A situation where 'tab_line_stays_inside' needs to be False.
* tab_line_stays_inside が True だと各MyTabsの線同士の末端が繋が
らなくなり、見た目が悪くなってしまう。
'''
from kivy.app import runTouchApp
from kivy.lang import Builder
import kivyx.uix.behavior.tablikelooks
KV_CODE = '''
#:set LINE_WIDTH 2
<MyTab@ToggleButtonBehavior+Image>:
... |
from statistics import median_low, mean
from math import floor, ceil
pos = list(map(int, input().split(",")))
avg = ceil(mean(pos)) if mean(pos) < median_low(pos) else floor(mean(pos))
print(sum(abs(i - avg) * (abs(i - avg) + 1) // 2 for i in pos))
|
class SearchingSorting:
def swap(self, A, x, y):
temp = A[x]
A[x] = A[y]
A[y] = temp
def linear_search(self, item, my_list):
self.found = False
self.position = 0
while self.position < len(my_list) and not self.found:
if my_list[self.position] == item... |
from math import sqrt, log
class Node():
def __init__(self, game, move = None, parent = None):
self.player_to_move = game.player_to_move
self.remaining_moves = game.get_moves()
self.move = move
self.parent = parent
self.cumulative_score = 0.0
self.visits_count = 0
... |
# frase = str(input('Digite uma frase para ver se é Palindromo: ')).strip().upper().replace(' ','')
# inverso = ''
# for i in range(len(frase)-1,-1,-1):
# inverso += frase[i]
# if inverso == frase:
# print(f'Sua frase {frase} é um palindromo')
# else:
# print(f'Sua frase {frase} não é um palindromo')
#pode... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import darknet_tools
import functools
import json
import os
import settings
import subprocess
import sys
import cv2
from collections import defau... |
import optparse
import textwrap
from herder.scripts import resolve_config, init_environment
def get_optparser(help):
"""Construct an OptionParser for the language scripts."""
parser = optparse.OptionParser(description=textwrap.dedent(help))
parser.add_option('-d', '--domain', dest='domain',
... |
# Test the exploration module
import os
import numpy as np
import tempdir
from activepapers.storage import ActivePaper
from activepapers import library
from activepapers.exploration import ActivePaper as ActivePaperExploration
def make_local_paper(filename):
paper = ActivePaper(filename, "w")
paper.data.cre... |
# Copyright (c) 2015 Kurt Yoder
# See the file LICENSE for copying permission.
import os
import logging
from . import log_file
from . import json_file
class ParserHostException(Exception):
pass
class Host(object):
def __init__(self, path):
self.path = path
self.logger = logging.getLogger(__na... |
from django.apps import AppConfig
class SignupConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'signup'
|
from application import db
from store.models import Store
class Pet(db.Document):
external_id = db.StringField(db_field="ei")
name = db.StringField(db_field="n")
species = db.StringField(db_field="s")
breed = db.StringField(db_field="b")
age = db.IntField(db_field="a")
store = db.ReferenceFiel... |
import magicbot
import wpilib
from wpilib import VictorSP
from magicbot import tunable
from robotpy_ext.control.toggle import Toggle
from wpilib.buttons import JoystickButton
from common.ctre import WPI_TalonSRX, WPI_VictorSPX
from wpilib.kinematics import DifferentialDriveKinematics
from common.rev import IdleMode, M... |
# Copyright 2020 Google LLC
# Copyright 2020 EPAM Systems
#
# 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 appl... |
from pymtl import *
from lizard.util.rtl.interface import UseInterface
from lizard.msg.codes import ExceptionCode
from lizard.core.rtl.messages import FetchMsg, DecodeMsg, PipelineMsgStatus
from lizard.core.rtl.frontend.imm_decoder import ImmDecoderInterface, ImmDecoder
from lizard.core.rtl.frontend.sub_decoder import ... |
# This file is auto-generated by /codegen/x86_64_test_encoding.py
# Reference opcodes are generated by:
# GNU assembler (GNU Binutils) 2.25
from peachpy.x86_64 import *
import unittest
class TestKADDB(unittest.TestCase):
def runTest(self):
pass
class TestKADDW(unittest.TestCase):
def runTest(se... |
"""
Description: This test is to run onos Teston VTN scripts
List of test cases:
CASE1 - Northbound NBI test network/subnet/ports
CASE2 - Ovsdb test&Default configuration&Vm go online
lanqinglong@huawei.com
"""
from adapters.client import client
if __name__=="__main__":
main = client()
main.getdefaultpara()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.