content
stringlengths
0
894k
type
stringclasses
2 values
num = str(input()) [int(i) for i in str(num)] n = sorted(num, reverse=True) print(n) if n[0] > n[1]: print(n[1]) else: buf = 0 for j in n: if n[buf] < n[0]: print(n[buf]) break else: buf += 1
python
import opensim import math import numpy as np import os from .utils.mygym import convert_to_gym import gym class Osim(object): # Initialize simulation model = None state = None state0 = None joints = [] bodies = [] brain = None maxforces = [] curforces = [] def __init__(self, ...
python
import sys import os import numpy as np import math from oct2py import octave from extract_feature import get_sequence, calc_z_curve, z_curve_fft if __name__=='__main__': taxonomy= sys.argv[1] fft_length= int(sys.argv[2]) time_length= int(sys.argv[3]) file_list= list(filter(lambda x: 'fna' == x[-3:], os.listdir(ta...
python
from .gpib_bus_server import GPIBBusServer from .gpib_device_manager import GPIBDeviceManager
python
import numpy as np class Convolution(): def initalizeParams(self): self.W = np.random.randn(self.shape[0],self.shape[1],self.shape[2],self.shape[3]) self.b = np.zeros([1,self.ksize]) # 初始化一个 w shape的矩阵,在convAdd中使用 # self.wConvAdd = np.zeros(self.windowWidth,self.windowHeight,self....
python
""" Owner: Noctsol Contributors: N/A Date Created: 2021-10-24 Summary: Just here for messing around. """ # import os # DATA_DIR = "src/data/" # with open(os.path.join(DATA_DIR, "VERSION"), "w", encoding="utf-8") as fh: # fh.write(f"2.8.8\n")
python
""" Test No Operation Operator """ import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) from gva.flows.operators import NoOpOperator try: from rich import traceback traceback.install() except ImportError: pass def test_noop_operator(): in_d = {'a':1} in_c = {'...
python
# -*- coding: utf-8 -*- """ This is the config-loading and json-loading module which loads and parses the config file as well as the json file. It handles the [General]-Section of the config. All object-getters create deepcopies. """ import logging from copy import deepcopy import hjson try: import ConfigParse...
python
import itertools import collections from pyclts import CLTS from pycldf import Sources from clldutils.misc import nfilter, slug from clldutils.color import qualitative_colors from clld.cliutil import Data, bibtex2source from clld.db.meta import DBSession from clld.db.models import common from clld.lib import bibtex fr...
python
# coding: utf-8 from .mecab_read import read_mecab_data from collections import defaultdict def Q_036(): """ 36. 単語の出現頻度 文章中に出現する単語とその出現頻度を求め,出現頻度の高い順に並べよ. """ data = read_mecab_data('data/neko.txt.mecab') noun_phrase_set = defaultdict(lambda: 0) for sent in data: for word in sent: ...
python
# -*- coding: utf-8 -*- import os import shutil import yaml # logging related packages import logging from logging.handlers import RotatingFileHandler PROJECT_DIR = os.path.dirname(os.path.realpath(__file__)) DebugConf = True #DebugConf = False model_logger = logging.getLogger('bart-web') formatter = logging.Forma...
python
from sanic.app import Sanic from sanic.blueprints import Blueprint __version__ = "19.6.0" __all__ = ["Sanic", "Blueprint"]
python
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ListView,DetailView from .models import Rating,Post from .forms import PostForm,RatingForm from django.contrib.auth.decorators import login_required from django.shor...
python
from libfmp.b import plot_matrix import numpy as np from numba import jit import matplotlib.pyplot as plt from synctoolbox.feature.filterbank import FS_PITCH, generate_list_of_downsampled_audio, get_fs_index, filtfilt_matlab,\ generate_filterbank PITCH_NAME_LABELS = [' ', ' ', ' ', ' ', ' ', ' ', ' ...
python
"""Allows light-weight profiling of code execution.""" import time class Profiler: """Collects messages with timestamps so you can profile your code.""" def __init__(self): self.clear() def add_event(self, message): milliseconds = int(round(time.time() * 1000)) self._profile...
python
#!/usr/bin/env python """ Code for Harris corner detection. """ import cv2 import numpy as np def interactive_harris(title, img): cv2.imshow(title, img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def update_harris(pos): bs_i = cv2.getTrackbarPos('bs', title) ks_i = cv2.getTrackbarPos('...
python
import logging logging.basicConfig(level=logging.DEBUG) from experiments_seminar_2 import ptl_wandb_run_builder if __name__ == "__main__": """ Best fit with multiple orders """ config_dict = { "env": { "num_dcs": 3, "num_customers": 10, "num_commodities": 5,...
python
# coding: utf-8 # # Tutorial 2 - MicaSense library # # This tutorial assumes you have gone through the [basic setup](./Micasense Image Processing Setup.html) and builds on the basic radiance, irradiance, and reflectance concepts and code covered in the [first tutorial](./MicaSense Image Processing Tutorial 1.html). ...
python
""" For each Results/Final/LargeSet_20180106/ subfolder: alpha maxiter lsiterations population eliteprop mutantprop generations inheritance create list of results ex: alpha_results = { 'paramval': get from file, ...
python
""" Problem: You come across a dictionary of sorted words in a language you've never seen before. Write a program that returns the correct order of letters in this language. For example, given ['xww', 'wxyz', 'wxyw', 'ywx', 'ywz'], you should return ['x', 'z', 'w', 'y']. """ from typing import Dict, List, Optional, ...
python
# -*- coding: utf-8 -*- from typing import List from decibel.tab_chord_parser.segment import Segment from decibel.tab_chord_parser.line_type import LineType from decibel.tab_chord_parser.line import Line from decibel.tab_chord_parser.system import System def find_systems(segment: Segment): system_nr = 0 syst...
python
import argparse import asyncio import getpass import logging import os import sys import traceback import yaml import pkg_resources from aiohttp import web from colorlog import ColoredFormatter from pathlib import Path from rest_api.intkey_client import IntkeyClient from rest_api.exceptions import IntKeyCliException...
python
# -*- coding: utf-8 -*- def str_dict(str_headers): di = [] try: for i in str_headers.split("\n"): he = i.split(": ", 1) if he != [""]: di.append(he) return dict(di) except ValueError as error: print("请把请求类型一行去掉:POST /xxx/xxx/xxx HTTP/1.1" + "...
python
#!/usr/local/bin/python3 import torch # Element-wise , componenet-wise, point-wise # If the two tensors have the same shape, we can perform element wise # operations on them. +-*/ are all element wise operations. # Returns a tensor filled with random numbers from a uniform # distribution on the interval [0,1) t1 = to...
python
import tensorflow.contrib.learn as skflow from sklearn import datasets, metrics iris = datasets.load_iris() classifier_model = skflow.LinearClassifier(feature_columns=[tf.contrib.layers.real_valued_column("", dimension=iris.data.shape[1])], n_classes=3) classifier_model.f...
python
'''Author: Sourabh Bajaj''' import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages setup( name='QSTK', version='0.2.8.2', author='Sourabh Bajaj', packages=find_packages(), namespace_packages=['QSTK'], include_package_data=True, long_description=open('README.md...
python
from typing import Any __all__ = ["AttrDict"] class AttrDict(dict): """ Wrapper of dict class, to allow usage of attribute notation (instance.key) in place of index notation (instance["key"]). Can be used as a mixin for Mappings. """ def __getattr__(self, item: str) -> Any: if item ...
python
from django.conf.urls import url from zebra import views urlpatterns = [ url(r'webhooks/$', views.webhooks, name='webhooks'), url(r'webhooks/v2/$', views.webhooks_v2, name='webhooks_v2'), ]
python
# Copyright 2019 Huawei Technologies Co., Ltd # # 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
import pandas as pd import time #------------------------------------ #loading dataset begin = time.time() df = pd.read_csv("adult.data" , names=["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-w...
python
#Author: Zhicheng Zhu #Email: zhicheng.zhu@ttu.edu, yisha.xiang@ttu.edu #copyright @ 2018: Zhicheng Zhu. All right reserved. #Info: #main file to solve multi-stage DEF of CBM model by using linearization and solver # #Last update: 10/18/2018 #!/usr/bin/python from __future__ import print_function import sys import cp...
python
""" ██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ ██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝ ██║ ██║██████╔╝███████║█████╗ ╚████╔╝ ██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝ ╚██████╗██║██║ ██║ ██║███████╗ ██║ © Brandon Skerritt Github: brandonskerritt """ from copy import copy from distutils import util f...
python
from django.contrib import admin from .models import Coach, Comment class CoachAdmin(admin.ModelAdmin): list_display = ( 'id', 'first_name', 'last_name', 'email', 'phone_number', 'image', ) ordering = ('first_name',) class CommentAdmin(admin.ModelAdmin): ...
python
# Generated by Django 3.0 on 2020-12-03 14:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('manager', '0001_initial'), ] operations = [ migrations.AlterField( model_name='activity', name='amount', f...
python
from enum import Enum, IntEnum from pathlib import Path from typing import List, Literal, Optional, Union from pydantic import BaseModel import tomlkit # type: ignore (no stub) from .iec_62056_protocol.obis_data_set import ( ObisFloatDataSet, ObisId, ObisIntegerDataSet, ObisStringDataSet, ) def loa...
python
from telegram.ext import Dispatcher,CommandHandler,CallbackQueryHandler from telegram import InlineKeyboardMarkup,InlineKeyboardButton, BotCommand import random def whoAreYou(update,context): msg = [ """You can call me Operation Lune 9000, I'm actually just a random reply AI(not really)""", """Bro,...
python
import datetime, pytz from dateutil.tz import tzlocal log_dir = None verbose = False def log(message): ts = pytz.utc.localize(datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] if verbose: print(f'{ts} {message}') if log_dir is not None: print(f'{ts} {message}', file=open(log_d...
python
from WMCore.WMException import WMException class WMSpecFactoryException(WMException): """ _WMSpecFactoryException_ This exception will be raised by validation functions if the code fails validation. It will then be changed into a proper HTTPError in the ReqMgr, with the message you enter used...
python
#! python3 from __future__ import print_function import SimpleITK as sitk import numpy as np import sys import os # def LocalFusionWithLocalSimilarity(targetImage, registeredAtlases, outputPath, debug): """" Fuses the labels from a set of registered atlases using local similarity metrics. Arguments: ...
python
def create_adjacency_list(num_nodes, edges): graph = [set() for _ in range(num_nodes)] for index, edge in enumerate(edges): v_1, v_2 = edge[0], edge[1] graph[v_1].add(v_2) graph[v_2].add(v_1) return graph
python
""" Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk 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 ...
python
import glob import pandas as pd from pathlib import Path import re import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.patches as patches import os def transformCordinates(coordinates, wmax, hmax): maxis = coordinates[0] minaxis = coordinates[1] angle = c...
python
""" Setup to install the 'factorymind' Python package """ import os from setuptools import find_packages, setup def read(file_name: str): """Utility function to read the README file. Used for the long_description. It's nice, because now 1) we have a top level README file and 2) it's easier...
python
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-list-negativeInteger-enumeration-1-NS" class NistschemaSvIvListNegativeIntegerEnumeration1Type(Enum): VALUE_17702143_68213_73070785813457_55650_85440493680_6799621_74925_12_725375920010560...
python
""" The go starter template. Author: Tom Fleet Created: 24/06/2021 """ import shutil import subprocess from pathlib import Path from typing import List, Optional from pytoil.exceptions import GoNotInstalledError from pytoil.starters.base import BaseStarter class GoStarter(BaseStarter): """ The go starter ...
python
# Generated by Django 3.0.7 on 2020-10-30 16:41 from django.db import migrations import inclusive_django_range_fields.fields class Migration(migrations.Migration): dependencies = [ ('jobsapp', '0011_auto_20201030_1636'), ] operations = [ migrations.AddField( model_name='job'...
python
from operator import eq, ge from functools import partial import pandas as pd from microsetta_public_api.resources import resources ops = { 'equal': eq, 'greater_or_equal': ge, } conditions = { "AND": partial(pd.DataFrame.all, axis=1), "OR": partial(pd.DataFrame.any, axis=1) } def _is_rule(node): ...
python
# Copyright (C) 2019 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 agreed to in writing, ...
python
from unittest.mock import patch import pytest from telegram.ext import CommandHandler from autonomia.features import dublin_bike @pytest.mark.vcr def test_cmd_dublin_bike(update, context): with patch.object(update.message, "reply_text") as m: context.args = ["89"] dublin_bike.cmd_dublin_bike(upd...
python
# All content Copyright (C) 2018 Genomics plc from wecall.bamutils.read_sequence import HIGH_QUALITY from wecall.bamutils.sequence_builder import sequence_builder class SequenceBank(object): """ A container to hold annotated DNA sequences in relation to a reference sequence. """ def __init__(self, re...
python
# # PySNMP MIB module ZHONE-GEN-INTERFACE-CONFIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-GEN-INTERFACE-CONFIG-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:47:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
python
from typing import Any from rpg.items import Equippable class Armor(Equippable): config_filename = "armor.yaml" __slots__ = ("type",) def __init__(self, **kwargs: Any): self.type: str = kwargs.pop("type") super().__init__(**kwargs) def __repr__(self) -> str: return f"<{sel...
python
from .dual_network import DualNetBounds, robust_loss, robust_loss_parallel, DualNetwork from .dual_layers import DualLinear, DualReLU from .dual_inputs import select_input, InfBallBoxBounds from .utils import DenseSequential, Dense, epsilon_from_model
python
import a1 #$ use=moduleImport("a1") x = a1.blah1 #$ use=moduleImport("a1").getMember("blah1") import a2 as m2 #$ use=moduleImport("a2") x2 = m2.blah2 #$ use=moduleImport("a2").getMember("blah2") import a3.b3 as m3 #$ use=moduleImport("a3").getMember("b3") x3 = m3.blah3 #$ use=moduleImport("a3").getMember("b3").ge...
python
from .users import * # importamos todas las clases del archivo circle.
python
# -*- coding: utf-8 -*- # Copyright 2014 Red Hat, 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 l...
python
# Copyright (c) OpenMMLab. All rights reserved. import copy import warnings from typing import Dict, Iterable, Optional import torch import torch.nn as nn from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, ...
python
import argparse import gym from gym import wrappers import os.path as osp import random import numpy as np import tensorflow as tf import tensorflow.contrib.layers as layers import dqn from dqn_utils import * from atari_wrappers import * def cartpole_model(img_in, num_actions, scope, reuse=False): # as described...
python
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
python
# %% consumer_key = "idBfc3mYzrfBPxRM1z5AhXxAA" consumer_secret = "K50925I1FObqf6LA8MwiUyCBWlOxtrXXpi0aUAFD0wNCFBPQ3j" access_token = "1245495541330579457-6EBT7O9j98LgAt3dXxzsTK5FFAA2Lg" access_secret = "jUP2N1nHeC6nzD30F4forjx7WxoOI603b4CqHdUnA6wqL" # %% import tweepy auth = tweepy.OAuthHandler(consumer_key, consu...
python
""" Copyright 2011 Lars Kruse <devel@sumpfralle.de> This file is part of PyCAM. PyCAM 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. PyCA...
python
# SPDX-License-Identifier: BSD-3-Clause # Depthcharge: <https://github.com/nccgroup/depthcharge> """ U-Boot environment variable parsing and handling functionality """ import copy import os import re from zlib import crc32 from .. import log from ..arch import Architecture # This is a bit bonkers because U-Boot le...
python
# Function to add looted inventory to player inventory def addToInventory(inventory, addedItems): for loot in addedItems: if loot in inventory: inventory[loot] = inventory[loot] + 1 else: inventory.setdefault(loot, 1) return inventory # Function to display inventory def ...
python
import requests url = 'https://images-api.nasa.gov/search?q=Ilan%20Ramon' image_metadata_url= 'https://images-assets.nasa.gov/image/{0}/metadata.json' #KSC-03pd2975/metadata.json' # params = dict( # origin='Chicago,IL', # destination='Los+Angeles,CA', # waypoints='Joplin,MO|Oklahoma+City,OK', # sensor...
python
import multiprocessing import os from argparse import ArgumentParser from pathlib import Path import torch from nflows import distributions, transforms from pyprojroot import here from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.loggers import WandbLogger from torch.utils.data import DataL...
python
# Generated by Django 2.2.5 on 2019-09-07 04:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bhs', '0002_group_pos'), ] operations = [ migrations.AlterField( model_name='group', name='chapters', fi...
python
# Authors: # Loic Gouarin <loic.gouarin@polytechnique.edu> # Benjamin Graille <benjamin.graille@universite-paris-saclay.fr> # Thibaut Van Hoof <thibaut.vanhoof@cenaero.be> # # License: BSD 3 clause from .model import ModelWidget from .test_case import TestCaseWidget from .lb_scheme import LBSchemeWidget fr...
python
""" Пул воркеров. Полное управление и контроль воркерами. """ import logging import threading from functools import partial from multiprocessing import Pool, cpu_count, Queue, Process logger = logging.getLogger(__name__) class Worker(Process): """ Свой процесс. Тут мы вызываем команду. """ def __i...
python
import sys import tempfile from textwrap import dedent import _pytest import pytest import yaml from mock import Mock from mock import patch from tavern.core import run from tavern.schemas.extensions import validate_file_spec from tavern.testutils.helpers import validate_pykwalify from tavern.testutils.helpers import...
python
import copy import os import json from hpbandster.core.base_iteration import Datum class Run(object): """ Not a proper class, more a 'struct' to bundle important information about a particular run """ def __init__(self, config_id, budget, loss, info, time_stamps, error_logs): self.config_id = config_id s...
python
userColors = []
python
class AbstractRequest(object): opcode = -1 class AbstractRequestCodec(object): @staticmethod def decode(payload): raise NotImplementedError @staticmethod def encode(request): raise NotImplementedError
python
import cairo import math import random import sys import os sys.path.append(os.path.abspath('..')) from lib import palettes from lib import colors # Final image dimensions IMG_HEIGHT = 2000 IMG_WIDTH = int(IMG_HEIGHT * (16/9)) SPACING = 2 def line(ctx, y, line_interval, color, x_increment=(IMG_WIDTH // 40)): li...
python
from typing import Callable, Sequence, Union, TYPE_CHECKING import io from enum import Enum if TYPE_CHECKING: from .expressions import ( ReadSubstitute, WriteSubstitute, ) from .arguments import UncompiledArgument PublicArgument = Union[ str, int, float, 'ReadSubstitute',...
python
from main.game.ConvertStringArray import historyToArray from main.game.verifyCheck import verificarCheck def especialMove(allpieces,piece,history): history = historyToArray(history) if history != ['']: if piece[0] == 'p': return EnPassant(piece,history) elif piece[0] == 'k': ...
python
eps = 10e-7
python
from ..geometry import np import math class Quaternion(object): def __init__(self, coeffs=[0., 0., 0., 1.]): self._coeffs = np.array(coeffs) def vec(self): return self._coeffs[0:3] def coeffs(self): return self._coeffs def normalize(self): norm = np.linalg.norm(self....
python
from django.http import HttpResponse from django.shortcuts import render from webcam_manager import * import time webcam_manager = WebcamManager() encryption_manager = EncryptionManager() webcam_manager.start() def make_aes_response(response_data): response = encryption_manager.get_aes_packet(response_data) ...
python
import json import numpy as np import os from env_rl import EnvRL from pathlib import Path def score_rl_solution(submission_filepath='example_output_rl.json', final_submission=False): base_path = Path(__file__).parent.absolute() test_data_instance_path = base_path.joinpath('data/valid/instances') test_dat...
python
# Reference: https://leetcode.com/problems/number-of-islands/ # Approach: # 1. Get a list of all locations that have 1 # 2. Iterate through this list and call DFS for every unmarked / unvisited 1 and mark all it's reachable locations with the current_island_count # 3. The final value of current_island_count is the ans...
python
from socket import *
python
from __future__ import unicode_literals import frappe import json from toolz.curried import compose, merge, map, filter @frappe.whitelist() def query(doctype, txt, searchfield, start, page_len, filters): station = filters.get("station") cond = ( " OR ".join( [ "so.initial_s...
python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE.txt file in the root directory of this source tree. import argparse import json import os import os.path import random from typing import...
python
__author__ = 'rogerjiang' ''' Purpose: 1. Data augmentation, including: 1.1 random translation in horizontal and vertical directions 1.2 horizontal and vertical flipping 1.3 random rotation ''' ''' Class blancing: Each class is trained using a different model, weights should be applied to the tr...
python
# Tests should generate (and then clean up) any files they need for testing. No # binary files should be included in the repository. import json import event_model from suitcase.mongo_embedded import Serializer import pytest def test_export(db_factory, example_data): """ Test suitcase-mongo-embedded serialize...
python
#!/usr/bin/env python import json import os import logging from ruv_dl.constants import CACHE_LOCATION, CACHE_VERSION, CACHE_VERSION_KEY logger = logging.getLogger(__name__) class CacheVersionException(Exception): pass class DiskCache: def __init__(self, program_id): self.location = os.path.join(C...
python
import socket, time, signal def resolves(domain, timeout): try: socket.gethostbyname(domain) return True except socket.gaierror: return False
python
from __future__ import annotations from typing import Union, List, Set, FrozenSet, Optional, Dict, IO, Callable from pathlib import Path from gd2c.project import Project from gd2c.target import Target from gd2c.gdscriptclass import GDScriptClass, GDScriptFunction, GDScriptMember, GDScriptGlobal from gd2c.targets._gdnat...
python
from django import template from django.conf import settings from django.urls import reverse from django.utils.html import format_html from django_gravatar.helpers import get_gravatar_url register = template.Library() @register.simple_tag def user_link(user): gravatar_url = get_gravatar_url(user.email, size=16) ...
python
# -*- coding: utf-8 -*- """ Test of the non-stationary poisson process sampling func. """ import numpy as np import simpy from forecast_ed.sampling import nspp fname = 'data/arrivals.csv' data = np.genfromtxt(fname, delimiter=',', skip_header=1) arrivals = [] def generate(env): a = nspp(d...
python
from dotenv import load_dotenv import os import requests load_dotenv() import json API_URL=os.getenv("shopify_product_url") url=API_URL+'?limit=250' products=[] headers={'Content-Type': 'application/json'} r=requests.get(url,headers=headers) products=products+r.json()['products'] header_link=r.headers['Link'] header_...
python
from .base_state import * from .channel_state import * from .emoji_state import * from .guild_state import * from .message_state import * from .role_state import * from .user_state import *
python
from django.urls import re_path from .views import SettingsView, UpdateSettingsView app_name = "baserow.api.settings" urlpatterns = [ re_path(r"^update/$", UpdateSettingsView.as_view(), name="update"), re_path(r"^$", SettingsView.as_view(), name="get"), ]
python
# coding: utf-8 """Test device 1.""" from . import release from .TestDevice1 import TestDevice1 from .TestDevice2 import TestDevice2 __version__ = release.__version__ __version_info__ = release.__version_info__
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import threading import sys import time from filesocket import filesocket '''path to temporary directory used for file sockets''' SOCKSER_DIR ='' '''SOCKS5 RFC described connection methods''' CONNECT = 1 BIND = 2 UDP_ASSOCIATE = 3 '''SOCKS5 RFC described...
python
from django.urls import path from . import views urlpatterns = [ path('friendrequest', views.send_friend_request, name="send_friend_request"), path('friendrequest/handle', views.handle_friend_request, name="handle_friend_request"), path('friendrequest/<slug:author_id>/', views.retrieve_fri...
python
import itertools import sys import os from rdkit import Chem from rdkit.Chem import rdMolTransforms, rdMolAlign import openbabel from qmconftool import QMMol def find_dihedral_idx(mol,smarts_patt): patt_mol = Chem.MolFromSmarts(smarts_patt) matches = mol.GetSubstructMatches(patt_mol) unique_match...
python
"""Root of podpointclient"""
python
import unittest from cpuinfo import * import helpers class MockDataSource_enforcing(object): @staticmethod def has_sestatus(): return True @staticmethod def sestatus_b(): returncode = 0 output = r''' SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root dire...
python
from .context_processors import * from .middleware import * from .templatetags import * from .http_client import *
python