content stringlengths 4 20k |
|---|
"""DSIG data item."""
from .. import variables
from .base import DataItemBase
class DSID(DataItemBase):
"""
Data set ID.
:Types:
- :class:`String <secsgem.secs.variables.String>`
- :class:`I8 <secsgem.secs.variables.I8>`
- :class:`I1 <secsgem.secs.variables.I1>`
- :class:`I2 <... |
# Filip Keri
# Average_Epochs.py
# A script that takes in a .par file, a .tim file, and an output directory
# as a result, it creates a new file with TOAs compressed in epochs, stored in output directory
# sample input:
# python Average_Epochs.py /Users/fkeri/Desktop/B1855+09_NANOGrav_9yv0.par /Users/fkeri/Desktop/B185... |
#!/usr/bin/env python
import numpy as np
import ctypes as c
import itertools
from multiprocessing import Pool
gdata = None
glabels = None
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2014, EESI Laboratory (Drexel University)"
__credits__ = ["Gregory Ditzler"]
__license__ = "GPL"
__version__ = "0.1.0"
_... |
"""Support for the Twitch stream status."""
import logging
from requests.exceptions import HTTPError
from twitch import TwitchClient
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity... |
from scipy import sparse
from sklearn.base import BaseEstimator
from sklearn.linear_model import Ridge
from sklearn.metrics import f1_score
import numpy as np
class LinRegStack(BaseEstimator):
def __init__(self, nn, verbose=0, fit_base=True):
self.fit_base = fit_base
self.verbose = verbose
... |
import warnings
# Show deprecation warnings
warnings.filterwarnings("always", category=DeprecationWarning, module="locust")
def check_for_deprecated_task_set_attribute(class_dict):
from locust.user.task import TaskSet
if "task_set" in class_dict:
task_set = class_dict["task_set"]
if issubcl... |
"""
Tools for extracting and displaying image patches.
"""
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Lucas Theis <<EMAIL>>'
__docformat__ = 'epytext'
__version__ = '1.0.0'
from numpy import array, asarray, floor, ceil, sqrt, zeros
from numpy.random import uniform
i... |
def WriteFix():
scriptName = nuke.root().name()
length = len(scriptName)
filmCheck = scriptName[3]
if length >= 5:
if str(filmCheck) == "F":
Task = scriptName[-10]+scriptName[-9]+scriptName[-8]
if str(Task) == "pnt":
CreateCrop = nuke.createNode("Crop... |
from aws import Action
service_name = 'Amazon CloudSearch'
prefix = 'cloudsearch'
BuildSuggesters = Action(prefix, 'BuildSuggesters')
CreateDomain = Action(prefix, 'CreateDomain')
DefineAnalysisScheme = Action(prefix, 'DefineAnalysisScheme')
DefineExpression = Action(prefix, 'DefineExpression')
DefineIndexField = Act... |
from __future__ import unicode_literals
import numpy as np
import re
import codecs
from random import shuffle
genre_vectors = {
'folk-country': [1, 0, 0, 0, 0, 0, 0, 0],
'electronica': [0, 1, 0, 0, 0, 0, 0, 0],
'metal': [0, 0, 1, 0, 0, 0, 0, 0],
'pop': [0, 0, 0, 1, 0, 0, 0, 0],
'danc... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2014 Alex Forencich
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 righ... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Post.texte'
db.delete_column('blogs_post', 'texte')
# Adding field 'Post.text'
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schools', '0007_auto_20170321_0937'),
]
operations = [
migrations.RemoveField(
model_name='answerinstitution',
... |
__source__ = 'https://leetcode.com/problems/unique-paths/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/unique-paths.py
# Time: O(m * n)
# Space: O(m + n)
# DP
#
# Description: Leetcode # 62. Unique Paths
#
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diag... |
#-*- coding: utf-8 -*-
import re
import string
import glob
import os.path
import io
header = """
# TIL
> Today I Learned
오늘 배운 내용을 간결하게 정리하여 모아둔다.
---
"""
footer = """
---
## Rules
* Directory and file would be lowercase.
* Follow GFM(Github Flavored Markdown)
## Usage
### Generate `README.md`
```
$ python3... |
import re
import subprocess
import unittest
import os
import zipfile
import shutil
from xml.etree import ElementTree
import json
import sys
sys.path.append("../")
import comm
class TestCrosswalkApptoolsFunctions(unittest.TestCase):
def invokeCrosswalkPkg(self, params=None):
params = params or []
... |
"""Conv2D spatial pack implementation for ARM CPU"""
from __future__ import absolute_import as _abs
import tvm
from tvm import te
from tvm import autotvm
from .. import nn
from ..util import get_const_tuple
from ..nn.util import get_const_int, get_pad_tuple
def conv2d_spatial_pack_nchw(cfg, data, kernel, strides, pad... |
import string
import random
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.forms import PasswordResetForm
from django.utils.translation import ugettext_lazy as _
from .models import DeployUser
class UserChangeForm(forms.M... |
"""
Tests for random topology parameter distributions. This is an implementation
of the Kolmogorov-Smirnov test [1] to check that the distribution of weights
fits the expected distribution to level alpha=0.05 when using random
parameters. Also serves as a regression test for ticket #687.
[1] http://www.itl.nist.gov/di... |
'''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
This program 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, either version 3 of the License, or
(at your option) any later version.
... |
#!/usr/bin/env python
from DAX3 import *
# Create a DAX
dispel4py = ADAG("dispel4py")
# Add some metadata
# Add input file to the DAX-level replica catalog
#python -m dispel4py.new.processor simple curl-countlines.py -i 10
#python -m dispel4py.new.processor simple split-countwords.py -d '{"split": [{"input": "myfile... |
from django.db import models
from django.utils import timezone
from accounting.models import LedgerAccount, LedgerEntry
class MembershipLevel(models.Model):
"""Descriptor for membership costs and privileges.
:param name: Name of membership level.
:param cost: Cost of this membership level.
:param pe... |
# -*- coding: utf-8 -*-
from pandas.compat import range
import pandas.util.testing as tm
from pandas import read_csv
import os
import nose
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
import pandas.tools.rplot as rplot
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))... |
from openerp import models
class StockMove(models.Model):
_inherit = 'stock.move'
def _find_moves_from_stock_planning(
self, company, to_date, from_date=None, category=None, template=None,
product=None, location_id=None, location_dest_id=None):
cond = [('company_id', '=', company.... |
"""
Holds satosa routing logic
"""
import logging
import re
from .context import SATOSABadContextError
from .exception import SATOSAError
from .logging_util import satosa_logging
logger = logging.getLogger(__name__)
STATE_KEY = "ROUTER"
class SATOSANoBoundEndpointError(SATOSAError):
"""
Raised when a given... |
from ctypes import *
from ctypes.util import find_library
import os
import logging
import platform
import re
import sys
import tempfile
import filecmp
import shutil
import codecs
def gen_enum_value(value):
return 'k' + value[0].upper() + value[1:]
class EnumType:
name = ''
enumValues = []
def __init__... |
"""
==========================
Random walker segmentation
==========================
The random walker algorithm [1]_ determines the segmentation of an image from
a set of markers labeling several phases (2 or more). An anisotropic diffusion
equation is solved with tracers initiated at the markers' position. The loca... |
import pygad as pg
import pygad.plotting
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
import utils
import glob
from multiprocessing import Pool
filename = __file__
def plot(args):
halo = args[0]
definition = args[1]
print args
path = '/ptmp/mpa/naab/REFINED/%s/SF_X/4x-2ph... |
# -*- coding: utf-8 -*-
from logging import getLogger
from django.utils import timezone
from celery.states import SUCCESS, FAILURE
from api.api_views import APIView
from api.exceptions import ObjectNotFound, TaskIsAlreadyRunning
from api.task.utils import task_log
from api.task.response import SuccessTaskResponse, Fai... |
from __future__ import print_function
import datetime
from dynamicserialize.dstypes.com.raytheon.uf.common.dataquery.requests import RequestConstraint
from dynamicserialize.dstypes.com.raytheon.uf.common.time import TimeRange
from awips.dataaccess import DataAccessLayer as DAL
from awips.ThriftClient import ThriftReque... |
"""Support for deCONZ lights."""
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_HS_COLOR,
ATTR_TRANSITION,
EFFECT_COLORLOOP,
FLASH_LONG,
FLASH_SHORT,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_COLOR_TEMP,
S... |
from ._application_gateways_operations import ApplicationGatewaysOperations
from ._application_gateway_private_link_resources_operations import ApplicationGatewayPrivateLinkResourcesOperations
from ._application_gateway_private_endpoint_connections_operations import ApplicationGatewayPrivateEndpointConnectionsOperation... |
import nova.conf
from nova.tests.functional.api_sample_tests import test_servers
CONF = nova.conf.CONF
class AdminPasswordJsonTest(test_servers.ServersSampleBase):
extension_name = 'os-admin-password'
def test_server_password(self):
uuid = self._post_server()
subs = {"password": "foo"}
... |
import spot
v1 = spot.trival()
v2 = spot.trival(False)
v3 = spot.trival(True)
v4 = spot.trival_maybe()
assert v1 != v2
assert v1 != v3
assert v2 != v3
assert v4 != v2
assert v4 != v3
assert v2 == False
assert True == v3
assert v4 == spot.trival_maybe()
assert v3
assert -v2
assert not -v1
assert not v1;
assert not -v3
... |
"""Test suite for pymongo, bson, and gridfs.
"""
import os
import socket
import sys
from pymongo.common import partition_node
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
from unittest2 import SkipTest
else:
import unittest
from unittest import SkipTest
import warnings
from functoo... |
"""Database Processing/Rename Event Types"""
#-------------------------------------------------------------------------
#
# GNOME modules
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
from gi.repository import GObject
#--------------------------------------... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from collections import defaultdict
from pants.base.build_environment import get_buildroot
from pants.base.build_file import BuildFile
class LazySourceMap... |
#!/usr/bin/env python
# -*- coding: UTF8 -*-
'''
justicker
~~~~~~~~~
A stock ticker for the Justcoin trading platform. Web front-end in Flask, data
stored in MongoDB.
This "main" script manages configuration, the web server, and scheduled tasks.
:copyright: (c) 2013, Douglas Watson <<EMAIL>>
:license: MIT license, s... |
from django.test import TestCase
from rest_framework import status
from rest_framework.response import Response
from django.test.client import RequestFactory
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.authentication import BasicAuthentication
from... |
from dynamics.dynamics.turbine_governors.turbine_governor import TurbineGovernor
from google.appengine.ext import db
# >>> imports
class GovSteamSGO(TurbineGovernor):
# <<< gov_steam_sgo.attributes
# @generated
# >>> gov_steam_sgo.attributes
# <<< gov_steam_sgo.references
# @generated
# >>>... |
import time
import threading
import socket
PORT = 4567
from gda.device.scannable import ScannableMotionWithScannableFieldsBaseTest
#import scannable.vrmlModelDriver
#reload(scannable.vrmlModelDriver);from scannable.vrmlModelDriver import \
# VrmlModelDriver, LinearProfile, MoveThread
#fc=VrmlModelDriver(
# 'fc... |
# -*- coding: utf-8 -*-
import click
from tabulate import tabulate
from ircb.lib.async import coroutinize
from ircb.storeclient import NetworkStore
@click.group(name='networks')
def network_cli():
"""Manager networks"""
from ircb.storeclient import initialize
initialize()
@click.command(name='create')... |
from random import randrange
from myhdl import Signal
from myhdl import intbv
from myhdl import traceSignals
from myhdl import Simulation
from myhdl import bin, instances
from myhdl import enum
from myhdl import delay, instance, always, always_seq, always_comb
from myhdl import toVerilog, toVHDL
t_ALU_FUNCTION = e... |
def get_relationships(df, columns=None):
columns = columns if columns is not None else df.columns
from itertools import product
for col_i, col_j in product(columns, columns):
if col_i == col_j:
continue
print(col_i, col_j, get_relation(df, col_i, col_j))
def get_relation(df, co... |
from qtpy.QtCore import QAbstractTableModel, Qt, Signal, QModelIndex
default_table_columns = ["Run", "Group/Pairs", "Fit status", "Chi squared"]
RUN_COLUMN = 0
GROUP_COLUMN = 1
FIT_STATUS_COLUMN = 2
FIT_QUALITY_COLUMN = 3
NUM_DEFAULT_COLUMNS = len(default_table_columns)
default_fit_status = "No fit"
default_chi_square... |
#! python
# * * * * * * * * * * * * * * * * * * *
# * *
# * * * http://www.caddit.net * * *
# * ... |
from django.template import RequestContext
from django.core.mail import EmailMultiAlternatives
from django.shortcuts import render_to_response, get_object_or_404
from forms import GuestForm, RegistrationForm
from models import Event, Guest, Registration
from django.utils import timezone
from django.template.loader impo... |
from .resource import Resource
class VirtualNetwork(Resource):
"""Virtual Network resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource Identifier.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: ... |
import argparse
import sys
from cyber.python.cyber_py3.record import RecordReader
from modules.canbus.proto import chassis_pb2
from modules.control.proto import control_cmd_pb2
from modules.drivers.proto import pointcloud_pb2
from modules.perception.proto import perception_obstacle_pb2
from modules.planning.proto impo... |
import unittest
import common
import lib.config
class ConfigBaseTests:
fmt = None
@classmethod
def setUpClass(cls):
if cls is ConfigBaseTests:
raise unittest.SkipTest("Skip BaseTest tests, it's a base class")
super(ConfigBaseTests, cls).setUpClass()
def config(self, name)... |
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
fmt = 'TreeNode(data={}, left={}, right={})'
return fmt.format(self.data, self.left, self.right)
class BinarySearchTree:
def __i... |
"""Support for NuHeat thermostats."""
import asyncio
from datetime import timedelta
import logging
import nuheat
import requests
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
CONF_DEVICES,
CONF_PASSWORD,
CONF_USERNAME,
HT... |
import toppra as ta
import toppra.constraint as constraint
import toppra.algorithm as algo
import numpy as np
import matplotlib.pyplot as plt
import time
import openravepy as orpy
ta.setup_logging("INFO")
def main():
# openrave setup
env = orpy.Environment()
env.Load("robots/barrettwam.robot.xml")
env... |
import os
import re
import sys
import shutil
import ftplib
import hashlib
import tarfile
import getpass
import fnmatch
import tempfile
import configparser
from zgitignore import ZgitIgnore, normalize_path
local_storage = ''
use_local = True
ftp_host = ''
ftp_path = ''
ftp_user = ''
ftp_pass = ''
project = os.path.rel... |
"""
This module contains general purpose URL functions not found in the standard
library.
Some of the functions that used to be imported from this module have been moved
to the w3lib.url module. Always import those from there instead.
"""
import posixpath
import re
from urllib.parse import ParseResult, urldefrag, urlp... |
# -*- coding: utf-8 -*-
from plexapi import media, utils
from plexapi.base import Playable, PlexPartialObject
class Audio(PlexPartialObject):
""" Base class for audio :class:`~plexapi.audio.Artist`, :class:`~plexapi.audio.Album`
and :class:`~plexapi.audio.Track` objects.
Attributes:
a... |
"""BibFormat element - Prints 260b field information for CIP data
"""
import cgi
import re
def format_element(bfo, prefix, suffix):
publisher = ''
publisher = bfo.field('260%%b')
if len(publisher) > 0:
if publisher[-1] == ',':
publisher = publisher[:-1]
#publisher ... |
from tempfile import NamedTemporaryFile
from os import path
from urlparse import urlparse
from contextlib import closing
import binascii
import calendar
import logging
import os
import re
import subprocess
import time
import uuid
import json
import urllib2
import arrow
try:
from eventlet.green.subprocess import ... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program 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, either version 3 of the License, or
(at your option) any later version.
T... |
#!/usr/bin/env python
import re
import os
import argparse
header = """<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Physical Computing Exercises</title>
<link rel="stylesheet" type="text/css" href="../support/css/physcomp.css" />
</head>
<body>
<h2>Physical Computing... |
"""
cfbrank -- A college football ranking algorithm
conference.py: Defines the Conference class for generating rankings
and other statistical information on an athletic conference as a
whole.
Written by Michael V. DePalatis <<EMAIL>>
cfbrank is distributed under the terms of the GNU GPL.
"""
class Conference:
"... |
class TreeNode:
def __init__(self,val=0):
self.val=val
self.left=None
self.right=None
self.numOfNodes=1
self.combinations=1
class Solution:
def numOfWays(self, nums: List[int]) -> int:
root=TreeNode(nums[0])
def insertNode(root, num):
... |
from __future__ import print_function
from hyperledger.client import Client
# import base64
# import json
import sys
import time
import timeit
# from timeit import Timer
API_URL = 'http://127.0.0.1:5000'
DEPLOY_WAIT = 15
def query(chaincode_name, arg_list, validate=False):
"""
Query a list of values.
... |
from nslocapysation.classes.localized_string import LocalizedString
class DynamicLocalizedString(LocalizedString):
"""
A subclass of LocalizedString, whose instances represent
localized strings that are used with a dynamic key
(i.e. some variable as key).
Those are special because you need to chec... |
import copy
import time
import unittest
import command
import config
import mle
import node
DUT_LEADER = 1
DUT_ROUTER1 = 2
class Cert_5_5_1_LeaderReboot(unittest.TestCase):
def setUp(self):
self.simulator = config.create_default_simulator()
self.nodes = {}
for i in range(1,3):
... |
import json
from zdict.dictionary import DictBase
from zdict.exceptions import NotFoundError
from zdict.models import Record
class JishoDict(DictBase):
# Change the url below to the API url of the new dictionary.
# Need to keep the `{word}` for `_get_url()` usage.
API = 'http://jisho.org/api/v1/search/w... |
import logging
import time
import sqlalchemy as sql
from sqlalchemy import create_engine
from sqlalchemy.exc import DisconnectionError
from sqlalchemy.orm import sessionmaker, exc
from quantum.api.api_common import OperationalStatus
from quantum.common import exceptions as q_exc
from quantum.db import model_base, mod... |
from oslo_config import cfg
from oslo_db import options as oslo_db_options
from nova.conf import paths
_DEFAULT_SQL_CONNECTION = 'sqlite:///' + paths.state_path_def('nova.sqlite')
_ENRICHED = False
# NOTE(markus_z): We cannot simply do:
# conf.register_opts(oslo_db_options.database_opts, 'api_database')
# If we reu... |
from environmentbase.template import Template
import environmentbase.resources as res
from environmentbase.networkbase import NetworkBase
from environmentbase.environmentbase import EnvConfig
from troposphere import Ref, Parameter, GetAtt, Output, Join, rds, ec2
class RDS(Template):
"""
Adds an RDS instance.
... |
import bisect
import numpy as np
import math
# spline function modified from
# from looptools 4.5.2 done by Bart Crouch
# kept as it is used in older nodes
# calculates natural cubic splines through all given knots
def cubic_spline(locs, tknots):
knots = list(range(len(locs)))
n = len(knots)
if n < 2:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from GestureAgents.Recognizer import Recognizer, newHypothesis
from GestureAgents.Events import Event
from GestureAgentsTUIO.Tuio import TuioCursorEvents
from GestureAgents.Agent import Agent
import math
class AgentZoomRotate(Agent):
eventnames = ("newZoomRotate", "... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Project.theme'
db.delete_column(u'organisation_project'... |
from typing import Dict, Optional
import fsui
from fscore.system import System
from fsgamesys.platforms.platform import Platform
from fswidgets.widget import Widget
from launcher.context import get_config, useInputService
from launcher.devicemanager import DeviceManager
from launcher.gui.components.inputportdevicesele... |
from __future__ import print_function
import types
import numpy as np
import config
from context import context_length
from expr import (FunctionExpr, not_hashable,
getdtype, as_simple_expr, as_string,
get_missing_value, ispresent, LogicalOp, AbstractFunction,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import ebstall.util as util
from sarge import run, Capture, Feeder
from ebclient.eb_utils import EBUtils
from datetime import datetime
import time
import sys
import types
import ebstall.errors as errors
import subprocess
import shutil
import re
import json
import... |
"""
Common functions for ADS-B and Mode-S EHS decoder
"""
import math
# the polynominal generattor code for CRC
GENERATOR = "1111111111111010000001001"
def hex2bin(hexstr):
"""Convert a hexdecimal string to binary string, with zero fillings. """
scale = 16
num_of_bits = len(hexstr) * math.log(scale, 2)
... |
#!/usr/bin/env python
import os, sys, subprocess, argparse
__all__ = ['Ansible']
class Ansible(object):
def __init__(self, run_path=None, site_path='site.yml'):
self.run_path = run_path
self.site_path = site_path
def __call__(self):
self.check_ansible_version()
self.check_a... |
import os
import sys
sys.path.append(os.path.abspath(os.pardir))
import helper
def eval(pred_values, true_values, metric):
total_score = 0
for index in range(len(pred_values)):
total_score += metric(pred_values[index], true_values[index])
return total_score
ex1 = [[[0.2], [0.5]], [[-0.4], [-0.1]... |
import abc
import time
from email.utils import parsedate
class PostBase(object):
"""Represents a generic post on a social network."""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def content(self):
return 'Content'
@abc.abstractproperty
def time_posted(self):
return int(... |
"""
Output control utilities.
"""
import warnings
from functools import wraps
from fabric.api import env
from fabric.state import output
from fabric.utils import warn
def with_output(verbosity=1):
"""
Decorator that configures output verbosity.
"""
def make_wrapper(func):
@wraps(func)
... |
from odoo import models, fields, api
from odoo.http import request
class AuditlogtHTTPSession(models.Model):
_name = 'auditlog.http.session'
_description = u"Auditlog - HTTP User session log"
_order = "create_date DESC"
display_name = fields.Char(
u"Name", compute="_compute_display_name", sto... |
"""
Module for scope operations
"""
import sys
import struct
import inspect
import datetime
import itertools
import pprint
import numpy as np
import pandas
import pandas as pd # noqa
from pandas.compat import DeepChainMap, map, StringIO
from pandas.core.base import StringMixin
import pandas.core.computation as comp... |
"""
A newforms widget and field to allow multiple file uploads.
Created by Edward Dale (www.scompt.com)
Released into the Public Domain
"""
from django.utils.datastructures import MultiValueDict
from django.utils.translation import ugettext
from django.forms.fields import Field, EMPTY_VALUES
from django.core.files.up... |
"""
Distutils convenience functionality.
Don't use this outside of Twisted.
Maintainer: Christopher Armstrong
"""
from distutils.command import build_scripts, install_data, build_ext
from distutils.errors import CompileError
from distutils import core
from distutils.core import Extension
import fnmatch
import os
imp... |
import socket
import threading
import logging
from SocketServer import TCPServer, ThreadingMixIn, BaseRequestHandler
from core.responder.packet import Packet
from core.responder.odict import OrderedDict
from core.responder.common import *
mitmf_logger = logging.getLogger("mitmf")
class FTPServer():
def start(self... |
import pytest
import numpy as np
from scipy.stats import norm
from hyperspy.signals import Signal2D, BaseSignal
from hyperspy._signals.lazy import LazySignal
from hyperspy.decorators import lazifyTestClass
from hyperspy.signal_tools import PeaksFinder2D
def _generate_dataset():
coefficients = np.array(
[... |
"""
SAMPL dataset loader.
"""
import os
import deepchem as dc
from deepchem.molnet.load_function.molnet_loader import TransformerGenerator, _MolnetLoader
from deepchem.data import Dataset
from typing import List, Optional, Tuple, Union
SAMPL_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/SAMP... |
'''This program 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, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be usef... |
"""handles mongodb functions
schema of the database in json format
{'name': (string),
'password: (string),
'phone': (string),
'authenticated': (boolean),
'alarm': {'time': (datetime.datetime),
'lines': (iter(Strings))}}
Some values can be None
{'name': (cannot be None),
'password: (None),
'phone': (... |
import re
import requests
from bs4 import BeautifulSoup
from cloudbot import hook
rfc_re = re.compile(r"https?://(?:tools\.ietf\.org/\w+/|www\.rfc-editor\.org/\w+/)rfc(\d+){,4}")
BASE_URL = "https://tools.ietf.org/html/rfc{}"
def get_info(rfc_id, show_url=False):
url = BASE_URL.format(rfc_id)
# Only reque... |
from citrination_client.search.pif.query.core.base_object_query import BaseObjectQuery
from citrination_client.search.pif.query.core.field_operation import FieldOperation
from citrination_client.search.pif.query.core.units_normalization import UnitsNormalization
class ValueQuery(BaseObjectQuery):
"""
Class to... |
from pytz import timezone
import six
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import timeutils
from cinder.i18n import _LW
from cinder import rpc
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class ImageVolumeCache(object):
def __init__(self, db, volume_api, max_cach... |
import os
import unittest
from barf.analysis.basicblock import CFGRecoverer
from barf.analysis.basicblock import ControlFlowGraph
from barf.analysis.basicblock import RecursiveDescent
from barf.analysis.basicblock.basicblock import BasicBlock
from barf.arch import ARCH_X86_MODE_32
from barf.arch.x86.x86base import X86... |
# coding: utf8
# 基础request封装, 约定:
# 记录用户: 安全cookie保存用户id, key(token), cache保存用户对象(使用cpickle.dumps序列化对象), 每次更新用户信息需要及时更新缓存
# 登录: 在config中设置登录url, 需要登录才能访问的接口需要添加login_required()修饰器即可, 默认web模式
from tornado.web import RequestHandler, MissingArgumentError, HTTPError
import json
from config import configs
class Request... |
"""
===========
N2H+ fitter
===========
Reference for line params:
Daniel, F., Dubernet, M.-L., Meuwly, M., Cernicharo, J., Pagani, L. 2005, MNRAS 363, 1083
http://www.strw.leidenuniv.nl/~moldata/N2H+.html
http://adsabs.harvard.edu/abs/2005MNRAS.363.1083D
Does not yet implement: http://adsabs.harvard.edu/abs/2010Ap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Rhythmic feature extraction'''
import numpy as np
import scipy.signal
import six
from .. import util
from ..core.audio import autocorrelate
from ..util.exceptions import ParameterError
__all__ = ['tempogram']
# -- Rhythmic features -- #
def tempogram(y=None, sr=22... |
import os
import psycopg2
import nltk.data
from dueling_lstms import compute_scale_factor, label_sentences, reload_model, SourceStance
from dotenv import load_dotenv, find_dotenv
from topic_scoring import compute_sim, load_word2vec
def connect():
load_dotenv(find_dotenv())
PASSWORD = os.getenv("PASSWORD")
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 15 22:18:08 2014
@author: Jiri
Fetch time-series of snow coverage
from the MODIS_TERRA GIBS WMTS
Requires: pyPNG
"""
import math
import datetime
import png
import urllib2
import pandas as pd
import numpy as np
"""
Convert (lat, lon) to the proper tile number
Taken fr... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from trackma import utils
try:
LONG_DESCRIPTION = open("README.rst").read()
except IOError:
LONG_DESCRIPTION = __doc__
NAME = "Trackma"
REQUIREMENTS = []
EXTRA_REQUIREMENTS = {
'curses': ['urwid'],
'GTK' : ['PyGTK', 'Pillow'],
'Qt'... |
from functools import wraps
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask_login import current_user
from flask_login import login_user
from requests.utils import quote
import config
import database.user
from constants.api import *
from uri.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.