content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
使用__new__方法实现单例模式
"""
class SingleTon(object):
"""继承该父类的类都是单例类,即重写类的new方法"""
_instance = {} # 用来保存自己类的实例
def __new__(cls, *args, **kwargs):
# 如果没有创建过该实例则创建一个自身的实例
if cls not in cls._instance:
cls._insta... | python |
class PathgeoTwitter:
import sys
from datetime import datetime
'''
createXLSX: convert tweets array into xlsx file
input
1. *tweets (array)
2. *cols (array): which columns in tweets you want to export
3. *outputPath (String)
4. *fileName (St... | python |
# Minimum Window Substring: https://leetcode.com/problems/minimum-window-substring/
# Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty stri... | python |
from webapp.forms import SForm
from django.views.generic.edit import FormView
from django import forms
class HomePageView(FormView):
template_name = 'home.html'
form_class = SForm
success_url = '/'
ctx = dict()
def form_valid(self, form):
# This method is called when valid form data has b... | python |
from .default.params.Params import (Choice, TransitionChoice,
Array, Scalar, Log, Tuple,
Instrumentation, Dict)
| python |
from flask import current_app as app
class Purchase:
def __init__(self, id, uid, pid, time_purchased, name, price, quantity, status):
self.id = id
self.uid = uid
self.pid = pid
self.time_purchased = time_purchased
self.name = name
self.price = price
self.qua... | python |
from heapq import nlargest
def popular_shop(l, r, make_dict):
for i in range(l, r+1):
make_dict[i] += 1
t = int(input())
for j in range(t):
n_m = list(map(int, input().strip().split()))
n = n_m[0]
m = n_m[1]
make_dict = {i + 1: 0 for i in range(n)}
for i in range(m):
arr_el =... | python |
import sys, os
from lxml import objectify
usage = """
Usage is:
py admx2oma.py <your.admx> <ADMX-OMA-URI>
<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file
Take care, the OMA-URI is case sensitive.
<your.admx> : The admx file you ingested
"""
def run():
if len(s... | python |
import logging
import sys
import ast
from typing import Optional
from logistik.config import RedisKeys
from ttldict import TTLOrderedDict
from logistik.cache import ICache
from logistik.db.reprs.handler import HandlerConf
from logistik.environ import GNEnvironment
ONE_HOUR = 60 * 60
class CacheRedis(ICache):
... | python |
from django.template.response import TemplateResponse
from .forms import QuestionForm
# Create your views here.
def index(request) :
form = QuestionForm()
# print(request.context)
data_service = request.context
template_context = data_service.to_dict()
template_context.update(form=form)
... | python |
"""Create social table.
Revision ID: fe9c31ba1c0e
Revises: 7512bb631d1c
Create Date: 2020-04-15 16:12:02.211522
"""
import sqlalchemy as sa
import sqlalchemy_utils as sau
from sqlalchemy.dialects import postgresql
from modist.models.common import SocialType
from alembic import op
from alembic.operations.toimpl impor... | python |
import bpy
class ahs_maincurve_volume_down(bpy.types.Operator):
bl_idname = 'object.ahs_maincurve_volume_down'
bl_label = "肉付けを削除"
bl_description = "選択カーブの設定したテーパー/ベベルを削除"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
try:
for ob in context.selected_objects:
if ob.type != 'CUR... | python |
#! /usr/bin/env python3
# Script for generating a general_pipeline_alternative.glsl that
# handles filling two mip levels, for the given warps-per-workgroup
# and 2nd level mipmap tile size per workgroup.
# Hard to explain, but hopefully the output is more sensible.
from sys import argv, exit, stderr
import os
from pat... | python |
from django.shortcuts import redirect, render
from django.urls import reverse
def home(request):
"""
This bounces home page requests to an appropriate place.
"""
if request.user.is_authenticated:
return redirect(reverse("page", kwargs={'path': 'index'}))
else:
return redirect(reve... | python |
import pygame as pg
from .utils import init_events, check_name_eligibility, str_to_tuple, find_font
from .base_icon import BaseIcon
class Canvas(BaseIcon):
defaults = {'type' : 'Canvas',
'name' : None,
'width' : 200,
'height' : 200,
'x' : None,
... | python |
URL = "https://github.com/General-101/Halo-Asset-Blender-Development-Toolset/issues/new"
EMAIL = "halo-asset-toolset@protonmail.com"
ENABLE_DEBUG = False
ENABLE_DEBUGGING_PM = False
ENABLE_PROFILING = False
ENABLE_CRASH_REPORT = True
| python |
from mrjob.job import MRJob
from mrjob.step import MRStep
class SpendByCustomerSorted(MRJob):
def steps(self):
return [
MRStep(mapper=self.mapper_get_orders,
reducer=self.reducer_totals_by_customer),
MRStep(mapper=self.mapper_make_amounts_key,
... | python |
import aws_cdk.core as cdk
import aws_cdk.aws_s3 as s3
import aws_cdk.aws_s3_deployment as s3_deployment
import aws_cdk.aws_ssm as ssm
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_iam as iam
import aws_cdk.aws_kms as kms
class CfnNag(cdk.Stack):
def __init__(self, scope: cdk.Construct, id: str, general... | python |
"""
PASSIVE Plugin for Testing for Captcha (OWASP-AT-008)
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Google Hacking for CAPTCHA"
def run(PluginInfo):
resource = get_resources("PassiveCAPTCHALnk")
Content = plugin_helper.resource_linklist("... | python |
# -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation,... | python |
# python3
"""Parse a pyi file using typed_ast."""
import hashlib
import sys
import typing
from typing import Any, List, Optional, Tuple, Union
import dataclasses
from pytype import utils
from pytype.ast import debug
from pytype.pyi import classdef
from pytype.pyi import conditions
from pytype.pyi import definition... | python |
#
# Copyright 2022 Logical Clocks AB
#
# 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 ag... | python |
import json
import os
import threading
import time
from functools import wraps
import speech_recognition as sr
class BaseCredentials:
def __init__(self):
pass
def __call__(self):
raise NotImplementedError
@property
def name(self):
raise NotImplementedError
class GoogleClou... | python |
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from django.conf.urls import url
from starlingx_dashboard.dashboards.dc_admin.dc_software_management.views \
import CreateCloudPatchConfigView
from starlingx_dashboard.dashboards.dc_admin.dc_software_management.views \
i... | python |
# Generated by Django 3.2.7 on 2021-09-24 18:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
('recipes', '0001_initial'),
]
operations = [
migratio... | python |
from minpiler.std import M
x: int
y: str
z: int = 20
M.print(z)
# > print 20
| python |
from structure_generator.structure import Structure
from structure_generator.argument import Argument
from minecraft_environment.position import Position
from minecraft_environment.minecraft import fill, clone, setblock, base_block, redstone_dust, redstone_torch, repeater
class Decoder(Structure):
def __init__(self):... | python |
"""
This module provides fittable models based on 2D images.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import warnings
import logging
import numpy as np
import copy
from astropy.modeling import Fittable2DModel
from astropy.modeling.parameters imp... | python |
from .resource import *
from .manager import *
from .dist_manager import *
| python |
from itertools import product
import cv2
import pytest
from sklearn.decomposition import PCA
from sklearn.preprocessing import QuantileTransformer, StandardScaler, MinMaxScaler
from qudida import DomainAdapter
def params_combinations():
return product(
(QuantileTransformer(n_quantiles=255),
Sta... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pub2sd
----------------------------------
Tests for `bibterm2dict` module.
or will be when I get how to reference functions in BibTerm2Dict.py figured out!
"""
import unittest
#import bibterm2dict
#from bibterm2dict import BibTerm2Dict
class TestPub2SD(unittes... | python |
from setuptools import setup
import os
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md")) as f:
readme = f.read()
setup(
name="json_tabularize",
version="1.0.3", # change this every time I release a new version
packages=[
"json_tabularize",
],
package_di... | python |
import numpy as np
import pickle, os
class DataSho():
def __init__(self, pro):
self.pro = pro
def load(self, name):
with open(os.path.join(self.pro.path, name+'.pkl'), 'rb') as f:
return pickle.load(f)
def show_items(self):
return 'Dates', 'Timing', 'user', 'IP', 'state'
def show_appro(self):
chart =... | python |
import discord
import asyncio
from discord.ext import commands
import datetime
import random
import aiohttp
class Utility(commands.Cog):
def __init__(self, bot):
self.bot = bot
client = bot
@commands.Cog.listener()
async def on_ready(self):
print("Cog: Utility, Is Ready!")
@c... | python |
from __future__ import division
import numpy as np
import pandas as pd
from PyAstronomy import pyasl
import astropy.constants as c
import matplotlib.pyplot as plt
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = Fa... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.AlisisReportRow import AlisisReportRow
class KoubeiMarketingDataAlisisReportQueryResponse(AlipayResponse):
def __init__(self):
super(KoubeiMarketingDataA... | python |
import torch
import torch.nn as nn
import numpy as np
ic = 8
ih = 64
iw = 64
oc = 8
oh = 61
ow = 61
kk = 4
conv2d = nn.Conv2d(in_channels=ic, out_channels=oc, kernel_size=kk, padding=0, bias=False)
relu = nn.ReLU(inplace=False)
# randomize input feature map
ifm = torch.rand(1, ic, ih, iw)*255-128
#ifm = torch.one... | python |
"""
Lambdata - a collection of data science helper functions
"""
import lambdata_mpharm88.class_example
# sample code
| python |
""""""
from typing import List, Dict, Optional, Any
import json
from shimoku_api_python.exceptions import ApiClientError
class GetExplorerAPI(object):
def __init__(self, api_client):
self.api_client = api_client
def get_business(self, business_id: str, **kwargs) -> Dict:
"""Retrieve an spe... | python |
import datetime
from django.http import HttpResponse
from django.urls import Resolver404
from blog.auth import authorize
from blog.models import Article
def dispatch(request, *args, **kwargs):
if request.method == 'GET':
return index(request, *args, **kwargs)
elif request.method == "POST":
ret... | python |
"""Tests the probflow.models module when backend = tensorflow"""
import pytest
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
from probflow.core.settings import Sampling
import probflow.core.ops as O
from probflow.distributions import Normal
from probflow.pa... | python |
from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from starlette import status
import app.core.db.crud as crud
router = APIRouter()
@router.post("users/token", tags=["auth"])
async def login... | python |
import time
from gpioServo import MotorControls
motor = MotorControls()
import numpy as np
key_strokes = np.load('train_data.npy',encoding='latin1')
#with open("key_strokes.txt",'r') as keys:
# key_strokes = keys.readlines()
#key_strokes = [x.strip() for x in key_strokes]
key_strokes = [x['input'] for x in key_stro... | python |
import tempfile
import os
import geohash.lock
def test_lock_thread():
lck = geohash.lock.ThreadSynchronizer()
assert not lck.lock.locked()
with lck:
assert lck.lock.locked()
assert not lck.lock.locked()
def test_lock_process() -> None:
path = tempfile.NamedTemporaryFile().name
assert... | python |
A, B, W = map(int, input().split())
W *= 1000
mx = 0
mn = 1000*1000
for i in range(1, 1000*1000+1):
if A*i <= W <= B*i:
mn = min(mn, i)
mx = max(mx, i)
if mx == 0:
print('UNSATISFIABLE')
else:
print(mn, mx)
| python |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorKNN()
while(True):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
if cv2.waitKey(30) == 27:
break
cap.release()
cv2.destroyAllWindows()
| python |
from requests import Session, request
from urllib.parse import urljoin
class FlaskSession(Session):
def __init__(self, app=None, config_prefix="MICROSERVICE"):
super(FlaskSession, self).__init__()
self.config_prefix = config_prefix
self.service_url = None
self.service_port = None
... | python |
from GetFile import getContents
from SortedSearch import find_le_index
from blist import blist
# ------Classes------ #
class Rectangle:
def __init__(self, rectID, x, y, width, height):
self.rectID = rectID
self.x = x
self.y = y
self.width = width
self.height = height
#... | 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 |
# -*- coding: utf-8 -*-
from os import environ
import os.path
import re
from .compat import (
string_type,
json,
urlparse,
urljoin
)
from .exceptions import (
InvalidResourcePath,
)
EVENTBRITE_API_URL = environ.get(
'EVENTBRITE_API_URL', 'https://www.eventbriteapi.com/v3/')
EVENTBRITE_API_PATH... | python |
import wx
import prefs
from theme import Theme
from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
class PrefsEditor(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, size=(500,500), title="WxPyMOO Preferences")
self.parent = parent
panel = wx.Panel(s... | python |
# Copyright 2019 TerraPower, 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 writi... | python |
import pytest
from morphometrics.explore._tests._explore_test_utils import make_test_features_anndata
from morphometrics.explore.dimensionality_reduction import pca, umap
@pytest.mark.parametrize("normalize_data", [True, False])
def test_pca_no_gpu(normalize_data: bool):
"""This test doesn't check correctness of... | python |
#
# Created by Lukas Lüftinger on 05/02/2019.
#
from .clf.svm import TrexSVM
from .clf.xgbm import TrexXGB
from .shap_handler import ShapHandler
__all__ = ['TrexXGB', 'TrexSVM', 'ShapHandler']
| python |
# Copyright 2019 Google 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 applicable law or agreed to in wr... | python |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class CompartmentDefinition_ResourceSchema:
"""
A compartment definition that de... | python |
def square_exp(x:int, power:int) -> int:
if (power < 0):
raise ValueError("exp: power < 0 is unsupported")
result = 1
bit_list = []
while (power != 0):
bit_list.insert(0, power % 2)
power //= 2
for i in bit_list:
result = result * result
if (i == 1):
... | python |
"""This module defines the header class."""
import abc
import datetime
from typing import Optional, Dict
from ..misc.errorvalue import ErrorValue
class Header(object, metaclass=abc.ABCMeta):
"""A generic header class for SAXS experiments, with the bare minimum attributes to facilitate data processing and
red... | python |
from PySide2.QtGui import QVector3D
import numpy as np
def validate_nonzero_qvector(value: QVector3D):
if value.x() == 0 and value.y() == 0 and value.z() == 0:
raise ValueError("Vector is zero length")
def get_an_orthogonal_unit_vector(input_vector: QVector3D) -> QVector3D:
"""
Return a unit vec... | python |
'''Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2'''
class Solu... | python |
"""The Efergy integration."""
from __future__ import annotations
from pyefergy import Efergy, exceptions
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ... | python |
# Copyright (c) 2020 Abe Jellinek
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of condition... | python |
from . import display
from . import field_utils
from . import hunt_ai
from . import player
from . import probabilistic_ai
from . import random_ai
| python |
# coding=utf-8
import humanize
import logging
import re
import times
from markdown import markdown
from path import path
from typogrify import Typogrify
from typogrify.templatetags import jinja2_filters
__author__ = 'Tyler Butler <tyler@tylerbutler.com>'
logger = logging.getLogger(__name__)
def format_... | python |
from conan.packager import ConanMultiPackager
import copy
import platform
if __name__ == "__main__":
builder = ConanMultiPackager(archs = ["x86_64"])
builder.add_common_builds(pure_c=False)
items = []
for item in builder.items:
if item.settings["compiler"] == "Visual Studio":
if ite... | python |
"""Define base class for a course guide argument."""
from args import _RawInputValue, _QueryKVPairs, _InputValue, _InputValues, \
_QueryValues, _ARG_TYPE_TO_QUERY_KEY
from args.meta_arg import MetaArg
from typing import final, Optional
class Arg(metaclass=MetaArg):
"""Base class for a Course Guid... | python |
import sys
import os
import numpy as np
import h5py
sys.path.append('./utils_motion')
from Animation import Animation, positions_global
from Quaternions import Quaternions
from BVH import save
from skeleton import Skeleton
import argparse
offsets = np.array([
[ 0. , 0. , 0. ],
[-13... | python |
from nuaal.Models.BaseModels import BaseModel, DeviceBaseModel
from nuaal.connections.api.apic_em.ApicEmBase import ApicEmBase
from nuaal.utils import Filter
import copy
class ApicEmDeviceModel(DeviceBaseModel):
"""
"""
def __init__(self, apic=None, object_id=None, filter=None, DEBUG=False):
"""
... | python |
#!/usr/bin/env python
import glob
import os
import signal
import subprocess
import sys
import time
from multiprocessing import Process
import yaml
MODULE_PATH = os.path.abspath(os.path.join("."))
if MODULE_PATH not in sys.path:
sys.path.append(MODULE_PATH)
from xt.benchmark.tools.evaluate_xt import get_bm_args_fr... | python |
# Copyright (c) 2021, Bhavuk Sharma
#
# 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, dist... | python |
# Generated by Django 3.2.7 on 2021-11-23 16:39
import ckeditor.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blog',
... | python |
from django import forms
from properties.models import BookingRequest
class BookingRequestForm(forms.ModelForm):
class Meta:
model = BookingRequest
fields = ['comment', 'mobile_phone']
widgets = {
'comment': forms.Textarea(attrs={
'class': 'contact-form__texta... | python |
#! /usr/bin/env python3
import subprocess
import json
import argparse
import sys
import logging
def main():
parser = argparse.ArgumentParser()
parser.description = u'Compile test a sketch for all available boards'
parser.add_argument(u'-s', u'--sketch', dest=u'sketch',
required=Tru... | python |
#Chris Melville and Jake Martens
'''
booksdatasourcetest.py
Jeff Ondich, 24 September 2021
'''
import booksdatasource
import unittest
class BooksDataSourceTester(unittest.TestCase):
def setUp(self):
self.data_source_long = booksdatasource.BooksDataSource('books1.csv')
self.data_source_short ... | python |
from django.contrib import admin
from main.models import Post
# Register your models here.
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
pass | python |
from django.contrib import admin
from .models import Location,categories,Image
admin.site.register(Location),
admin.site.register(categories),
admin.site.register(Image), | python |
# Challenge 1
# vowels -> g
# ------------
# dog -> dgg
# cat -> cgt
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation... | python |
import asyncio
import datetime
import logging
import pytz
import threading
import traceback
from abc import ABC, abstractmethod
from confluent_kafka import DeserializingConsumer, Consumer
from confluent_kafka.schema_registry.json_schema import JSONDeserializer
from confluent_kafka.serialization import StringDeserialize... | python |
from pathlib import Path
from dyslexia import io
import numpy as np
test_path = Path(__file__).resolve().parents[1]
def test_load_image_type():
image_path = test_path / "data" / "images" / "Sample_0.jpeg"
image = io.load_image(str(image_path))
assert isinstance(image, np.ndarray)
def test_load_im... | python |
# Create your models here.
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.files.storage import get_storage_class
from django.db import models
from django_extensions.db.models import TimeStampedModel
fr... | python |
#!/usr/bin/env python3
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import spectral_norm
def _conv_func(ndim=2, transpose=False):
"Return the proper conv `ndim` function, potentially `transposed`."
assert 1 <= ndim <=3
return getattr(nn, f'Conv{"Transpose" if transpose else ""}{ndim}d')... | python |
import numpy as np
import numba as nb
@nb.jit(nopython=True, parallel=False, fastmath=True)
def kernel(M, float_n, data):
# mean = np.mean(data, axis=0)
mean = np.sum(data, axis=0) / float_n
data -= mean
cov = np.zeros((M, M), dtype=data.dtype)
# for i in range(M):
# for j in range(i, M):... | python |
from django.apps import AppConfig
class NotificationsConfig(AppConfig):
name = 'safe_transaction_service.notifications'
verbose_name = 'Notifications for Safe Transaction Service'
| python |
import sys
import subprocess
import os
if sys.platform == 'win32':
dir_path = os.path.dirname(os.path.realpath(__file__))
if len(sys.argv) >= 2:
subprocess.Popen(['startup.bat', sys.argv[1]], cwd=dir_path)
else:
subprocess.Popen(['startup.bat'], cwd=dir_path)
elif sys.platform in ['darwin... | python |
"""
parse simple structures from an xml tree
We only support a subset of features but should be enough
for custom structures
"""
import os
import importlib
from lxml import objectify
from opcua.ua.ua_binary import Primitives
def get_default_value(uatype):
if uatype == "String":
return "None"
elif... | python |
import os
import json
import xmltodict
xml_list = os.listdir("./xml/")
eng_reading = json.loads(open("./noword.json", "r").read())
eng_data = eng_reading["data"]
n = 0
for data in eng_data:
text = data["text"]
for t in text:
word_list = []
try:
xml = "./xml/" + xml_list... | python |
message = 'vyv gri kbo iye cdsvv nomynsxq drsc mszrob iye kbo tecd gkcdsxq iyeb dswo vyv hnnnn' # encrypted message
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
message = message.upper()
def decrypt(message, LETTERS):
for key in range(len(LETTERS)):
translated = ''
for symbol in message:
if ... | python |
from django.shortcuts import render, get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.models import User
from .models import Post, Category
from .forms import CatTransferForm
def category(request, slug=None):
if slug:
instance = get_object... | python |
# Copyright 2013 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 applicable law or ag... | python |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# ... | python |
"""Services Page Locator Class"""
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
from tests.web_app_tests.parabank_test.page_locators.base_page_locator import BasePageLocator
class ServicesPageLocator(BasePageLocator):
"""
Services Page Locat... | python |
from .state import State | python |
#!/usr/bin/env python
import sys
import os
import shutil
import warnings
from django.core.management import execute_from_command_line
os.environ['DJANGO_SETTINGS_MODULE'] = 'wagtail.tests.settings'
def runtests():
# Don't ignore DeprecationWarnings
warnings.simplefilter('default', DeprecationWarning)
... | python |
favorite_word = "coding" # valid string using double quotes
favorite_word = 'coding' # also valid string using single quotes
print(favorite_word) | python |
#encoding=utf-8
import torch
import os
import json
import argparse
import logging
import random
import numpy as np
from typing import NamedTuple
from dataset import MyBartTokenizer, Dataset
from models import Config as ModelConfig
from models import MyPLVCG, MyClassificationPLVCG
from train import test_rank
pars... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import os
import yaml
import re
COLOR_METHOD = '#7fb... | python |
# -*- coding:utf-8 -*-
import os
from handlers import Passport, Verify, VerifyCode, House
from tornado.web import RequestHandler
# , StaticFileHandler
# 静态文件用到StaticFileHandle,这里使用继承加入了xsrf校验
from handlers.BaseHandler import MyStaticFileHandler
# 获取tornado项目的根目录的绝对路径
current_path = os.path.dirname(__file__)
handlers... | python |
import copy
import functools
import json
import logging
from collections import defaultdict
from multiprocessing import Pool
from tempfile import NamedTemporaryFile
from openff.qcsubmit.results import (
OptimizationResultCollection,
)
from openff.qcsubmit.results.filters import (
ConnectivityFilter,
Elemen... | python |
"""
Defines sets of featurizers to be used by automatminer during featurization.
Featurizer sets are classes with attributes containing lists of featurizers.
For example, the set of all fast structure featurizers could be found with::
StructureFeaturizers().fast
"""
import matminer.featurizers.composition as cf
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.