content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2018-03-16 23:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('productos', '0001_initial'),
]
operations = [
migrations.RenameModel(
ol... |
#
# PySNMP MIB module Fore-DS1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-DS1-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:16:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
import unittest
import ramda as R
"""
https://github.com/ramda/ramda/blob/master/test/reduceBy.js
"""
byType = R.prop('type')
def sumValues(acc, obj): return acc + obj['val']
sumInput = [
{'type': 'A', 'val': 10},
{'type': 'B', 'val': 20},
{'type': 'A', 'val': 30},
{'type': 'A', 'val': 40},
{'... |
def readFastq(filename):
'''Reading and parsing a fastq file
return the reads in a list
returns the quality score for the individual read'''
sequences = [] # stores a list sequences
qualities = [] # stores a list of quality scores
with open(filename) as fh: # open the file and store it in a fi... |
import asyncio
import random
import hikari
import tanjun
from hikari.interactions.base_interactions import ResponseType
from hikari_testing.bot import bot
from hikari_testing.bot.client import Client
component = tanjun.Component(name="fun")
EMBED_MENU = {
"📋": {"title": "Title", "style": hikari.ButtonStyle.SEC... |
"""
This file contains exhaustive list of all the metrics
those can be collected to monitor CouchDB.
"""
couchdb_metrics = {
"basic_metrics": {
"node_metrics": [
("couchdb.httpd.aborted_requests", "counter"),
("couchdb.httpd.bulk_requests", "counter"),
("couchdb.httpd.re... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Fraunhofer FKIE/CMS, Alexander Tiderko
# 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 mu... |
# Copyright 2020 BULL SAS All rights reserved
"""This module contains different classes to implement a stop criterion.
These criteria take as input the history of the optimization process,
and outputs a boolean indicating if the optimization process should stop
depending on the tested values.
The implemented criteria ... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
import numpy as np
from animation import vector
from pygame import draw
from animation.trail import trail
class particle:
radius = 5
force_constant = 7000
mass = 3 * 10**-13
def __init__(self, is_positive, position, velocity):
self.is_positive = is_positive
self.position = position
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Interfaces relating to NTIIDs.
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
# pylint: disable=inherit-non-class, no-self-argument, no-method-argument
from zope import interface
from zope.interface.c... |
from typing import List
from collections import Counter
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
def isEqual(a, b):
if len(a) != len(b):
return False
for key, val in a.items():
if b[key] != val:
... |
import toml
class FeatureField(object):
DEFAULT_TOWER_NAME = "default_tower"
def __init__(self):
self.name = None
self.dtype = None
self.ignore = None
self.tot_length = None
self.num_sub_field = None
self.pad_val = None
self.emb_group = None
sel... |
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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 t... |
from io import BytesIO
from weakref import WeakKeyDictionary, WeakSet
from matplotlib.figure import Figure
from deephaven.plugin.object import Exporter, ObjectType
from threading import Timer
# Name of the matplotlib figure object that was export
NAME = "matplotlib.figure.Figure"
# DPI for the figure
DPI = 144
# Dic... |
from flask import Blueprint
from arrow import get as arrow_get
from tubbymemes import config
bp = Blueprint('filters', 'filters')
@bp.app_template_filter('shorten_address')
def shorten_address(a):
_p = a[0:6]
_s = a[-4:]
return f'{_p}...{_s}'
@bp.app_template_filter('humanize')
def humanize(d):
i... |
import datetime
import re
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
from lxml import etree
from lxml.builder import ElementMaker
import pytz
from open511.utils.schedule import Schedule
from open511.utils.serialization import NS_ATOM, NS_AGE, NS_XHTML, NS_GEORSS, NS... |
# Generated by Django 3.2 on 2021-05-24 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timelines', '0003_timeline_bundle'),
]
operations = [
migrations.RemoveField(
model_name='timeline',
name='part',
... |
"""Validate system module
Used by the command validate-system
"""
import inspect
import importlib
import logging
import os
import sys
root_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../../')
def validate_system():
"""Main validation method
"""
validate_structure()
validate... |
import math
dias=int(input())
ano=math.floor(dias/365)
anores=dias%365
meses=math.floor(anores/30)
mesesres=anores%30
dias=math.floor(mesesres%30)
print('{} ano(s)'.format(ano))
print('{} mes(es)'.format(meses))
print('{} dia(s)'.format(dias))
|
"""Tests for basic flow of the system."""
import json
from typing import Any
from medtagger.definitions import LabelVerificationStatus, LabelElementStatus, LabelTool
from medtagger.repositories import (
datasets as DatasetsRepository,
label_tags as LabelTagsRepository,
tasks as TasksRepository,
)
from tes... |
import os
import sys
import copy
import pygame
from code.extensions.common import UITemplateLoaderExt
from code.render.glfunctions import *
from code.controllers.intervalcontroller import IntervalController
from code.controllers.menucontroller import MenuController
from code.controllers.timercontroller import Time... |
from flask import Flask
from flask import request
from flask import Flask, jsonify
from flask_cors import CORS
import base64
import requests
import time
import json
import math
import os
import configparser
import jwt
# read variables from config
credential = configparser.ConfigParser()
credential.read('webex_cred')
... |
from .info import *
|
from typing import Optional
from pydantic import BaseModel, Extra
class NewPendingOperationRequest(BaseModel, extra=Extra.forbid):
operationType: str
datasetName: str
description: str
class UpdatePendingOperationRequest(BaseModel, extra=Extra.forbid):
releaseStatus: str
description: Optional[st... |
# Global (retrieval) heads
from .heads import ArcMarginProduct
from .heads import ArcFace
from .heads import AdaCos
from .heads import CosFace
# Feature (embedding) pooling layers
from .pooling import GeneralizedMeanPooling2D
# DELG layers
from .delg import Attention
from .delg import Autoencoder
|
from django.conf import settings
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class Util:
def send_email(data):
# port = 587 # For starttls
# smtp_server = "smtp.gmail.com"
sender_email = settings.DEFAULT_FROM_EMAIL
... |
from enum import Enum
from lmath import FbToInt
from ltable import LuaTable
from lvm import LuaVM
arithoplist = [(j, i) for i, j in enumerate(['LUA_OPADD', 'LUA_OPSUB', 'LUA_OPMUL', 'LUA_OPMOD', 'LUA_OPPOW',
'LUA_OPDIV', 'LUA_OPIDI', 'LUA_OPBAN', 'LUA_OPBOR', 'LUA_OPBXO',
... |
#! /usr/bin/env python3
# example #1 - WiFi connection at boot
#from pynq.lib import Wifi
#
#port = Wifi()
#port.connect('your_ssid', 'your_password', auto=True)
# example #2 - Change hostname
#import subprocess
#subprocess.call('pynq_hostname.sh aNewHostName'.split())
# example #3 - blink LEDs (PYNQ-Z1, PYNQ-Z2, ZC... |
# static methods to load and compile OpenGL shader programs
from OpenGL.GL import *
import pygame # for loading images / texture data
class OpenGLUtils(object):
@staticmethod
def initializeShader(shaderCode, shaderType):
extension = '#extension GL_ARB_shading_language_420pack : require\n'
... |
import contextlib
import json
import logging
import os
from typing import List, Dict, Optional, Set
import requests.exceptions
import ripgrepy # type: ignore
from logsearch import zuul
LOG = logging.getLogger(__name__)
class BuildLogCache:
def __init__(self, log_cache_dir: str, zuul_api: zuul.API) -> None:
... |
def get_spans(df, partition, scale=None):
"""
:param df: the dataframe for which to calculate the spans
:param partition: the partition for which to calculate the spans
:param scale: if given, the spans of each column will be divided
by the value in `scale` for that colu... |
import os
from pathlib import Path
from chronologer import subprocess
from chronologer.config import config
from chronologer.executable import get_executable
from chronologer.typing import CommitHash
def benchmark(commit: CommitHash):
executable = get_executable(commit)
if not executable:
return
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 15:06:51 2021
@author: Alex
"""
import os #sistema operativo
import pandas as pd #gestionar datframes
import numpy as np #numeric python (vectores, matrices,...)
import matplotlib.py... |
"""Merging of normalized ClinVar TSV files."""
import datetime
import enum
import json
import re
import typing
from dateutil.parser import isoparse
import attr
import cattr
from .parse_clinvar_xml import DateTimeEncoder, ClinVarSet, VariationClinVarRecord, as_pg_list
HEADER_OUT = (
"release",
"chromosome",
... |
#!/usr/bin/python
from nltk.parse.bllip import BllipParser
from bllipparser.ModelFetcher import download_and_install_model
from nltk import word_tokenize, sent_tokenize
from nltk.tree import ParentedTree, Tree
from pymongo import MongoClient
from progressbar import ProgressBar
import numpy as np
import subprocess
clas... |
# -*- coding: utf-8 -*-
import sys
import os
from tutorials import basic
class Singleton1(object):
def __new__(cls, *args, **kwargs):
print("[+] Singleton1 __new__")
if not hasattr(cls, '_inst'):
cls._inst = super(Singleton1, cls).__new__(cls, *args, **kwargs)
return cls._inst... |
from botocore.vendored import requests
import json
import random
from datetime import date
def lambda_handler(event, context):
# 깃헙 graphql
git_url = "https://api.github.com/graphql"
headers = {"Content-Type": "application/json", "Accept": "application/vnd.github.inertia-preview+json",
"Aut... |
# import pymongo
# from pymongo import MongoClient
# def get_db_handle(db_name, host, port, username, password):
# client = MongoClient(host=host,
# port=int(port),
# username=username,
# password=password
# )
# ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 20:51:37 2020
@author: xuel12
"""
import os
os.chdir('/Users/xuel12/Documents/MSdatascience/CS7180AI/project/prosit/local_training/')
import re
import constants
def from_msp_prosit(ofile):
# Get a list of the keys for the datasets
... |
from tacx_speed import *
from flask import Flask
from flask import render_template
from flask_socketio import SocketIO, emit
from flask import Markup
import time
import eventlet
eventlet.monkey_patch()
app = Flask(__name__)
socketio = SocketIO(app)
thread = None
def background_thread():
wh... |
import signal
import subprocess
from typing import Optional, Tuple
from PIL import Image
from PIL.Image import Image as ImageType
from platypush.plugins.camera import CameraPlugin
from platypush.plugins.camera.ffmpeg.model import FFmpegCamera, FFmpegCameraInfo
class CameraFfmpegPlugin(CameraPlugin):
"""
Plu... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from Favorites.views import FavoriteCollegesView, FavoriteMajorsView
app_name = 'Favorites'
router = DefaultRouter()
router.register('colleges', FavoriteCollegesView, basename='colleges-list')
router.register('majors', FavoriteMajo... |
"""
Lasso_regulation_program
- train_data = 20대 총선 자료,
d = 더불어 민주당
s = 새누리당
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
from pandas import Series
from sklearn.model_selection import train_test_split
from sklearn.linear_model ... |
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
try:
from pip.req import parse_requirements
except:
from pip._internal.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
... |
from inception_resnet_v2 import *
from bnlstm import *
from hybrid import *
|
import pytest
import censere.models
class TestCreateTables:
def test_create_event_table(self, database):
database.bind( [ censere.models.Event ], bind_refs=False, bind_backrefs=False)
database.connect( reuse_if_open=True )
database.create_tables( [ censere.models.Event ] )
assert... |
# -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.data_object import DataObject
from ingenico.connect.sdk.domain.hostedmandatemanagement.definitions.hosted_mandate_info import HostedMandateInfo... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Isis(A10BaseClass):
"""Class Description::
Enable isis traps.
Class isis supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param isisOwnLSPPurge: {"default": 0, "o... |
from puq import *
def run(level=2):
# Declare our parameters here. Both are uniform on [-2, 2]
p1 = UniformParameter('x', 'x', min=-2, max=2)
p2 = UniformParameter('y', 'y', min=-2, max=2)
# Create a host
host = InteractiveHost()
# Example pbshost
# This says each process uses 1 cpu and ... |
_base_ = '/home/aad13694zb/mmsegmentation/configs/deeplabv3plus/deeplabv3plus_r50-d8_769x769_40k_cityscapes.py'
dataset_type = 'CarlaCityScapesDataset'
data_root = "/home/aad13694zb/carla-semantic-segmentation/working"
work_dir="/home/aad13694zb/carla-semantic-segmentation/working/outputs/deeplabv3plus/40k/lr_0.005/p... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Dict, List, Optional, Tuple
from detectron2.config import configurable
from detectron2.layers import ShapeSpec, cat, get_norm
from detectron2.modeling import PROP... |
import pytest
from rotkehlchen.tests.utils.exchanges import create_test_bitpanda
from rotkehlchen.tests.utils.factories import make_api_key, make_api_secret
@pytest.fixture(name='bitpanda_api_key')
def fixture_bitpanda_api_key():
return make_api_key()
@pytest.fixture(name='bitpanda_api_secret')
def fixture_bit... |
import sys, os
import numpy as np
from networks.vgg19 import Network
from misc.config import Config
from misc.misc import Misc
import cv2
# DIR_PATH
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
print 'Loading TEST data'
X = Misc.prepare_data_test_from_file(Config.PATH_TEST_CSV)
Xs = (X - 124.84467441020496)... |
#
# PySNMP MIB module Juniper-IPv6-Profile-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-IPv6-Profile-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:03:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
#!/usr/bin/evn python
# File name : auto.py
# Description : By detecting the distance through Ultrasonic,controlling the RPi car move to the four directons:the front,back,left and right,thus the car achieves automatic avoidance.
# Website : www.adeept.com
# E-mail : support@adeept.com
# Author : Willi... |
import time
import utils
from pyrogram import Client
from pyrogram.api import functions, types
from pyrogram.api.errors import FloodWait
from collections import namedtuple
USER = namedtuple('User', ['username', 'name', 'about'])
app = Client("account")
target = input('username чата без "@": ') # Target chann... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" generate_vars.py
"""
import codecs
import ipaddress
import json
import os
import subprocess
import sys
import yaml
COMMAND_DIR = os.path.abspath(os.path.dirname(__file__)) + "/"
def main():
fp = open(sys.argv[1])
data = yaml.safe_load(fp)
fp.close()
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class WrongVecError(Exception):
'''
Raised when an operation use empty or not same size vector.
Attributes:
value: error info
'''
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
|
"""Tools for graphical debugging
These are simple functions to draw the world state when something goes
wrong. They are not intended to make production-ready graphics or to
build a UI around, but instead focus on putting as much useful
information on the screen as possible.
"""
import numpy
import shapely.geometry
im... |
from flask import render_template,request,redirect,url_for
from . import main
from ..models import Articles,Sources
from ..requests import get_news,get_articles
@main.route('/')
def index():
'''
View root page function that returns the index page
'''
source_news = get_news()
# business_news = get_news('busin... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return -lim, lim
class Network(nn.Module):
def __init__(self, input_dim, hidden_in_dim, hidden_out_dim, output_dim, actor=Fals... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from copy import copy
import json
import argparse
from flask import Flask, render_template
import app_config
import app_utils
from app_utils import get_last_updated
from render_utils import make_context, smarty_filter, urlencode_filter
import slides
import static_app
imp... |
# This sample tests the type checker's handling of generic protocol types.
from typing import TypeVar, Protocol
T = TypeVar('T')
T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)
class Box(Protocol[T_co]):
def content(self) -> T_co:
...
box: Box[float]
second_box:... |
import numpy as np
import time
from urh.signalprocessing.FieldType import FieldType
from urh.util.Logger import logger
from urh.awre.components.Address import Address
from urh.awre.components.Component import Component
from urh.awre.components.Flags import Flags
from urh.awre.components.Length import Length
from urh.... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botbuilder.schema import Activity
from .metadata import Metadata
from .query_result import QueryResult
class QnAMakerTraceInfo:
""" Represents all the trice info that we collect from the Qn... |
#!/usr/bin/python
"""
This script is for setting up OAuth credentials for Google Analytics.
To use:
Visit https://code.google.com/apis/console/ and select "API Access".
If a client ID for an "installed application" hasn't been created, add one.
Click "Download JSON" in the box containing information about that client ... |
from copy import deepcopy
from itertools import permutations, chain
from asyncio import Queue
import asyncio
from typing import List, Tuple, cast
class IntCode:
def __init__(self, program_str: str, input_queue: Queue, output_queue: Queue):
self.mem = {i: int(v) for i, v in enumerate(program_str.split(",")... |
from gazette.spiders.base import FecamGazetteSpider
class ScEntreRiosSpider(FecamGazetteSpider):
name = "sc_entre_rios"
FECAM_QUERY = "cod_entidade:87"
TERRITORY_ID = "4205175"
|
"""
This module contains all files for a django deployment 'site'.
When called via the manage.py command, this folder is used as regular django setup.
"""
|
from typing import Dict, Union # isort:skip
from collections import OrderedDict
import os
from pathlib import Path
from catalyst import utils
from catalyst.core import Callback, CallbackNode, CallbackOrder, State
def _pack_state(state: State):
checkpoint = utils.pack_checkpoint(
model=state.model,
... |
# Generated by Django 2.1.9 on 2019-08-13 18:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20190813_1130'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='after_image',
)... |
from libs.PyxelArt import *
a = 2
b = a
c = 1
for loop in range(5) :
if a != 4 :
colorier(a,1)
else :
colorier(a,2)
a = a + 1
for loop in range(3) :
colorier(1,b)
colorier(7,b)
b = b + 1
colorier(4,7)
for loop in range(2) :
colorier(4-c,7-c)
colorier(4+c,7-c)
... |
from django.db import models
from hashlib import md5
class GenreManager(models.Manager):
"""Manager for managing the genres in meta"""
def create_genre(self, name: str):
genre = self.model(name=name)
genre.save(using=self._db)
return genre
class Genre(models.Model):
"""Model for... |
# %%
#######################################
def encode_base64(obj: object, no_newline=False):
"""Encodes the string / bytes string using BASE64.
Example:
>>> encode_base64('hello')\n
b'aGVsbG8=\\n'
>>> encode_base64('hello', no_newline=True)\n
b'aGVsbG8='
>>> encode_bas... |
import os
import pickle
import requests
STORAGE_FILE = "storage"
USER_AGENT = "uHoo/9.1 (iPhone; XS; iOS 14.4; Scale/3.00)"
class UHooSession(requests.Session):
"""Proxy class to listen for session changes and save to disk
Does not modify any of the parent's class original behavior. Instead it only watches
... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy.interpolate as spint
import scipy.spatial.qhull as qhull
import itertools
import MITgcmutils as mit
import f90nml
plt.ion()
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = Tr... |
"""Sherlock Tests
This module contains various tests.
"""
from tests.base import SherlockBaseTest
import unittest
class SherlockDetectTests(SherlockBaseTest):
def test_detect_true(self):
"""Test Username Existence Detection.
This test ensures that the mechanism of ensuring that a Username
... |
import datetime
import requests
import json
import time
base_ip = 'http://10.0.6.21' # Dia chi ip den k8s
base_port = '30312' # Dung lenh k get svc xem cua db
base_index = 'location_index_4' # Index dang su dung, xem trong configmap
base_type = 'full_location_type' # Type dang su dung, xem trong configmap
base_ur... |
import time
from machine import I2C
class AS3935:
"""A basic class used for interacting with the AS3935 lightning
sensor from a Raspberry Pi over I2C"""
def __init__(self, i2c, addr=0x00):
self._addr = addr
self._i2c = i2c
def calibrate(self, tun_cap=None):
"""Calibrate the l... |
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import os
from setuptools import setup, find_packages
requirements = [
# The core package.
'signac>=0.9.0',
# For the templated generation of (submission) scrip... |
import app as myapp
# This is just a simple wrapper for gunicorn to find your app.
# If you want to change the algorithm file, simply change "main"
# above to the new file.
app = myapp.app
|
from dialRL.dataset.data_file_generator import DataFileGenerator
from dialRL.dataset.rf_generator import RFGenerator
# from dialRL.dataset.run_rf_algo import run_rf_algo
__all__ = ['DataFileGenerator', 'RFGenerator']
|
import json
from twisted.python.filepath import FilePath
from base_plugin import SimpleCommandPlugin
from plugin_manager import FatalPluginError
class StarboundConfigManager(SimpleCommandPlugin):
name = 'starbound_config_manager'
depends = ['command_plugin']
def activate(self):
super(StarboundC... |
from django.shortcuts import get_object_or_404, render, RequestContext, render_to_response
from repo.forms import UserForm, UserEditForm
from reg.forms import MyRegistrationForm
from reg.models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.views import password_reset
from djang... |
from flask.cli import FlaskGroup
from run import app
from todo.extension import database
cli = FlaskGroup(app)
@cli.command('create_database')
def create_database():
database.drop_all()
print('Dropped all tables...')
database.create_all()
print('Created all tables...')
database.session.commit(... |
# -*- coding: utf-8 -*-
import queue
class FakeOs:
'''用于重定向 os.system'''
def __init__(self):
self.call_q = queue.LifoQueue() # (stack)
def system(self, cmd):
self.call_q.put(cmd)
return 0
def readline(self):
if self.call_q.empty():
return None
els... |
from django.apps import AppConfig
class SocialmessagesConfig(AppConfig):
name = 'socialmessages'
|
import pickle
import argparse
from pdb import set_trace
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--category", help="category id", default=67)
args = parser.parse_args()
cid = str(args.category)
set_trace()
with open('data/parsed/bitcointalk_{}_parsed'.format(cid), 'rb') as f:
pickle_data = pi... |
import MDSplus
import time
import threading
import math
import numpy as np
class CAENWAVECARD(MDSplus.Device):
"""
CAEN VME V1470 ADC Cards class for DAQ
"""
parts = [
{"path": ":COMMENT", "type": "text", "options": ("no_write_shot",)},
{"path": ":RUNNING", "type": "numeric", "options... |
'''
Implements the RTS Target backstore and storage object classes.
This file is part of LIO(tm).
Copyright (c) 2011-2014 by Datera, 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://... |
#!/usr/bin/env python3
import fileinput
import subprocess
import os
def main():
"""Attempt IPv6 ping to every host listed in the input file.
The input file is specified as the only command line argument"""
with open(os.devnull, "wb") as limbo:
for line in fileinput.input():
line= line.... |
import operator
from transpiler.Operations.Binary import Binary, SimpleBinary
from transpiler.Operations.Unary import Unary
from transpiler.Imports import UINT256_MODULE
from transpiler.utils import uint256_to_int256, int256_to_uint256
class And(SimpleBinary):
def __init__(self):
super().__init__(operator... |
from django.conf import settings
config = settings.CSV2_CONFIG
from django.shortcuts import render, get_object_or_404, redirect
from django.views.decorators.csrf import requires_csrf_token
from django.http import HttpResponse
from django.core.exceptions import PermissionDenied
from cloudscheduler.lib.view_utils impo... |
import logging
import os
from pathlib import Path
from typing import Any, List, Tuple, Union
import jsons
import numpy as np
import torch
# Update serializaiton rules for `jsons` module used by `serialize` function (below).
jsons.set_serializer(lambda x, **kwargs: x.tolist(), torch.Tensor) # type: ignore
jsons.set_s... |
import logging
import math
import random
from collections import defaultdict
from queue import Queue
from typing import Any, Callable, Dict, List
import numpy as np
from gym import spaces
from landia import gamectx
from landia.clock import clock
from landia.common import Base, Vector2
from landia.event import DelayedE... |
def add_native_methods(clazz):
def registerNatives____(a0):
raise NotImplementedError()
def defineClass0__java_lang_String__byte____int__int__java_security_ProtectionDomain__(a0, a1, a2, a3, a4, a5):
raise NotImplementedError()
def defineClass1__java_lang_String__byte____int__int__java_sec... |
"""
You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be ex... |
from typing import Text, Any, Dict, List, Union, Optional
import stanza
from cachetools import cached
from sagas.conf.conf import cf
@cached(cache={})
def get_nlp(lang:Text, package:Text='default', processors:Text=None,
pretokenized:bool=False):
processors = processors or {}
alias={'zh':'zh-hans',... |
#!/usr/bin/env python
#
# Copyright 2007 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.