content stringlengths 5 1.05M |
|---|
import numpy as np
import xarray as xr
from xbitinfo import get_keepbits
from . import _skip_slow, ensure_loaded, parameterized, randn, requires_dask
class GetKeepbits:
"""
Benchmark time and peak memory of `get_keepbits`.
"""
# https://asv.readthedocs.io/en/stable/benchmarks.html
timeout = 30.... |
import click
import time
@click.group()
def cli():
pass
@cli.command()
@click.option('--interval', default=1000, help='interval of refreshing (milliseconds)')
@click.option('--show_length', default=True, type=click.BOOL, help='whether show file length')
@click.option('--show_line', default=True, type=click.BOOL, h... |
from decimal import Decimal
import logging
import asyncio
import pandas as pd
from typing import List, Dict, Tuple, Optional
from hummingbot.core.utils.async_utils import safe_ensure_future
from hummingbot.core.clock import Clock
from hummingbot.core.data_type.limit_order import LimitOrder
from hummingbot.core.data_typ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import cmapPy.pandasGEXpress.parse as parse
import numpy as np
import matplotlib.pyplot as plt
# In[2]:
input_dir = '../0A.download-data/data/'
output_dir = 'data/'
# In[3]:
phase1_gctoo = parse.parse(input_dir + 'GSE92742_Broad_LINCS_Level5_... |
"""Reports doit execution status/results"""
import sys
import time
import datetime
import json
from io import StringIO
class ConsoleReporter(object):
"""Default reporter. print results on console/terminal (stdout/stderr)
@ivar failure_verbosity: (int) include captured stdout/stderr on failure
... |
from .course import Course
from .exam import Exam
|
class Claim():
def __init__(self, claim_string):
claim_props = claim_string.split()
self.id = int(claim_props[0][1:])
position = claim_props[2].split(',')
self.left = int(position[0])
self.top = int(position[1][:-1])
dimensions = claim_props[3].split('x')
self... |
from os.path import join
# Main data and script locations
BPHO_DIR = '/imaging3/owenlab/bpho'
REPO_DIR = '/home/bpho/Documents/MSc_Research-Project'
# Common folders
BIOBANK_LABELS = join(BPHO_DIR, 'Biobank Labels')
SCRATCH_DATA = join(REPO_DIR, 'scratch_data')
# Power atlas labels
RAW_POWER = join(SCRATCH_DATA, 'po... |
import pytest
from orchestral_tutti_chord_database import pitch
from orchestral_tutti_chord_database.pitch import Pitch, Interval
class TestAccidental:
@pytest.mark.parametrize(
"s, x",
[
pytest.param("", 0, id="empty"),
pytest.param(["#", "##"], [1, 2], id="sharp"),
... |
import numpy as np
from voucher_opt.config.global_parameters import GlobalParameters
from voucher_opt.constants import CONTROL, EXPLORATION, LOGPROB, ACTION_CODE, SEGMENT
from voucher_opt.pipelines.bandit_agent import PREDICTION_COLUMNS
def set_experiment_groups(df, global_parameters: GlobalParameters):
control_... |
#!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # output a string.
colors = ['red','orange','yell... |
#estagio/main/apps.py
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class MainConfig(AppConfig):
name = "estagio.main"
verbose_name = _("Main")
def ready(self):
try:
pass
except ImportError:
pass |
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant, QModelIndex
from typing import List
from .animal import Animal
from .arimr_data import save_report_file, save_traces_file
header = ['Nr stada', 'Nr identyfikatora', 'Status pobierania danych', 'Nr paszportu', 'Status paszportu',
... |
# mysolution
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
if not haystack:
return -1
l=len(haystack)
l1=len(needle)
for i in range(l-l1+1):
if haystack[i:i+l1]==needle:
return ... |
# -*- 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):
# Adding field 'Board.slug'
db.add_column(u'organisation_board', 'slug',
... |
# -*- coding: utf-8 -*-
# Copyright 2020 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 o... |
import sys
import argparse
from pathlib import Path
SAMPLES_DIR = Path(sys.argv[0]).parent
EXCLUDE_EXT = ['.user']
TEMPLATE_NAME = 'ProjectTemplate'
def create_project(name):
# Source and destination directories.
src_dir = SAMPLES_DIR / TEMPLATE_NAME
dst_dir = SAMPLES_DIR / name
print(f'Creating proj... |
#!/usr/bin/env python
"""MixPanel to MailChimp Email Loaderator"""
import base64
import logging
import urllib2
from google.cloud import storage
from google.appengine.api import app_identity
from google.appengine.api import urlfetch
import googleapiclient.discovery
from flask import Flask
from mailchimp3 import MailC... |
#
# Copyright (c) 2018 CountStarlight
# Licensed under The MIT License (MIT)
# See: LICENSE
#
def flatten_idx(position, size):
(x, y) = position
return x * size + y
|
# Copyright (c) 2011 Adi Roiban.
"""
Unit tests for Windows NT Service.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
from chevah.compat.testing import CompatTestCase
if os.name == 'nt':
import win32service
from chevah.compat.nt_serv... |
# coding=utf-8
# 验证码有效期时间,单位:秒
IMAGE_CODE_EXPRIES_SECONDS = 100
# 短信验证码有效期时间,单位:分钟
SMS_CODE_EXPRIES_SECONDS = 5
# session有效期,单位:秒
SESSION_EXPIRES_SECONDS = 86400
# 密码加密混淆
PASS_WORD_HASH_KEY = 'cleven_video@$^*'
|
import pytest
import os
import numpy as np
from datetime import datetime, timezone
import spiceypy as spice
from importlib import reload
import json
import unittest
from unittest.mock import MagicMock, PropertyMock, patch
from conftest import get_isd, get_image_label, get_image_kernels, convert_kernels, compare_dicts... |
import logging
import math
import numpy as np
from saf.common.timeintegration.factory import Factory as tifactory
from saf.linear.config import Config
# from .characteristicstracer import CharacteristicsTracer
from .henrickapproximator import HenrickApproximator
from saf.euler1d.linear.problem import Problem as Euler... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import collections
from PyQt5 import QtCore, QtGui, QtWidgets
from gui.util.table_fit_mixin import TableFitMixin
class TableWithRemoveableEntries(QtWidgets.QTableWidget, TableFitMixin):
class EntryActionWidget(QtWidgets.QWidget):
remove =... |
"""Example code to demonstrate how to enumerate loaded plugins and their
parameters.
"""
import curses
import sys
import time
from dataclasses import dataclass
import pyfmodex
from pyfmodex.enums import (DSP_PARAMETER_DATA_TYPE, DSP_PARAMETER_TYPE,
PLUGINTYPE)
from pyfmodex.structures impo... |
"""
Copyright (c) 2015 SONATA-NFV and Paderborn University
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by ap... |
# -*- coding: utf-8 -*-
class Utils():
def __init__(self):
pass |
#coding:utf-8#
from PyQt5.QtWidgets import *
from PyQt5 import QtCore,QtWidgets,QtGui
from PyQt5.QtGui import *
import sys
import os
pic_folder=r'D:\JM\src\Job_Manager\pics\\'
class example(QWidget):
def __init__(self):
super(example,self).__init__()
self.setFixedSize(420,320)
self.layout=QGridLayout(self)
... |
#! /usr/bin/env python
"""
right now i'm sending "123,142|02,133|" to send two asciipixels
that's at least 8 bytes per asciipixel. i'd like to make it more
raw so that i send 2 bytes per asciipixel
"""
# external
import os
import sys
import struct
import pickle
sys.path.insert(0, os.path.join("..", "common"))
# ... |
# Auto generated from resourcedescription.yaml by pythongen.py version: 0.9.0
# Generation date: 2022-01-05T01:11:30
# Schema: resourcedescription
#
# id: https://hotecosystem.org/tccm/resourcedescription
# description: ResourceDescription represents the shared characteristics common to both abstract and resource
# ... |
from formencode import Invalid, htmlfill, Schema, validators
from WebKit.Page import Page
page_style = '''
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Tell me about yourself</title>
<style type="text/c... |
"""
652. Factorizatioremain
https://www.liremaintcode.com/problem/factorizatioremain/descriptioremain
"""
import math
class Solution:
"""
@param n: An integer
@return: a list of combination
"""
def getFactors(self, n):
# write your code here
results = []
self.dfs(n, 2, [], re... |
###########################################################################
#
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/l... |
import dask
parameter_scores = []
for i in range(4):
X_train, X_test, y_train, y_test = dask.delayed(train_test_split, nout=4)(data.data, data.target, pure=False)
for max_df in [0.5, 0.75, 1.0]:
for ngram_range in [(1, 1), (1, 2)]:
vect = dask.delayed(CountVectorizer)(max_df=max_df, ngram... |
# coding: utf-8
"""
Payoneer Mobile API
Swagger specification for https://mobileapi.payoneer.com
OpenAPI spec version: 0.9.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class LoginResponse(object):
""... |
"""
Using Annotation Files
======================
Display a Freesurfer cortical parcellation from an annotation file.
"""
import os
from os.path import join as pjoin
from surfer import Brain
print(__doc__)
subject_id = 'fsaverage'
hemi = 'both'
surface = 'inflated'
view = 'frontal'
"""
Bring up the visualization
"... |
from pathlib import Path
from typing import List
import numpy as np
from vicarutil.image import read_image
from ..widget.filelist import FileListWidget
from ...support import start_progress, stop_progress, ImageWrapper
def stack(flw: FileListWidget, paths: List[Path]) -> ImageWrapper:
try:
flw.busy = Tr... |
# Introduction to Computation and Programming Using Python (2021)
# Chapter 7, Finger Exercise 3
"""Finger exercise: Write a program that first stores the first ten
numbers in the Fibonnaci sequence to a file named fib_file. Each
number should be on a separate line in the file. The program should
then read the numbers... |
import numpy as np
import matplotlib.pyplot as plt
from .solver import EDONumericalResolution
from utils import seconds_to_hour
class RK4Method(EDONumericalResolution):
def derivatives(self, tn, y):
k1 = self.edo(self, tn, y)
k2 = self.edo(self, tn + (self.time_step / 2), y + ((self.time_step / 2) * k1))
... |
from enum import Enum
import pandas as pd
import numpy as np
from ..simulator.map_constants import MAP_Y
class FieldType(Enum):
STANDARD = 1
STANDARD_FIELD_LENGTH_HALF = 5120
STANDARD_FIELD_WIDTH_HALF = 4096
STANDARD_GOAL_WIDTH_HALF = 893
HEIGHT_0_BALL_LIM = 95 # Height of car when on ground
HEIGHT_0_LIM = 2... |
"""
Train InceptionV3 Network using the CUB-200-2011 dataset
"""
import pdb
import os
import sys
import argparse
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import math
import torch
import numpy as np
from analysis import Logger, AverageMeter, accuracy, binary_accuracy
from CUB import... |
# Tai Sakuma <tai.sakuma@gmail.com>
import time
import pytest
from mantichora.hubmp import available_mp_start_methods
from mantichora import mantichora
##__________________________________________________________________||
def task_perpetual(ret):
while True:
time.sleep(0.001)
return ret
##_________... |
#!/usr/bin/python
from __future__ import absolute_import
from roberta.ev3 import Hal
from ev3dev import ev3 as ev3dev
import math
import os
class BreakOutOfALoop(Exception): pass
class ContinueLoop(Exception): pass
_brickConfiguration = {
'wheel-diameter': 5.6,
'track-width': 18.0,
'actors': {
},
... |
import gc
import sys
from pathlib import Path
import torch
from torch import nn
from tqdm import tqdm
from config.parser import Configuration
from data.binary_datasets import BaseDataset
from log.tensorboard import Logger, LoggerTypes
from model.transfer_learning import CNN, NetworkTypes
class TrainerClass:
@sta... |
#!/usr/bin/env python2
from itertools import product as prod
import click
class Password():
__d1337 = {
"a": ["a", "A", "4"],
"b": ["b", "B", "8"],
"c": ["c", "C"],
"d": ["d", "D"],
"e": ["e", "E", "3"],
"f": ["f", "F"],
"g": ["g", "G", "9"],
"h": ["... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView
from django.views.generic import DeleteView
from django.views.generic import DetailView
from django.views.generic import ListView
from django.views.generic import UpdateView
from applications.blog.models import Post
... |
import numpy as np
def str2vec(_str):
""" vectorize the captcha str """
vec = np.zeros(4 * 43)
for i, ch in enumerate(_str):
offset = i*43 + (ord(ch)-ord('0'))
vec[offset] = 1
return vec
def vec2str(vec):
""" transform the vector to captcha str"""
_str = ""
for i in range... |
"""Functions and classes for the analysis after PBG training"""
import numpy as np
import pandas as pd
import anndata as ad
from scipy.stats import entropy
from sklearn.neighbors import KDTree
from scipy.spatial import distance
# import faiss
from ._utils import _gini
def softmax(adata_ref,
adata_query,... |
import pytest
from molsysmt.multitool import get_form as get_form
from molsysmt import get
from molsysmt import convert
import numpy as np
import pickle
with open('data/1tcd.pickle', 'rb') as f:
expected_values = pickle.load(f)
args = [
'data/1tcd.pdb',
convert('data/1tcd.pdb', to_form='molsysmt.MolSys'),... |
# Bismillah
# Clustering
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import cluster
# Bagian 1 - expolratory data analysis
df = pd.read_csv('D:/Phyton Code/Contoh dari Github/from-data-with-love-master\
/data/faithful.csv')
df.columns = ['eruptions', 'waiting']
# Bagian 2 - p... |
#!/usr/bin/env python
import time
from sys import exit
try:
import psutil
except ImportError:
exit('This script requires the psutil module\nInstall with: sudo apt install python3-psutil')
import blinkt
blinkt.set_clear_on_exit()
def show_graph(v, r, g, b):
v *= blinkt.NUM_PIXELS
for x in range(blin... |
from uuid import uuid4
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
def __str__(self):
return self.username
|
# Needed so that test_all.py will recurse into this directory.
|
import json
import traceback
from hashlib import sha512, md5
from unittest import mock
import uuid
from datetime import datetime
from freezegun import freeze_time
from openprocurement.audit.api.choices import VIOLATION_TYPE_CHOICES
from openprocurement.audit.monitoring.tests.base import BaseWebTest as MonitoringWebTe... |
LOOKUP_BY_ID = {
"AM": "ADMINISTRATIVE CRIMINAL",
"AG": "AGGRAVATED MISDEMEANOR",
"AC": "APPEAL FOR CIVIL",
"AR": "APPEAL FOR CRIMINAL",
"DI": "ATTORNEY DISCIPLINARY ACTION",
"CN": "CHANGE OF NAME",
"CS": "CHILD SUPPORT CONVERSION",
"CY": "CITY ORDINANCE - DO NOT USE",
"EQ": "CIVIL E... |
# coding=utf-8
from __future__ import absolute_import, print_function
import hashlib
import os
import os.path
import random
import re
import struct
import sys
import tarfile
from datetime import datetime
from time import time
import numpy as np
#import tensorflow as tf
from six.moves import urllib
#from tensorflow.py... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - Wiki Utility Functions
@copyright: 2000-2004 Juergen Hermann <jh@web.de>,
2004 by Florian Festi,
2006 by Mikko Virkkil,
2005-2008 MoinMoin:ThomasWaldmann,
2007 MoinMoin:ReimarBauer
@license: GNU GPL,... |
# -*- coding: utf-8 -*-
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Common functions for interacting with repo manifest XML files."""
from __future__ import print_function
import sys
# TODO(va... |
from django.shortcuts import render, redirect, get_object_or_404
from .models import Guide
def measureguides(request):
guides = Guide.objects.all()
return render(request, 'measureguides.html', {'guides' : guides})
|
# coding=utf-8
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from clambda.options import db_uri
@contextmanager
def session_scope():
"""Provide a transactional scope around a series of operations."""
session = Session()
... |
# -*- coding: utf-8 -*-
class DatabaseAsAServiceApi(object):
def __init__(self, credentials):
self.credentials = credentials
@property
def endpoint(self):
return self.credentials.endpoint
@property
def user(self):
return self.credentials.user
@property
def passwo... |
# Copyright 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 accompan... |
'''
File: new.py
Project: KrOB
File Created: Wednesday, 5th September 2018 3:44:30 am
Author: shpkng (shpkng@gmail.com)
Organization: Communication University of China
License: GPL
-----
Last Modified: Thursday, 6th September 2018 5:17:59 am
Modified By: shpkng (shpkng@gmail.com)
-----
Valar Morghulis.
'''
s = 'I:\腾讯游... |
#partindo do principio fundamental do triangulo informar se é equilatero, escaleno ou isosceles
retaA = int(input('Digite o valor em CM para a reta A: '))
retaB = int(input('Digite o valor em CM para a reta B: '))
retaC = int(input('Digite o valor em CM para a reta C: '))
if retaA + retaB < retaC:
print('Não há po... |
from nose.tools import eq_, raises
import paycalc.tax as pt
def test_brackets_at_threshold():
brackets = pt.TaxBrackets(pt.TAX_BRACKETS_2018)
cases = [
(100, 0),
(18200, 0),
(18300, 19),
(37000, 3572),
(37200, 3572 + (32.5*2)),
(87000, 19822),
(87100, ... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
num=load_digits()
for x,y in zip(num.data[6:10],num.target[6:10]):
plt.imshow(x.reshape(8,8),cmap="gray")
plt.title(y)
|
# -*- coding: utf-8 -*-
import json
import time
import tryagain
import requests as r
import config as cfg
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'}
url = "https://gorzdrav.spb.ru/_api/api/v2/schedule/lpu/" + c... |
import asyncio
import signal
import os
from back.repl_proto import Events, encode, decode
from utils.logger import log
_REPL = 'back/repl.py'
_shells = {}
_glock = asyncio.Lock()
_log = log(__name__)
class Shell:
def __init__(self, name, user):
self._proc = None
self._user = user
self._n... |
import os
import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
import discord
from discord.ext import commands
import sys, traceback
from datetime import datetime
import platform
def start_bot():
initial_extensions = ['cogs.nncog']
bot = commands.Bot(command_prefix="!", description=f'Nazywam się... |
import numpy as np
from gym import Env, spaces
from gym.envs.registration import register
class DynamicsEnv(Env):
def __init__(self, dt=0.1):
self.x = np.zeros((2, 1))
self.A = np.array([[1, dt], [0, 1]])
self.B = np.array([[0], [dt]])
self.action_space = spaces.Discrete(2)
de... |
from os import getenv
from typing import Any, Dict, List, Match, NamedTuple, Tuple, Type
from ..helpers import raise_, re_finditer
from . import Resolver, ValueNotFound, ValueResolutionPostponed
REGEX = r"%(static|env|var)\(([str:int:float:bool:]*?)([\w]+)(,\s{1}'.*?')?\)%"
STATIC_TEMPLATE: str = "%static({0}:{1}, '{... |
'''llvm_types
Utility module containing common (to Numba) LLVM types.
'''
# ______________________________________________________________________
import sys
import llvm.core as lc
# ______________________________________________________________________
if sys.maxint > 2**33:
_plat_bits = 64
else:
_plat_bit... |
#!/Users/lindsaychuang/miniconda3/envs/obspy/bin/python
import pandas as pd
from obspy import UTCDateTime, read, Stream, Trace
import dash_html_components as html
import plotly.graph_objects as go
def wrap_wfs(st):
fig = go.Figure()
for i in range(0, len(st)):
fig.add_trace(
go.Scattergl(
... |
#!/usr/bin/env python
"""
Author: Gideon Bar
"""
import json
import os
import traceback
from enum import Enum
from time import sleep
import logging
from cassandra import ConsistencyLevel
from cassandra.cluster import Cluster, BatchStatement
from cassandra.policies import RoundRobinPolicy
from cassandra.query import S... |
# Generated by Django 3.1.8 on 2021-04-09 06:20
from django.db import migrations, models
import unievents.models
class Migration(migrations.Migration):
dependencies = [
('unievents', '0018_auto_20210409_0616'),
]
operations = [
migrations.CreateModel(
name='Tag',
... |
# Generated by Django 3.2.11 on 2022-01-08 10:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DimDmr',
fields=[
... |
# Generated by Django 2.2.2 on 2019-06-20 22:59
from django.conf import settings
import django.contrib.postgres.fields.hstore
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependenci... |
"""
Feature_Selectors.py
====================================
File with different Feature Selectors
"""
from ..helpers import (get_possible_init_params,
get_obj_and_params, all_from_avaliable)
from sklearn.feature_selection import SelectPercentile, VarianceThreshold
from ...extensions.feat_select... |
from django.contrib import admin
from .models import Blog, Comment
class CommentInline(admin.StackedInline):
model = Comment
class BlogAdmin(admin.ModelAdmin):
inlines = [CommentInline, ]
admin.site.register(Blog, BlogAdmin)
# admin.site.register(Comment)
# Register your models here.
|
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
"""
@param head: The head of linked ... |
from dataknead import Knead
from pathlib import Path
from pywikibot import WbTime
from util.skiplist import Skiplist
from util.wikidata import Props, Items, WikidataItem
from util.wikipedia import get_permalink
import pywikibot
import requests
import sys
def get_ref(item, permalink):
return [
item.get_item... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MODIS Download and Processing Tool
Author: Emily Burchfield <emily.k.burchfield@vanderbilt.edu>
This package downloades user specified MODIS tiles over a period of time,
mosaics the tiles, reprojects the HDF files, and transforms the images
into a 2D matrix where each ... |
"""Module to hold the constants of the SDK."""
API_BASE_URL = "https://api.fintoc.com"
API_VERSION = "v1"
LINK_HEADER_PATTERN = r'<(?P<url>.*)>;\s*rel="(?P<rel>.*)"'
DATE_TIME_PATTERN = "%Y-%m-%dT%H:%M:%SZ"
|
"""proto_app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
"""Package for zExceptions tests"""
|
from unicodedata import category
import flask_simplemde
from flask_wtf import FlaskForm
from wtforms import TextAreaField, SubmitField, StringField , SelectField
from wtforms.validators import DataRequired
class UpdateProfile(FlaskForm):
bio = TextAreaField("Tell us something about yourself", validators=[DataRequi... |
import datetime
import requests
from django.shortcuts import render, redirect
from django.http import request, HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.core.paginator import Paginator
from django.contr... |
# Generated by Django 1.11.1 on 2017-05-21 17:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("misago_threads", "0005_index_search_document")]
operations = []
|
#!/usr/bin/env python
# encoding: utf-8
# File Name: mat2edge.py
# Author: Jiezhong Qiu
# Create Time: 2019/03/18 12:01
# TODO:
import scipy.io
import scipy.sparse as sparse
import math
import numpy as np
import sys
def WriteMatrix(file, A):
A = A.todok()
print(A.shape)
print(A.nnz)
with open(file, "w... |
# standard libraries
from math import pi
# external libraries
import mendeleev
# global imports
import config
import check_inputs
from models import *
import writeoutput
class Atom:
"""
The Atom class defines the main atom object containing the key information about the
atomic species, temperature, dens... |
# Copyright (c) 2021, Xuzhe Zhang, Xinzi He, Yun Wang
# MIT License
from timm.models.registry import register_model
from .transformer_block import Block, get_sinusoid_encoding, SWT4, SWT_up4
from torch import nn
import torch
import torch.nn.functional as F
class PTNet(nn.Module):
"""
PTNet class
"""
... |
import os
from qiskit import IBMQ, __version__
from dotenv import load_dotenv
# Load environment variables.
load_dotenv()
# Login to IBM Quantum.
if IBMQ.stored_account().get('token') == None:
IBMQ.save_account(os.environ['IBMQ_TOKEN'])
print('You are now logged in...')
print(__version__) |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import VERSION as django_version
from django.template import Library
from stagesetting.models import RuntimeSettingWrapper, RuntimeSetting
register = Library()
if django_version[0:2] < (1, 9):
tag = register.assignment_ta... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
@api.onchange('lead_enrich_auto')
def _onchange_cron_lead_enrich(self):
""" change the ... |
from PyQt4 import QtCore, Qt
class OkMainToolBar(Qt.QToolBar):
def __init__(self, parent=None):
Qt.QToolBar.__init__(self, parent)
spacer = Qt.QWidget()
spacer.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding)
self.addWidget(spacer)
self.addWidget(MinBut... |
from cgi import parse_multipart, parse_header
from io import BytesIO
from base64 import b64decode
from ibm_watson import SpeechToTextV1, ApiException
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator
import json, os
def main(args):
# Parse incoming request headers
_c_type, p_dict = parse_heade... |
#--------------------------------------------------------------------------------
# Authors:
# - Yik Lung Pang: y.l.pang@qmul.ac.uk
# - Alessio Xompero: a.xompero@qmul.ac.uk
#
# MIT License
# Copyright (c) 2021 CORSMAL
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... |
from setuptools import setup
#from distutils.extension import Extension
#from Cython.Distutils import build_ext
setup(
name="WMM",
version="0.1.0dev",
#cmdclass = {'build_ext': build_ext},
#ext_modules = [Extension("wmm.grid",
# sources=["wmm/grid.pyx", "GeomagnetismLibrary.c"],
# include... |
# coding=utf-8
"""
Tests for deepreg/model/network/ddf_dvf.py
"""
import tensorflow as tf
from deepreg.model.network.ddf_dvf import ddf_dvf_forward
from deepreg.model.network.util import build_backbone
def test_ddf_dvf_forward():
"""
Testing that ddf_dvf_forward function returns the tensors with correct sha... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import RobustScaler, StandardScaler
from tqdm import tqdm
from .misc import make_conf, print_c, is_number
from .constants import FILL_NAN_METHODS, FILL_INF_METHODS
def remove_single_value_features(df: pd.DataFrame = None , verbose: bool = False, include... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.