content
stringlengths
0
894k
type
stringclasses
2 values
import numpy as np from .base import BasePipe from .utils import Bounds class CreateFM(BasePipe): def __init__(self, n_samples=np.array([500, 5000], dtype=int), nudge_avg=np.array([0.05, 0.5]), control_unique=np.array([0, 1.0]), control_precisio...
python
from django.urls import path from . import views urlpatterns = [ path('rooms', views.dashboard_view, name='rooms'), path('create_room', views.create_room_view, name='create_room'), path('chat/<int:room_id>', views.chat_view, name='chat'), path('send_message', views.send_message, name='send_message'), ...
python
# general imports import os import pytest from pathlib import Path # AHA imports import magma as m import fault # FPGA-specific imports from svreal import get_svreal_header from msdsl import get_msdsl_header # DragonPHY imports from dragonphy import get_file, Filter BUILD_DIR = Path(__file__).resolve().parent / 'bu...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Section', fields=[ ('id', models.AutoField(prim...
python
# coding=utf-8 # Author: Rion B Correia & Xuan Wang # Date: Jan 06, 2021 # # Description: Parse Instagram timelines and extract dictionary matches # import os import sys # include_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'include')) # include_path = '/nfs/nfs7/home/rionbr/mya...
python
import revkit import pytest def test_tbs_synthesizes_swap(): net = revkit.tbs([0, 2, 1, 3]) assert net.num_gates == 3 assert net.num_qubits == 2 g = net.gates assert [c.index for c in g[0].controls] == [1] assert g[0].targets == [0] assert g[0].kind == revkit.gate.gate_type.mcx
python
# Copyright 2003-2011 Nick Mathewson. See LICENSE for licensing information. """mixminion.directory.ServerInbox A ServerInbox holds server descriptors received from the outside world that are not yet ready to be included in the directory. It is designed to be written to by an untrusted user (e.g., CGI). ...
python
import numpy as np import pandas as pd def exclude_subjects(subjects, mod, reset=False): """ Utility function to denote excluded subjects Parameters ---------- subjects: list of str The subjects to be excluded mod: str The modality they are being excluded base on. fmri, eeg, e...
python
from httphmac.compat import SignatureIdentifier from httphmac.request import Request from httphmac.v1 import V1Signer from httphmac.v2 import V2Signer try: import urllib.parse as urlparse except: import urlparse as urlparse import hashlib import base64 def get_version(version): v = version.lower() if ...
python
from django.db import models from polymorphic import PolymorphicManager from bluebottle.utils.managers import GenericForeignKeyManagerMixin class PaymentManager(PolymorphicManager): def get_query_set(self): return super(PaymentManager, self).get_query_set()
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table import sys from PyQt5.QtCore import Qt, QAbstractListModel, QVariant from PyQt5.QtWidgets import QApplication, QListView class MyModel(QAbstractListModel): def __init__(self, parent): super(...
python
class Departamento: def __init__(self,nome): self._nome = nome def _get_nome(self): return self._nome def _get_funcionario(self): return self._funcionario def _get_id(self): return self._id def _set_nome(self, nome): self._nom...
python
import ure from micropython import const from robot import ucoroutine from array import array from gc import collect as gccollect issubclass = issubclass isinstance = isinstance len = len FunctionType = type(lambda x: x) GeneratorType = type((lambda: (yield))()) NoneType = type(None) CompileType = ...
python
import oemof.thermal.absorption_heatpumps_and_chillers as abs_hp_chiller import matplotlib.pyplot as plt import os import pandas as pd filename = os.path.join(os.path.dirname(__file__), 'data/characteristic_parameters.csv') charpara = pd.read_csv(filename) chiller_name = 'Kuehn' t_cooling = [...
python
#!/usr/bin/env python # coding: utf-8 # # <font color='yellow'>How can we predict not just the hourly PM2.5 concentration at the site of one EPA sensor, but predict the hourly PM2.5 concentration anywhere?</font> # # Here, you build a new model for any given hour on any given day. This will leverage readings across a...
python
""" This attempts to model the problem as a Generative Adversarial Network """ import argparse from multiprocessing import cpu_count import os import torch import torch.autograd as autograd import torch.nn as nn import torchvision as tv import tqdm from datasets import ColorDataset, GrayDataset from models import UNe...
python
# setup.py # Usage: ``python setup.py build_ext --inplace`` from distutils.core import setup, Extension import numpy setup(name='_akima', ext_modules=[Extension('_akima', ['akima.c'], include_dirs=[numpy.get_include()])])
python
__title__ = "opensearch-stac-adapter" __version__ = "0.0.5" __author__ = "Stijn Caerts"
python
import pandas as pd import requests import us from can_tools.scrapers.base import CMU from can_tools.scrapers.official.base import StateDashboard from can_tools.scrapers.util import requests_retry_session class TennesseeBase(StateDashboard): state_fips = int(us.states.lookup("Tennessee").fips) source_name = ...
python
#!/usr/bin/env python3 # # Author: Theresa Enghardt (theresa@inet.tu-berlin.de) # 2018 # # Tools to compute and plot page load timings from Navigation Timings, Resource Timings, and HAR files as exported by webtimings.py # # Usage: # ./computetimings.py RUNFILTER WORKLOAD POLICY LOG_LEVEL # ...
python
# Copyright 2018 The TensorFlow Probability Authors. # # 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...
python
# Copyright 2018 D-Wave Systems 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 applicable law or...
python
import os import subprocess import numpy os.system('alluxio runSPPrepareFile') a = 1
python
import cirpy from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.Descriptors import MolWt def mol_wt(smiles): """Get molecular weight (in Daltons)""" return MolWt(Chem.MolFromSmiles(smiles)) def canonicalize_smiles(smiles, sanitize=True, iso=False, SLN=False): """Canonicalize given SMI...
python
# Copyright 2019 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
python
# %% from concurrent.futures.thread import ThreadPoolExecutor from pathlib import Path from collections import defaultdict import librosa as li import numpy as np import subprocess import json from tqdm.auto import tqdm import re import pandas as pd from typing import * import pickle import click print("doing it") dse...
python
from flaskapp.road import RoadType, Unit class SegmentEmissions: def __init__(self): # Numbers ought to be gram per mile. self.co = 0 self.co2 = 0 self.nox = 0 self.pm25 = 0 CO_AVG_GRAMS_PER_MILE_PER_CAR = 4.152 CO2_AVG_GRAMS_PER_MILE_PER_CAR = 404.0 NOX_AVG_GRAMS_PER_MILE_...
python
# Copyright (c) 2020 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 required by appli...
python
import time from pyprintplus import Log class Request(): def __init__(self, request=None, show_log=True): self.logs = ['self.__init__'] self.started = round(time.time()) self.show_log = show_log self.request = request self.url = request.build_absolute_uri() if request else ...
python
import csv import os class ProgramFile: def __init__(self, program_file_path: str): self.result_path = './results/' self.program_file_path = program_file_path self.program_file_name = self.program_file_path.split('/')[-1] self.program_text: list = ... self.read_program_from...
python
from bot_manager import TelegramBot bot_mgr = TelegramBot() if bot_mgr.is_initialized: bot_mgr.run()
python
""" This module holds the elementary data structures used by the application """ # Standard library imports from typing import Any from typing import List from typing import Dict from dataclasses import dataclass, fields, field # Third party imports # Local imports from spotify_flows.utils.dates import date_pars...
python
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2013 Jens Lindström, Opera Software ASA # # 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...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
python
num=int(input('Digite um número de 0 até 9999:')) unidade=num%10 dezena=num//10%10 centena=num//100%10 milhar=num//1000%10 print('Unidade {}'.format(unidade)) print('Dezena {}'.format(dezena)) print('Centena {}'.format(centena)) print('Milhar {}'.format(milhar))
python
import discord import requests import bs4 import requests import random import codecs import re import pickle from telebot.types import InlineQueryResultArticle, InputTextMessageContent from kivy.uix.behaviors import button from kivy.core.window import Window from types import BuiltinMethodType, FunctionType, MethodT...
python
""" Created on Mon Oct 5 2020 @author: E. Gómez de Mariscal GitHub username: esgomezm """ import numpy as np import cv2 # from skimage.segmentation import find_boundaries import SimpleITK as sitk import tensorflow.keras from utils.utils import read_input_image, read_input_videos, one_hot_it, read_instances ...
python
### # Copyright (c) 2012-2014, spline # All rights reserved. # ### import supybot.conf as conf import supybot.registry as registry def configure(advanced): # This will be called by supybot to configure this module. advanced is # a bool that specifies whether the user identified himself as an advanced # ...
python
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_larg...
python
from django.contrib.auth.decorators import login_required from django.core.serializers import serialize from django.shortcuts import render, redirect from django.http import JsonResponse, HttpResponse from django.views.generic import ListView from django.db.models import Q from .models import Event from .form import C...
python
#!/usr/bin/env python3 import time import pygame pygame.joystick.init() try: controller = pygame.joystick.Joystick(0) controller.init() print("Name of gamepad: ", controller.get_name()) print("Number of buttons: ", controller.get_numbuttons()) print("Number of axes: ", controller.get_numaxes()) e...
python
#!/usr/bin/env python """The mirrors module defines classes and methods for Ubuntu archive mirrors. Provides latency testing and mirror attribute getting from Launchpad.""" from sys import stderr from socket import (socket, AF_INET, SOCK_STREAM, gethostbyname, error, timeout, gaierror) from tim...
python
import datetime import io import re from typing import Dict import pandas as pd import requests import requests_cache # Cache all HTTP requests hourly requests_cache.install_cache('http_cache', expire_after=3600) def date_fixer(date: str) -> datetime.date: """Reformats hard-to-use %m/%d/%y (with single digit da...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 1 19:50:04 2018 @author: Chad """ class Activity(object): def __init__(self, file_name): self.file_name = file_name+'.gpx' self.time = 0 #A helper function to pull HR data from the file and put it into a dictionary of time at int...
python
from thenewboston_node.core.logging import validates from thenewboston_node.core.utils.misc import upper_first from .exceptions import ValidationError HUMANIZED_TYPE_NAMES = { str: 'string', int: 'integer', } def validate_not_empty(subject, value): with validates(f'{subject} value'): if not valu...
python
import os import stat def handler (event): os.chmod("goshopping", stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) os.execv('/bin/sh', ['sh', 'goshopping']) # Goodbye? return "Done! Hehehe"
python
#!/usr/bin/python # # Copyright 2013 Google 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 applicable law or a...
python
# Copyright 2017 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 serial import time class RobotArm(): """Handles the serial communication with the servos/arm used for movement.""" def __init__(self, device_nam...
python
import re from .customExceptions import UnableToGetUploadTime, UnableToGetApproximateNum import degooged_tube.config as cfg from typing import Callable def tryGet(data:dict, key: str, backupVal = ""): try: return data[key] except KeyError: #if cfg.testing: # raise Exception(f"tryGet...
python
from cidc_api.models.templates.file_metadata import Upload from flask.globals import session from sqlalchemy.orm.session import Session from cidc_api.models.models import UploadJobs, with_default_session from typing import Any, Dict from datetime import date, datetime from unittest.mock import MagicMock from cidc_api....
python
""" Advent Of Code 2021 Day 5 task1 Date: 05-12-2021 Site: https://adventofcode.com/2021/day/5 """ import sys inputfile = open('../input_files/day5_input', 'r') lines = inputfile.readlines() matrix = [[0] * 1000 for _ in range(1000)] for line in lines: xy1, xy2 = line.split("->") x1, y1 = map(in...
python
# # PySNMP MIB module WL400-GLOBAL-REG (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WL400-GLOBAL-REG # Produced by pysmi-0.3.4 at Mon Apr 29 21:29:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
python
# -*- encoding: utf-8 -*- """ @File : testpyandatic.py @Time : 2020/12/6 12:28 @Author : chise @Email : chise123@live.com @Software: PyCharm @info : """ from pydantic import Field from pydantic.main import BaseModel class A(BaseModel): a: str = Field( ..., ) a = A(a="4") class B(A): ...
python
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: ''' T: O(n) and S: O(1) ''' currMax = -1 for i in range(len(arr) - 1, -1, -1): currVal = arr[i] arr[i] = currMax currMax = max(currMax, currVal) return arr
python
from dateutil.parser import parse import datetime import json from six.moves import ( configparser, input, ) import sys import twitter USAGE = '''Usage: python adiaux.py archive before_date archive - the JSON file from your downloaded twitter archive before_date - the cut-off date for tweets; tweets post...
python
""" CacheItem interface: '_id': string, 'url': string, 'response_url': string, 'body': string, 'head': string, 'response_code': int, 'cookies': None,#grab.response.cookies, TODO: WTF with cookies??? """ from hashlib import sha1 import zlib import logging import MySQLdb import marshal import time from weblib.encoding i...
python
from vk_api.longpoll import VkLongPoll, VkEventType from vk_api import VkUpload import vk_api token = "YOUR_TOKEN" def write_msg(user_id, message, random_id): vk.messages.send( user_id=user_id, random_id=0, message=message, ) def write_k_msg(user_id, message, random_id, keyboard): ...
python
from rest_framework.views import APIView from django.shortcuts import render from .models import Lecturer, Publication from .serializers import PublicationSerializer, LecturerSerializer from rest_framework import filters from .pagination import PostPageNumberPagination from rest_framework.renderers import TemplateHTMLR...
python
#Encrypted with Crypton #Created by R 4 U F import marshal,zlib,base64 exec(marshal.loads(zlib.decompress(base64.b32decode("PCOO2OLLKMNVS5VXEVAIBQIGNSBW33DR3PRQP5QYXVADZ3DBHTRGLM5WQFVLA4PECBK2HPQSRVNN24W7S2AQSTVKY2U6Z3FHMSZ2S7NEU3ZCLFIPTPFOOVHFV5WFKUS37YF4TN2UNVZM5OL5UULMNTTMH2SPEIJNXB657Z64OPH3WSZMPQ5OD73L7ALX7WGBTACX...
python
from django.urls import path from blog import views from blog.feeds import LatestArticlesFeed app_name = 'blog' urlpatterns = [ path('', views.article_list, name='article_list'), path('search/', views.article_search, name='article_search'), path('<int:year>/<int:month>/<int:day>/<slug:article_slug>/', ...
python
#!/usr/bin/env python """ .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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 ...
python
# Copyright (c) 2021 Oleg Polakow. All rights reserved. # This code is licensed under Apache 2.0 with Commons Clause license (see LICENSE.md for details) """Ultimate Python library for time series analysis and backtesting at scale. While there are many great backtesting packages for Python, vectorbt combines an extre...
python
# Copyright (c) 2018 RedHat, Inc. # 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...
python
""" Problem: stockprices Link: https://open.kattis.com/problems/stockprices Source: NWERC 2010 """ import queue import sys def runTest(): N = int(input()) buyHeap = queue.PriorityQueue() # MinHeap sellHeap = queue.PriorityQueue() # MinHeap stockPrice = None for i in range(N): ...
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import math import networkx as nx import functools import scipy.stats import random import sys import copy import numpy as np import torch import utils sys.path.append('../../build') import MatterSim class ShortestPathOracle(object):...
python
from typing import Callable, Dict, Tuple import jax import jax.numpy as np import numpy as onp def loss1_fn(x: np.ndarray) -> np.ndarray: """Compute first biobjective loss function.""" return 1 - np.exp(-np.linalg.norm(x - 1 / np.sqrt(x.shape[-1]), axis=-1) ** 2) def loss2_fn(x: np.ndarray) -> np.ndarray: ...
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "echopy", version = "1.1.0", author = "EchoPY", author_email = "echopy@protonmail.com", description= "Fisheries acoustic data processing in Python", long_description = long_descriptio...
python
# -*- coding: utf-8 -*- """Manages custom event formatter helpers.""" class FormattersManager(object): """Custom event formatter helpers manager.""" _custom_formatter_helpers = {} @classmethod def GetEventFormatterHelper(cls, identifier): """Retrieves a custom event formatter helper. Args: id...
python
import collections from typing import Callable from typing import List from typing import Optional from typing import Sequence import warnings import optuna from optuna._experimental import experimental from optuna.study import Study from optuna.trial import FrozenTrial from optuna.trial import TrialState from optuna....
python
import random import numpy as np from sum_tree import SumTree class Memory: def __init__(self, tree_memory_length, error_multiplier=0.01, alpha=0.6, beta=0.4, beta_increment_per_sample=0.001): self.tree = SumTree(tree_memory_length) self.tree_memory_length = tree_memory_length self.error_m...
python
import os import csv import config import random import argparse # Returns a number of reference and decoded text pairs along with scores from specified data. parser = argparse.ArgumentParser() parser.add_argument("-d", dest="data_name", required=False, default="data_T50...
python
#! /usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter from ResNetBlocks import * def gem(x, p=3, eps=1e-6): return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p) # return F.lp_pool2d(F.threshol...
python
import hypothesis from src.schemas import RawData, ProcessedData from src.process_data import process_data from src.train_model import train_model @hypothesis.given(RawData.strategy(size=10)) @hypothesis.settings(max_examples=100) def test_process_data(raw_data): process_data(raw_data) @hypothesis.given(Proces...
python
from controller import Robot class Spot (Robot): NUMBER_OF_LEDS = 8 NUMBER_OF_JOINTS = 12 NUMBER_OF_CAMERAS = 5 def __init__(self): Robot.__init__(self) self.time_step = int(self.getBasicTimeStep()) # keyboard self.keyboard = self.getKeyboard() self.keyboard....
python
# Copyright (c) 2021 NVIDIA Corporation. All rights reserved. # This work is licensed under the NVIDIA Source Code License - Non-commercial. # Full text can be found in LICENSE.md """ Create videos from image sequences (in json_save) """ import glob import subprocess import numpy as np import os import json import tq...
python
import os import torch import torchvision.transforms as transforms import pytest import pytorch_lightning as pl import shutil import imgaug.augmenters as iaa def test_heatmap_dataset(): from pose_est_nets.datasets.datasets import BaseTrackingDataset, HeatmapDataset data_transform = [] data_transform.appe...
python
import csv, json, os from collections import defaultdict from glob import glob import numpy as np import torch import scipy.io as sio from PIL import Image import cv2 from im_utils import read_keypoints, cropout_openpose_one_third, crop infant_root = r'/home/groups/syyeung/zzweng/code/Infant-Pose-Estimation/data/coco...
python
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from ..user import * from ..conekta_utils import * import os import jwt import json import requests import conekta import base64 from PIL import Image import StringIO conekta.api_key = 'key_ReaoWd2MyxP5QdUWKSuXBQ' conekta.api_version = "2.0.0" conekta.loc...
python
import numpy as np import scipy.sparse as sp import warnings import itertools from sklearn.model_selection import StratifiedShuffleSplit from sklearn.linear_model import LogisticRegressionCV from sklearn.metrics import roc_auc_score, average_precision_score, f1_score from sklearn.preprocessing import normalize def e...
python
import itertools from tensorboardX import SummaryWriter import Config from Buffer import Buffer from AgentControl import AgentControl from mlagents_envs.base_env import ActionTuple from collections import deque import numpy as np from TestAgent import TestAgent class Agent: def __init__(self, env, beh...
python
WAV_FROM_MP3_TYPE = T.StructType( [ T.StructField("audio_name", T.StringType()), T.StructField("audio", T.BinaryType()), ] ) @F.pandas_udf(WAV_FROM_MP3_TYPE) def wav_from_mp3_udf( audio_bytes_series: pd.Series, audio_type_series: pd.Series, audio_name_series: pd.Series, ) -> pd.Dat...
python
import os.path import random import numpy as np import cv2 import torch import dataops.common as util import dataops.augmentations as augmentations from dataops.debug import tmp_vis, describe_numpy, describe_tensor from data.base_dataset import BaseDataset, get_dataroots_paths class LRHRDataset(BaseDataset): '''...
python
import mock from django.test import TestCase from django.template import RequestContext from fancypages.test import factories class TestTextBlock(TestCase): def setUp(self): super(TestTextBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestConte...
python
# # Generated with EnvelopeCurveSpecificationBlueprint from dmt.blueprint import Blueprint from dmt.dimension import Dimension from dmt.attribute import Attribute from dmt.enum_attribute import EnumAttribute from dmt.blueprint_attribute import BlueprintAttribute from sima.sima.blueprints.moao import MOAOBlueprint cla...
python
# Будь ласка, не змінюйте версію навіть якщо ви створюєте своє програмне забезпечення на основі цього навчального коду! __version__ = 1.2
python
# -*- coding: utf-8 -*- """ shellstreaming.ostream.null ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :synopsis: ignore output records (for performance evaluation purpose) """ from shellstreaming.ostream.base import Base class Null(Base): """""" def __init__(self, **kw): """""" Base.__init__(self,...
python
""" Copyright 2019 Islam Elnabarawy 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 ...
python
from dataclasses import dataclass from typing import List from diamond_miner.defaults import UNIVERSE_SUBSET from diamond_miner.queries import GetInvalidPrefixes from diamond_miner.queries.query import LinksQuery, links_table from diamond_miner.typing import IPNetwork from diamond_miner.utilities import common_paramet...
python
import nep import time import sys msg_type = "string" # Message type to listen. node = nep.node("publisher_sample","ROS") # Create a new node pub = node.new_pub("pub_sub_test",msg_type) # Set the topic and the configuration of the publisher # Publish a message each second while True: ...
python
# # A convenient, gym-like wrapper for pybullet # https://github.com/liusida/PyBulletWrapper # # Author of this file: # 2020 Sida Liu (learner.sida.liu@gmail.com) # License: # MIT # Description: # This wrapper is the base of all other wrappers, it takes some Python tricks create a class interface for a module. # ...
python
#!/usr/bin/env python3 ''' This is a slow one, but works. ''' import scholarly import pandas as pd from csv import DictWriter def get_author_data(author): ''' Gets metadata for a single author. ''' author_data = [] print('Looking up:', author) try: a = scholarly.search_author(au...
python
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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/LICEN...
python
# Generated by Django 2.2.13 on 2021-09-09 14:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('characters', '0046_journal_stats'), ] operations = [ migrations.AlterField( model_name='character', name='num_games...
python
# -*- coding: utf-8 -*- import os import time from app import librusec from flask import render_template, request, abort, send_file, g from models import Authors, Books, Genre from readlib import extract_book RUSSIAN_LETTERS = u'АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЭЮЯ' def get_author_by_id(id_author): author = Authors.quer...
python
"""Add include_in_timeline field Revision ID: 51e93ee3ed38 Revises: 1cdc1050b92f Create Date: 2021-04-23 15:05:01.944535+00:00 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "51e93ee3ed38" down_revision = "1cdc1050b92f" branch_labels = None depends_on = None ...
python
import pyodbc from mysql import * from sqlalchemy import create_engine def mssql_121(): cstr = "Driver={SQL Server};SERVER=192.168.88.121;DATABASE=SOC_Roster;UID=sa;PWD=Robi456&" conn = pyodbc.connect(cstr) return conn def mssql(): cstr = "Driver={SQL Server};SERVER=192.168.0.108;DATABASE=SOC_Roster;...
python
""" """ import os from keras import backend as K from keras.layers import Embedding from ._mixin_common import mixedomatic if K.backend() == 'tensorflow': import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector from keras.callbacks import TensorBoard __all__ = ('TensorBoard...
python
import ftplib def connect(host,user,password): try: ftp = ftplib.FTP(host) ftp.login(user,password) ftp.quit() return True except: return False def main(): # Variables targetHostAddress = '192.168.0.103' userName = 'kuntu' passwordsFilePath = 'passwords.txt' # try to connect using a...
python
#!/usr/bin/python ################## # AndorCam.py # # Copyright David Baddeley, 2009 # d.baddeley@auckland.ac.nz # # 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 Licen...
python
import tensorflow as tf def convolutional_layer(name, inputs, filters: int, kernel_size: int, downsample: bool, batch_norm: bool, activation: str): """ An implementation of the yolov3 custom convolutional layer. Parameters ---------- name : string The name of the tensor to be used in Tens...
python