text stringlengths 3.07k 12.6k |
|---|
# @author <NAME>
# import os, sys
# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import argparse
import re
from process_methods import find_pdf_terms_in_sent_tsv, read_entity_set
from process_xhtml import read_xhtml, enrich_xhtml
import statistics
from config import ROOTPATH, PDFNLT_PA... |
"""
Run the Termset Generator user interface from the command line.
This file contains the front-end code to run the Termset Generator, a tool
which generates a "termset", or list of synonyms and spelling variations
for a given "concept of interest", or medical term.
Usage:
streamlit run termset_generator.py
"""
imp... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic.edit import View
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from .utils.imdatabase import IMDatabase
from rest_framework import status
from .forms impor... |
import os
import shutil
import glob
from utils.celery_client import celery_app
from workers.base_task import BaseTask, ObjectTask
from utils.repository import generate_repository_path
from utils.job_db import JobDb
from utils import cilantro_info_file
repository_dir = os.environ['REPOSITORY_DIR']
archive_dir = os.en... |
from django.test import Client, TestCase
from django.urls import reverse
from posts.models import Group, Post, User
class PostsURLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.test_group = Group.objects.create(
title='Тест',
slug='test',
... |
import logging
import time
from typing import Tuple
import datetime
import ccxt
import tqdm
from pandas import DataFrame
from kektrade import utils
from kektrade.data.converter import Converter
from kektrade.data.dataprovider import DatetimePeriod, PairDataInfo
from kektrade.exceptions import UnsupportedExchange
from ... |
import http.server as _hs
import urllib.parse as _uparse
import subprocess as _subp
import threading as _threading
import requests as _rq
import os as _os
import os.path as _path
import configparser as _configp
import time as _time
this_old_garmin_id = 29665
this_old_garmin_secret='<KEY>'
this_old_garmin_redirect_uri... |
"""-----------------------------------------------------------------------------
initialize.py (Last Updated: 01/16/2020)
The purpose of this script is to initialize the rt-cloud session. Specifically,
it will initiate any variables that need to be initiated (e.g., configuration
file) and upload any necessary files t... |
from typing import *
from plovary import *
# "English Single Chord DICTionary"
ESCDict = Dictionary[Chord[EnglishSystem], str]
shared = system.parse("-LGDZ")
# only isn't needed here, but this way `mypy` checks that this
# is really just a single correct key:
add_y = system.chord("-F")
submit = system.chord("-R")
add... |
import torch
import torch.nn.functional as f
from torch import nn
import numpy as np
import pandas as pd
class Critic(nn.Module):
def __init__(self, input_dim):
super(Critic, self).__init__()
self._input_dim = input_dim
# self.dense1 = nn.Linear(109, 256)
self.dense1 = nn.Linear(sel... |
__all__ = [
'Aligner',
'PrefixComparer',
'SuffixComparer',
'hamming_sphere',
'hamming_environment',
'edit_environment',
'edit_distance',
]
from cutadapt._align import Aligner, PrefixComparer, SuffixComparer
# flags for global alignment
# The interpretation of the first flag is:
# An initi... |
from __future__ import annotations
import os
import socket
from datetime import timedelta
from typing import Any, Dict
from abilian.web.action import Endpoint
from flask.cli import load_dotenv
load_dotenv()
HOST_MAP = {
"orophin": "TIRETDEV",
"tareg": "PREPROD",
"zirak": "PRODUCTION",
}
DEFAULT_SRC = ... |
# -*-coding:utf-8-*-
import argparse
import yaml
import time
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
from visdom import Visdom
from easydict import EasyDict
from models import *
from utils import *
parser = argparse.Argume... |
# http://codeforces.com/problemset/problem/2/A
import sys
from random import randint
from typing import Tuple, List
from timeit import default_timer as timer
IS_LOCAL = False
class HashSet:
_max_frac = 3.
_min_size = 7
def __init__(self):
self._n = 0
self._size = self._min_size
... |
from django.db import models
from django.utils.timezone import utc
import time
import datetime
from urllib.parse import urlencode
import logging
import sys
import email
class Source(models.Model):
# This is an actual feed that we poll
name = models.CharField(max_length=255, blank=True, null=True)
... |
import matplotlib.pyplot as plt
import urllib.request as request
import torch
import tarfile
import os
import numpy as np
from torch.utils.data import TensorDataset
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import matplotlib
matplotlib.use('agg')
class NotMNI... |
"""
SMB Protocol Authentication And Connection
- Edited by b3kc4t to using stated references on smbconnection file.
References = https://docs.microsoft.com/en-us/windows-server/storage/file-server/file-server-smb-overview#:~:text=The%20Server%20Message%20Block%20(SMB,protocol%20or%20other%20network%20protocols, https:/... |
import argparse
import logging
import multiprocessing as mp
import pynini
from ocrd_keraslm.lib import Rater
from ..lib.latticegen import FSTLatticeGenerator, lattice_shortest_path
from ..lib.helper import \
load_pairs_from_file, load_pairs_from_dir, \
save_pairs_to_file, save_pairs_to_dir
# globals (for pa... |
import asyncio
import contextlib
import json
import os
import subprocess
import typing as t
from datetime import datetime
import pandas as pd
import structlog
import yfinance as yf
from dateutil import tz
DEFAULT_DATA_FOLDER="tmp/repo"
RECORDS_FILE="records.csv"
SUMMARY_FILE="summary.csv"
SLEEP_SECS_BET_TICKERS=2
GH... |
# Copyright 2021 The Bellman Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import argparse
import os
import pandas as pd
import subprocess
import tempfile
def bedtools_intersect(filename_a, filename_b, out='annotations.bed', intersect_overlap=0):
# bedtools intersect -wao -a "${peaks_file}" -b "${annotations_file}" > "${peaks_base}_${annot_base}.intersect.bed"
intersect_tmp = tempfil... |
def test_zip():
assert(list(zip([1])) == [(1,)])
assert(list(zip([1], [2])) == [(1, 2,)])
assert(list(zip([1], [2], [3])) == [(1, 2, 3)])
assert(list(zip([1], [2], [3], [4])) == [(1, 2, 3, 4)])
assert(list(zip([1], [2], [3], [4], [5])) == [(1, 2, 3, 4, 5)])
assert(list(zip([1], [2], [3], [4], [5... |
from random import randrange
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from sklearn.linear_model import LinearRegression
# 数据预处理
table_header = {'id', 'time', 'op_setting_1', 'op_setting_2', 'op_setting_3',
'sensor_1', 'sensor_2', 's... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import division, print_function
"""
Copyright 2018 Digital Media Professionals 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 th... |
#coding:utf-8
# Copyright (c) 2019 PaddlePaddle Authors. 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 r... |
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import abc
from functools import wraps
from baskerville.models.metrics.registry import StatsHook
from baskerville.util.helpe... |
import os
import sys
import traceback
from pynus.utils import progress
from selenium import webdriver
from selenium.common.exceptions import (
StaleElementReferenceException,
TimeoutException
)
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.webdriver.chrome.options import Options ... |
import random
import torch
from torch.autograd import Variable
from tqdm import tqdm
from sklearn.utils import shuffle
from sklearn.metrics import mean_absolute_error
from scipy.stats import spearmanr
from util.batching import Batcher, prepare, prepare_with_labels
from sklearn.metrics import f1_score
import numpy as n... |
import argparse
import json
import sys
import requests
import re
from cfbs.utils import is_a_commit_hash
class CFBSIndexException(Exception):
def __init__(self, name, message) -> None:
if name is None:
super().__init__("Error in index: " + message)
else:
super().__init__("... |
def data(read_data,file):
if read_data is True:
#Reading system information
from scripts.readData import data_file
print('Reading data...')
data_file('datasystem/'+str(file)+'.xlsx')
# delete temporal files
def data_consistency(stages, seriesBack, seriesForw):
... |
import os.path
import random
import glob
import pickle
from main import train, test
def score(label_dict, target='', selection=list(), n=50):
"""
Calculate the score of a selected set compared to the target image.
:param label_dict: dictionary of labels, keys are image IDs
:param target: image ID of t... |
##################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2019 #
##################################################
import os, sys, time
import numpy as np
import random
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
class ArtGAN(keras.Model):
def __init__(self, latent_dimensions=128, image_directory="train_images"):
super(ArtGAN, self).__init__()
self.latent_dimensions = latent_dimensions
self.ge... |
import sys
import chardet
from .functions import *
class UrlNotDecoded(Exception):
pass
class Faup(object):
"""
Faup Python Library
"""
def __init__(self):
self.options = faup_options_new()
self.fh = faup_init(self.options)
self.decoded = False
self.retval = {}
... |
"""
Proxied IO classes definitions and implementations.
This library contains the implementation of a raw IO class that proxies reads and writes
to another raw IO object.
This library also contains these classes:
- EncryptedWriteIO: an IO instance that encrypts the written bytes using a CipherContext and
then wr... |
from const import *
import pygame
def splotch_bg(size, color):
surf = pygame.Surface(size)
surf.fill(color)
return surf
# Flat fill markings
def flat_mark(color, connections, ts, lw):
side = ts + 2 * lw
surf = pygame.Surface((side, side))
pygame.draw.rect(surf, color, pygame.Rect(lw, lw, ts... |
# ===============================================================================
# Copyright 2012 <NAME>
#
# 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/LI... |
#!/usr/bin/env python3
import boto
import concurrent.futures as futures
import katsdpservices
import logging
import multiprocessing
import os
import pysolr
import sys
from optparse import OptionParser
from katsdpdata.prod_handler import make_boto_dict
from katsdpdata.prod_handler import get_s3_connection
CPU_MULTIPL... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 17:18:58 2018
@author: chrelli
"""
# Demo getting the KRLS-t to work!
#%%
import time, os, sys, shutil
# for math and plotting
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
#import math
# small... |
#!/usr/bin/env python
# Copyright (c) 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import sys
import subprocess
import unittest
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(_... |
import uuid
def label(language='en', value=''):
"""Create and return a label (dict)"""
return {language: {'language': language, 'value': value}}
def alias(language='en', value=''):
"""Create and return an alias (dict)"""
a = {}
if len(value) == 0:
a[language] = [{'language': language, 'v... |
import sys
import os
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
from datetime import datetime
from pepper_variant.modules.python.models.dataloader_predict import Seq... |
#!/usr/bin/env python3
from pathlib import Path
import numpy as np
import pandas as pd
# Raw pressure sensor data (three samples per file) ------------------------------------------------------------------------------------------
def load_raw_data(file):
''' Load raw pressure sensor data from csv file and
... |
from unittest import TestCase
from namedspace import namedspace
class NamedspaceTests(TestCase):
@classmethod
def setUpClass(cls):
cls.mock_default_value = "Mock default value"
cls.mock_name_template = "Mock name for {id}"
cls.mock_default_factory = staticmethod(
lambda n... |
from __future__ import annotations
import functools
import re
from collections.abc import Iterable, Sequence
from typing import Any, TypedDict
from urllib.parse import urlencode
from flask import current_app, render_template, request, url_for
from markupsafe import Markup
from werkzeug.routing import Map, Rule
from ... |
import gym
import os
import torch
import stable_baselines3
from stable_baselines3.common.callbacks import CallbackList, CheckpointCallback, EvalCallback
from stable_baselines3 import SAC
from particle import ParticleEnv, get_particle_env
from gym.wrappers import TimeLimit
import torch as th
import numpy as np
import ma... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
from collections import defaultdict
# Use a interactive backend
import sys
import matplotlib
matplotlib.use("TkAgg")
from six.moves import xrange
from tqdm import tqdm
import cv2
impor... |
import torch
import torch.nn as nn
import torch.autograd as autograd
import torch.nn.functional as F
import numpy as np
from PIL import Image
from albumentations import *
from utils.transformations import *
def get_norm(norm_type, size):
if(norm_type == 'batchnorm'):
return nn.BatchNorm2d(size)
elif(norm_type == '... |
from .JSClass import JSClass
# from .JSGroup import JSGroup
import os
import re
from pathlib import Path
LOCATIONS_IGNORE = ["j.errorhandler", "j.core", "j.application", "j.exceptions", "j.logger", "j.dirs", "j.baseclasses"]
def _check_jlocation(location, classname=""):
"""
will return true if the location ... |
#!/usr/bin/python
# pip install lxml
"""
Module contains functions needed for generating synthetic image dataset.
"""
import random
import os
import glob
import logging
from typing import List, Sequence, Any
import cv2
import numpy as np
from mystique import config
logger = logging.getLogger("commands.generate_bulk_... |
#!/usr/bin/env python
# Copyright (c) 2014-2018, F5 Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
import abc
import logging
from copy import copy
from .Condition import ConditionWithOnlyColumns, Condition
from .ConditionTreeNode import ConditionTreeNodeBase
from .Selection import Selection
from .Table import Table
logger = logging.getLogger('Statement').print_pos
select_logger = logging.getLogger('Select statemen... |
from PyQt5 import QtGui, QtCore, QtWidgets
from collections import namedtuple
import time
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import utils
HumanFeedback = namedtuple('HumanFeedback', ['feedback_time', 'feedback_value'])
SavedAction = namedtuple('SavedAction', ['s... |
"""
Transforms a variable length text to a fixed-length vector.
Text2VectorOperator: Uses a pretrained model (DistilBERT) from the transformers library
to create word vectors which are then averaged to produce a document vector. It fetches
abstracts from PostgreSQL which decodes to text. The output vectors are
stor... |
import shutil
import subprocess
import unittest
from pathlib import Path
from unittest import TestCase, mock
from bigflow.cli import cli
class ProjectScaffoldE2ETestCase(TestCase):
def tearDown(self):
clear_project_leftovers(Path('my_project_project'))
class ProjectScaffoldE2E(ProjectScaffoldE2ETestCas... |
from rest_framework import serializers
from rest_framework_gis.serializers import (
GeoFeatureModelSerializer, GeometrySerializerMethodField)
from bims.models.biological_collection_record import BiologicalCollectionRecord
from bims.serializers.taxon_serializer import (
TaxonSerializer,
TaxonExportSerializer... |
"""Knows about HTML generation."""
import datetime as dt
import os
import shutil
import typing as tg
from pmlv.base import Stoptimes
def default_css_srcfile():
return "%s/../css/pomalevi.css" % os.path.dirname(__file__)
def default_favicon_srcfile():
return f"{os.path.dirname(__file__)}/../img/favicon.png"... |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import csv
import numpy as np
from bingo.symbolic_regression.agraph.generator import AGraphGenerator
from bingo.symbolic_regression.agraph.component_generator \
import ComponentGenerator
from bingo.sym... |
from datetime import datetime, timedelta
from unittest.mock import Mock
import pytest
import sqlalchemy as sa
from h_matchers import Any
from h.models.document import ConcurrentUpdateError, create_or_update_document_uri
from h.models.document._document import Document
from h.models.document._uri import DocumentURI
... |
from os.path import join
import open3d as o3d
import numpy as np
import os
import re
import python.open3d_tutorial as o3dtut
# http://www.open3d.org/docs/release/tutorial/pipelines/rgbd_odometry.html
#####################################################################################################################... |
from math import isclose
from ppb import BaseSprite
from ppb import Vector
from ppb.camera import Camera
from hypothesis import given, assume, note, example
import hypothesis.strategies as st
from .utils import vectors
def test_camera_move():
cam = Camera()
cam.position = Vector(500, 500)
assert cam.pos... |
import mimetypes
from Jumpscale import j
from Jumpscale.clients.peewee.peewee import OperationalError
from . import auth
from .rooter import app, abort, enable_cors, package_route, response, request, PACKAGE_BASE_URL
MODEL_URL = f"{PACKAGE_BASE_URL}/model/<model_url>"
RECORD_URL = f"{MODEL_URL}/<record_id>"
class... |
import subprocess
import requests
from flask import Blueprint, request, redirect, current_app, abort
from globals import globalvars
rtmp_bp = Blueprint('rtmp', __name__)
@rtmp_bp.route('/auth-key', methods=['POST'])
def streamkey_check():
key = request.form['name']
ipaddress = request.form['addr']
# E... |
import copy
import numpy as np
import logging
import collections
from typing import List, Dict, Tuple
from ray.autoscaler.node_provider import NodeProvider
from ray.autoscaler.tags import TAG_RAY_INSTANCE_TYPE
logger = logging.getLogger(__name__)
# e.g., m4.16xlarge.
InstanceType = str
# e.g., {"resources": ..., "m... |
# TO USE THIS FILE:
# _ install the following packages: boto3
# _ rename __AMAZON_KEY__.template.py to __AMAZON_KEY__.py and add your own amazon access id, key and mobius directory to the file
# _ change FUNC_NAME to be whichever function you want to update
import boto3
import os
import shutil
import zipfile
import js... |
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import serializers
from rest_framework import generics
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import de... |
# -*- coding: utf-8 -*-
#
# SPDX-FileCopyrightText: 2014 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: BSD-2-Clause
import logging
import fnmatch
import os
import re
import gv
import yaml
from kapidox.depdiagram import gvutils
from kapidox.depdiagram.framework import Framework
TARGET_SHAPES = [
"polygon", # li... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
import os.path
from io import BytesIO
import pytest
from pex import hashing
from pex.hashing import Sha1Fingerprint, Sha256Fingerprint
from pex.pep_503 import ProjectName
fro... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018, <NAME> <<EMAIL>>
# Based on code:
# (c) 2013, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {... |
import pyqtgraph as pg
from PySide2 import QtCore, QtWidgets, QtGui
import pyqtgraph.functions as fn
import pandas as pd
from functools import partial
transparentCol = "#969696"
transparentStyle=f"background: transparent;color:{transparentCol};border-color: {transparentCol};border-width: 1px;border-style: solid;min-wi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2021) Hewlett Packard Enterprise Development LP
#
# 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/L... |
#!/usr/bin/env python3
import os, re, random, copy, time, sys
import numpy as np
import matplotlib.pyplot as plt # for output generalization error graphs
from myClass import Theta # for classifier's parameters
from functions import loss, func_s # for loss and classifier
from sgd import sgd, momentum_sgd # defines sgd
... |
"""
The MIT License (MIT)
Copyright (c) 2017 SML
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 17:16:21 2017
@author: cschuwerk
"""
PKG = 'roboclaw_driver'
import roslib; roslib.load_manifest(PKG) # This line is not needed with Catkin.
#import sys
import unittest
import rospy
from kinematics_python_wrapper.kinematics_py import Kinematic... |
from typing import List
from fontbakery.callable import condition
# used to inform get_module_specification whether and how to create a specification
from fontbakery.fonts_spec import spec_factory # NOQA pylint: disable=unused-import,cyclic-import
@condition
def ttFont(font):
from fontTools.ttLib import TTFont
re... |
from itertools import chain, tee
from ...exceptions import NeuroLangException
from ...expressions import Constant
from ...logic.unification import (apply_substitution_arguments,
compose_substitutions,
most_general_unifier_arguments)
from ...utils impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Faker providers for tracking request generation
'''
from collections import OrderedDict
from typing import Iterable, Tuple
from urllib.parse import urljoin, quote as urlquote
from faker import Faker
from faker.providers import BaseProvider
from ._utils import get_f... |
# -*-coding:Utf-8 -*
from os import system
import xml.etree.ElementTree as ET
def getMeteoYahoo(woeid):
return system('curl "http://weather.yahooapis.com/forecastrss?w='+woeid+'&u=c" > weather.xml')
def recupMeteo(woeid):
"""Parcours le fichier xml récupéré, puis renvoie les attribus dans cet ordre : condition,wind... |
#!/usr/bin/env python
import tempfile
import boto3
import os
import sys
import json
import io
from apiclient import discovery
from apiclient import errors
from apiclient.http import MediaFileUpload
from googleapiclient.http import MediaIoBaseDownload
def get_service_account_credentials(credentials_parameter):
""... |
from flask_socketio import SocketIO, emit, join_room, leave_room
from subprocess import call
from main import session, upload
import database as db
import datetime, json, re
# The file types that will preview on the page
# Other file types will show a download link instead
file_types = {
"image" : ["png", "jpg", "... |
"""
views.py -- Views for MARC record manipulation
"""
#
# 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... |
import json
import time
import zope.sqlalchemy
from pyramid.renderers import render
from sqlalchemy import (
engine_from_config,
Column,
String,
UnicodeText,
Integer,
ForeignKey,
func,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import Mutable
from s... |
import pandas as pd
import geopandas as gp
import numpy as np
from shapely.geometry import Point, LineString, MultiLineString
def to2D(geometry):
"""Flatten a 3D line to 2D.
Parameters
----------
geometry : LineString
Input 3D geometry
Returns
-------
LineString
Output 2D... |
import nevergrad as ng
from ..helpers import args_repr
class Params():
def _class_name(self):
return type(self).__name__
def _extra_repr(self):
if not hasattr(self, 'extra'):
return ''
base = ''
for info in self.extra:
base += '.' + info['name'] + '(... |
# External packages
import sys
import os
import pandas as pd
import ast
import string
import unicodedata
import re
import string
# Internal modules
import paperscraper.config as config
regex = re.compile(r'[\n\r\t]')
set_punctuations = set(string.punctuation)
set_numbers = set("0123456789")
def clean_string(_string)... |
import json
import requests
import json
import os
import csv
import datetime
darksky_api_key = ""
darksky_base_url = "https://api.darksky.net/forecast/{}/".format(darksky_api_key)
def get_daily_temp_forecast(lat_long):
# Gets average daily temperature for one week
darksky_url = darksky_base_url + "{},{}?exten... |
import sys
import tensorflow as tf
import numpy as np
import data
import cnn
import new_cnn
EPOCH = 1
SAMPLE_SIZE = 51520000
BATCH_SIZE = 32
INIT_LEARNING_RATE = 0.0001
DECAY_STEPS = 5000
DECAY_RATE = 0.94
KEEP_PROB = 0.5
CKPT_PATH = lambda size_index: "./.tmp/" + str(size_index) + "/"
CKPT_PREFIX = "training.ckpt"... |
# This file contains (messy) code used to find diagnosis codes whcih appeared assigned to
# both qualified and unqualified patients, identifying records with errors and common sources of error.
# This file was also used to mark patients who suffered a hemispheric stroke to use that as a feature for the model.
# Namrata... |
from .Configuration import Conf
from .CustomEnums import DataSetName
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch
import os
def get_data_set(conf, test_size=1):
dataset = conf.dataset
batch_size = conf.batch_size
train, valid, test, train_loa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : sentiment_weibo.py
# @Author : <NAME>
# @Time : 2021/08/19
# @Desc :
import sys
import os
import random
import numpy as np
import pandas as pd
from dataclasses import dataclass
import tensorflow as tf
import tensorflow.keras as keras
from keras.preproce... |
import numpy as np
from numpy.random import rand
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import glob as glob
import pandas as pd
import json
from scipy.interpolate import interp1d
from scipy import interp
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from matp... |
# -*- coding:utf-8 -*-
# &Author AnFany
# 引入数据
import pm25_LightGBM_Data as data
# 引入模型
import lightgbm as lgbm
from sklearn.metrics import mean_squared_error as mse
import numpy as np
# 绘制不同参数下MSE的对比曲线
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 显示中文
mpl.rcParams['axes.uni... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 21:26:33 2020
@author: xavier.mouy
"""
import sys
sys.path.append("..") # Adds higher directory to python modules path.
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
import time
from dask import delayed, compute
import dask.bag as db
from ... |
# Copyright 2020 <NAME> <<EMAIL>>
# 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... |
#!/usr/bin/env python3
# vim: set expandtab tabstop=4 shiftwidth=4:
# Borderlands 3 Data Processing Scripts
# Copyright (C) 2021 <NAME>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source ... |
# Copyright 2021 Zilliz. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
# encoding: utf-8
# Django command installing a Windows Service that runs Django commands
#
# Copyright (c) 2012 Openance
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Core Initiative and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import json
import frappe
from frappe.model.document import Document
class InnRoom(Document):
pass
@frappe.whitelist()
def copy_amenities_templa... |
from torch.utils.data import Dataset
from util import get_args
import numpy as np
import torch
import imageio
from PIL import Image
from torchvision import transforms
import torch.nn as nn
import os
class VideoDataset(Dataset):
"""Video dataset.(There is the THUMOS 14.)"""
def __init__(self, args, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.