content
stringlengths
5
1.05M
import json import urllib.request import urllib.error import urllib.parse import sys import subprocess import random import os import lyricsgenius import multiprocessing from shared.config import Config from profanity import profanity from datetime import datetime from shared.set_username import SetUsername from fortun...
import pytest import shutil from pathlib import Path import numpy as np import pysd @pytest.mark.parametrize( "model_path,subview_sep,variables,modules,n_deps,dep_vars", [ ( # split_views Path("more-tests/split_model/test_split_model.mdl"), [], ["stock"], ...
import collections from datetime import datetime import importlib import json import re from unittest.mock import patch import pytest from django.contrib.auth.models import AnonymousUser from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.paginator i...
import mock import unittest from wsme import exc from wsme.rest import args from wsme.rest import json class TestArgs(unittest.TestCase): def test_args_from_body(self): funcdef = mock.MagicMock() body = mock.MagicMock() mimetype = "application/json" funcdef.ignore_extra_args = T...
import re YOUTUBE_HEADERS: dict = { "x-youtube-client-name": "1", "x-youtube-client-version": "2.20201030.01.00", } CONTINUATIONS_CONTEXT: dict = { "client": {"clientName": "WEB", "clientVersion": "2.20211019.06.00"} } DATA_JSON = re.compile(r'(?:window\["ytInitialData"\]|ytInitialData)\W?=\W?({.*?});') ...
from __future__ import absolute_import, division, print_function, unicode_literals import json import unittest from amaascore.market_data.curve import Curve from amaascore.tools.generate_market_data import generate_curve class CurveTest(unittest.TestCase): def setUp(self): self.longMessage = True # Pri...
from antarest.study.storage.rawstudy.model.filesystem.config.model import ( FileStudyTreeConfig, ) from antarest.study.storage.rawstudy.model.filesystem.context import ( ContextServer, ) from antarest.study.storage.rawstudy.model.filesystem.folder_node import ( FolderNode, ) from antarest.study.storage.raws...
# Copyright 2020 The TensorFlow 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 applica...
import numpy as np import open3d as o3d def create_open3d_point_cloud(point_cloud): indices = np.all(np.isfinite(point_cloud.xyzs()), axis=0) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(point_cloud.xyzs()[:, indices].T) if point_cloud.has_rgbs(): pcd.colors = o3d....
#py_dict.py the_dict = {"key":"value", "A":2, "B":3} same_dict = dict(key="value", A=2, B=3) print("Dict compare :", the_dict == same_dict) print("And here's the dict:", the_dict) the_dict['C']=3 print("... and again:", the_dict) my_value=the_dict.get('D', "some default value") print("... and yet again:", the_dic...
#Paperclip experiment from vsauce video "The Zipf Mystery" import sys import random import argparse class Paperclip: def __init__(self, id_): self.id_ = id_ self.chain = [self] def __repr__(self): return str(self.id_) + " : " + self.print_chain() def print_chain(self): s = "" for paperclip in self.chai...
from django.conf import settings from django_hbase.client import HBaseClient from django_hbase.models import HBaseField, IntegerField, TimestampField from django_hbase.models.exceptions import BadRowKeyError, EmptyColumnError class HBaseModel: class Meta: table_name = None row_key = () @clas...
#!/usr/bin/env python2.7 # -*- coding: UTF-8 -*- from sys import stdin from collections import defaultdict import argparse import re import time from importlib import import_module def main(): # Try begin try: # Import common module for shared operations common = import_module(...
# Generated by Django 3.0.3 on 2020-05-17 23:16 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("main", "0009_notification_is_active"), ] operations = [ migrations.AlterField( model_name="noti...
"""Default color theme """ class ColorTheme: """Color theme. """ def __init__(self, textFormatClass): """Constructor gets TextFormat class as parameter for avoid cross-import problems """ self.format = { 'dsNormal': textFormatClass(), 'dsKeyword': ...
""" Complete this function such that it returns True if and only if the two strings passed to the function are anagrams of each other, that is if they contain the same letters the same number of times. Return False otherwise. """ def is_anagram(string_a, string_b): # Delete pass, and put your code here. pass ...
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import logging from typing import Optional from ..configuration import Configuration from ..errors import Errors from ..repository ...
""" Item 47: Use __getattr__, __getattribute__, and __set__attr__ for Lazy Attributes Use __getattr__ and __setattr__ to lazily load and save attributes for an object. Understand __getattr__ only gets called when accessing a missing attribute while __getattribute__ gets called every time any attribute is accessed. Use...
from django.urls import reverse from rest_framework.test import APITestCase, APIClient from rest_framework.views import status from .models import Competicao from .serializers import CompeticaoSerializer from django.utils import timezone class BaseViewTest(APITestCase): client = APIClient() @staticmethod ...
from indra.statements import Agent, Evidence, Translocation, Phosphorylation from indra.tools.fix_invalidities import * import indra.tools.assemble_corpus as ac def test_fix_db_refs(): assert fix_invalidities_db_refs({'CHEBI': '123'}) == \ {'CHEBI': 'CHEBI:123'} assert fix_invalidities_db_refs({'CH...
#!/usr/bin/env python import json import os import time from random import choice from locust import HttpLocust from locust import task from locust import TaskSet try: import urllib.request as urlrequest except ImportError: import urllib as urlrequest USERNAME = os.getenv("LOCUST_USERNAME") or "a@a.com" PASSW...
from flask import Flask, request, jsonify, make_response, session from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import uuid from werkzeug.security import generate_password_hash, check_password_hash import jwt import datetime from functools import wraps import os from ..database import db from ..m...
from django.http import HttpResponse from django.shortcuts import render, redirect # Create your views here. from django.urls import reverse def index(request): print("hello world") return HttpResponse("index") def haha(request): print('呵呵') jump_url = reverse('user:jump') return redirect(jump_...
import numpy as np def generate_linear_regression(intercept, slope, sd=.2, size=700): x = np.random.uniform(-10, 10, size) y = intercept + x * slope return x, y + np.random.normal(size=size, scale=sd) def generate_sinus_regression(intercept, slope, sd=.2, size=700): x = np.random.uniform(-10, 10, si...
print ("how old are you?",end='') age=input() print ("how tall are you?",end='') height=input() print ("how much do you weight?",end='') weight=input() print(f"so, you're {age}old,{height}tall and {weight} heavy.")
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.utils.rnn import PackedSequence from typing import Optional, Tuple from lib.fpn.box_utils import nms_overlaps from lib.word_vectors import obj_edge_vectors from .highway_lstm_cuda.alternating_h...
import setuptools with open("README.rst","r") as f: long_description = f.read() setuptools.setup( name="xrdownloader", version="1.0.6", author="XploitsR Author (solomon narh)", author_email="solomonnarh97062@gmail.com", maintainer="XploitsR Authors", maintainer_email="xploitsr@gmail.com", plat...
#$Id$ class Term: """This class is used to create object for terms.""" def __init__(self): """Initialize parameters for terms.""" self.invoice_terms = '' self.estimate_terms = '' self.creditnotes_terms = '' def set_invoice_terms(self, invoice_terms): """Set invoice ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 邻接矩阵 顶点个数为V,则邻接矩阵可以使用V x V的二维数组表示; g[i][j]表示定点i和定点j的关系; 无向图可以使用0/1表示是否有连接; 带权图使用INF表示; """ class DirectedGraphNode(object): """有向图""" def __init__(self, x): self.label = x self.neighbors = [] class UnDirectedGraphNode...
# Euler discovered the remarkable quadratic formula: # # n2+n+41 # It turns out that the formula will produce 40 primes for the consecutive integer values 0≤n≤39. However, when n=40,402+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,412+41+41 is clearly divisible by 41. # # The incredible formula n2−79n+...
def about(name,age,likes): sentence = "Meet {}! They are {} years old and they like {}".format(name, age, likes) return sentence # function with default values. Defaults must be at the end def about2(name, age, likes = "Python"): sentence = "Meet {}! They are {} years old and they like {}".format(n...
"""Tests for module, within pagapp creates.""" from logging import ERROR import unittest from unittest.mock import patch from unittest.mock import MagicMock from pagapp.create_pagapp import create_pagapp, register_blueprints, \ setup_logging, check_folders class CreatePagappTestCase(unittest.TestCase): """T...
import itertools, copy, warnings import numpy as np from functools import reduce from collections import defaultdict, Counter from hacktrick_ai_py.utils import pos_distance, read_layout_dict, classproperty from hacktrick_ai_py.mdp.actions import Action, Direction class Recipe: MAX_NUM_INGREDIENTS = 5 LAPTOP ...
from unittest.mock import patch from rasa_sdk.events import SlotSet from covidflow.actions.action_daily_ci_early_opt_out import ActionDailyCiEarlyOptOut from covidflow.constants import CONTINUE_CI_SLOT from .action_test_helper import ActionTestCase class ActionDailyCiEarlyOptOutTest(ActionTestCase): def setUp(...
#!/usr/bin/env python from __future__ import absolute_import """Unit tests for M2Crypto.RSA. Copyright (c) 2000 Ng Pheng Siong. All rights reserved.""" import hashlib import logging import os try: import unittest2 as unittest except ImportError: import unittest from M2Crypto import BIO, RSA, Rand, X509, m2,...
from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.drm.aes.aes_api import AesApi from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.drm.aes.customdata.customdata_api import CustomdataApi from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.drm.aes.aes_encryption_drm_list_query_params import AesEncryptionDrmListQ...
import os import re import threading import time from datetime import datetime from math import cos, sin import logging import platform import kivy import numpy as np import obd from kivy.app import App from kivy.clock import Clock, mainthread from kivy.config import Config from kivy.lang import Builder from kivy.prop...
from django.db import models from django.utils import timezone import datetime class UserData(models.Model): user_name = models.TextField(max_length = 20, blank="True") visit_lank = models.IntegerField(blank="True", default=1) study_lank = models.TextField(max_length = 1000, blank="True", default="1_1_1_1_...
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import request, session from marshmallow_enum import E...
from setuptools import setup, find_packages from os import path from io import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='irt', version='0.0.2', description='Item Response Theory in Python',...
import numpy as np from cho_util.math.rotation import _matrix from cho_util.math.rotation import _quaternion from cho_util.math.rotation import _euler from cho_util.math.rotation import _axis_angle from cho_util.math.rotation._euler import * def to_matrix(x, *args, **kwargs): return _matrix.from_euler(x, *args, ...
from setuptools import setup setup( name='markdown-tabs', version='1.0', py_modules=['markdown-tabs'], install_requires=['markdown>=2.5'] )
from .remittance import RemittanceException from .remittance import AbstractInvoiceLineItem from .utilities import enrich_field from .utils import p class Invoice(AbstractInvoiceLineItem): """Normal Invoice""" def __str__(self): return ' Invoice {}'.format(repr(self)) def enrich(self, remittance...
import queue import os import csv def is_undirected_graph_circled(adj_matrix): n = len(adj_matrix) degrees = [0] * n visited = [] q = queue.Queue() for i in range(0, n): degrees[i] = sum([int(value) for value in adj_matrix[i]]) if degrees[i] <= 1: ...
import inspect import logging import os import re import shutil from pathlib import Path import tensorflow as tf from config import CkptConfig class Saver(object): """ https://www.tensorflow.org/guide/saved_model?hl=zh-CN 主要实现 TensorFlow save 和 load 的统一管理,防止格式不统一造成不方便; 所有模型使用同一种命名格式保存 model-0.01-0.9.ckp...
from django.db import models from user.models import User # Create your models here. class Post(models.Model): # 不使用外键关联,通过定义字段 uid = models.IntegerField() title = models.CharField(max_length=64) created = models.DateTimeField(auto_now_add=True) content = models.TextField() @property def aut...
class NotKnownType: """ Singleton for 'NotKnown' constant """ not_known_single_instance = None def __new__(cls): if cls.not_known_single_instance is None: cls.not_known_single_instance = super().__new__(cls) return cls.not_known_single_instance NotKnown = NotKnownType() ## t...
import argparse import urllib3 import requests import os import json import time import urllib import socket import jsonlines parser = argparse.ArgumentParser() parser.add_argument('--input_file', default="batchE.txt", help="input jsonlines file") args = parser.parse_args() with open(args.input_file, "r+", encoding="u...
#!/usr/bin/env python import sys tw = sys.argv[1].split(",") top_words = {word:0 for word in tw} #--- get all lines from stdin --- for line in sys.stdin: line = line.strip() words = line.split() t_words = dict(top_words) li = [] for word in words: if word in t_words: ...
# Resize image import cv2 import os from plantcv.plantcv import print_image from plantcv.plantcv import plot_image from plantcv.plantcv import fatal_error from plantcv.plantcv import params def resize(img, resize_x, resize_y): """Resize image. Inputs: img = RGB or grayscale image data to resize ...
"""Metadata of package.""" __version__ = '2.1.0' __title__ = 'mimesis' __description__ = 'Mimesis: mock data for developers.' __url__ = 'https://github.com/lk-geimfari/mimesis' __author__ = 'Likid Geimfari (Isaak Uchakaev)' __author_email__ = 'likid.geimfari@gmail.com' __license__ = 'MIT License'
""" .. module:: test_plotter :synopsis: Unit tests for plotter module """ from __future__ import print_function import os import numpy as np import nutsml.imageutil as ni import nutsml.plotter as pl import numpy.testing as nt from nutsflow import Collect # Set to True to create test data CREATE_DATA = False de...
# coding: utf8 # tente algo como def index(): form = SQLFORM.grid(db.EVENTOS, fields=[db.EVENTOS.NOME_EVENT, db.EVENTOS.TAXA_DOLAR, db.EVENTOS.ATUAL ], buttons_placement='left', showbuttontext=False, # Exibe os botões _class='web2py_grid', exportcla...
import pytest from shipchain_common.mixins import MultiSerializerViewSetMixin, MultiPermissionViewSetMixin class FakePermission: name = 'fake1' def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name class FakePermission2(FakePermission): name =...
""" EXT. Title: BUzzer test, beeping Author: Fin Mead, Meadeor. Desc:Functional test script for buzzer/siren (For the NXP HoverGames Competition//hackster.io) """ #imports import RPi.GPIO as GPIO import time #GPIO setup GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.OUT) #beeping loop...
import random async def reply(activity, bot, data): responses = [ "Your time!", "For formality's sake 'nothing much'", "My lawyer says I don't have to answer that question", "Ironing my blazer, Shaadi nahi hain meri, NBA Inspection hai. Pata nahi kya kya karna padta hai.", ...
# -*- coding: utf-8 -*- import calendar from datetime import datetime import unittest from doodle.core.models.base_model import PropertiedModel from doodle.core.property import BooleanProperty, DateTimeProperty, FloatProperty, IntegerProperty, ListProperty, Property, StringProperty class Model1(PropertiedModel): ...
from django.db.models import Q from rest_framework import filters class TeacherOrOwnedOnly(filters.BaseFilterBackend): """ If the requesting user isn't a teacher, filter queryset to their own objects only """ def filter_queryset(self, request, queryset, view): if not request.user.is_teach...
from sds.models.rarhmm import RecurrentAutoRegressiveHiddenMarkovModel as Ours from ssm.hmm import HMM as Theirs import warnings warnings.simplefilter(action='ignore', category=FutureWarning) # np.random.seed(1337) T = [900, 950] true_rarhmm = Theirs(3, 2, observations="ar", transitions="recurrent") true_z, x = []...
import pytest import sys from mocona.events import EventEmitter def test_on_strong_function(): a = 1 def f(): nonlocal a a += 1 E = EventEmitter() E.on("my.event", f, weak=False) E.emit("my.event") assert a == 2 a = 1 E = EventEmitter() E.on.my.event(f, weak=Fals...
import logging from collections import deque from contextlib import AsyncExitStack, asynccontextmanager from types import MappingProxyType from typing import ( Any, Callable, Deque, Dict, List, Mapping, NamedTuple, Optional, Set, Union, ) from supriya.clocks import Moment from s...
from app import db import datetime class ShellLogModel(db.Model): __tablename__ = 'shell_logs' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, default=0, index=True, nullable=True) command = db.Column(db.Text, nullable=True) output = db.Column(db.Text, nullable=True) ...
import os; import subprocess; import platform; # GLFW class class GLFW : @classmethod def Exists(cls) : return os.path.isdir("Thirdparty/glfw"); @classmethod def Add(cls) : dir = os.getcwd(); os.chdir("Thirdparty"); subprocess.call("git clone https://github.com/glfw/glfw glfw...
import copy import os import shutil import grass.script as grass import grass.script.setup as gsetup import pandas as pd import pytest from grass.pygrass.modules import Module from grass.pygrass.modules.shortcuts import general as g from grass.pygrass.modules.shortcuts import raster as r from grass.script import array...
import inspect from functools import total_ordering, wraps from os.path import join, dirname def yield_once(iterator): """ Decorator to make an iterator returned by a method yield each result only once. >>> @yield_once ... def generate_list(foo): ... return foo >>> list(generate_list(...
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- import re, os from xml.dom.minidom import parse, parseString from ddlInterface import createDdlInterface, attribsToDict from NamingConvention import * __author__ = "Scott Kirkwood (scott_kirkwood at berlios.com)" __keywords__ = ['XML', 'DML', 'SQL', 'Databases', 'A...
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'v1)g@8)7t&vj#q24yx8d+m3&v&emz&6u9f9g9mol96j8i7q_z0' DEBUG = False ALLOWED_HOSTS = ['tpp.pt', 'www.tpp.pt'] INSTALLED_APPS = ( 'raven.contrib.django.raven_compat', 'django.contrib.admin', 'django.contrib.auth'...
from django.urls import re_path from .views import ( MeetingCancelView, MeetingCommentView, MeetingConfirmView, MeetingDetailView, MeetingUpdateView, ) urlpatterns = [ re_path(r"^(?P<pk>\d+)/$", MeetingDetailView.as_view(), name="meeting_detail"), re_path( r"^(?P<pk>\d+)/request/$"...
"""Exemplar solution to Ellen's Alien Game exercise.""" class Alien: """Create an Alien object with location x_coordinate and y_coordinate. Attributes ---------- (class)total_aliens_created: int x_coordinate: int - Position on the x-axis. y_coordinate: int - Position on the y-axis. health...
import numpy as np import random import matplotlib.pyplot as plt def random_obstacle(x, y, max_size): obstacle_size = random.randint(5,max_size) obstacle_occupancy = [(x,y)] for i in range(obstacle_size): x += random.choice([1, 0, -1]) y += random.choice([1, 0, -1]) obstacle_occupa...
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import fields, models class ResConfigSettings(models.Transien...
def partition(result, low, high): i = low - 1 pivot = result[high] for j in range(low, high): element = result[j] if element[1] > pivot[1]: i = i + 1 result[i], result[j] = result[j], result[i] result[i+1], result[high] = result[high], result[i+1] return...
from selenium.webdriver.common.by import By class MyPersonalInfoLocators: PERSONAL_INFO_BUTTON = (By.XPATH, '//*[@title="Manage my personal information"]') FIRSTNAME_BUTTON = (By.XPATH, '//*[@name="firstname"]') LASTNAME_BUTTON = (By.XPATH, '//*[@name="lastname"]')
""" 0520. Detect Capital Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only...
#!/usr/bin/python import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="", db="testdata") cur = db.cursor() #My table looks like this: #mysql> desc UserList; #+----------+------+------+-----+---------+-------+ #| Fi...
# Public Domain (-) 2010-2013 The Assetgen Authors. # See the Assetgen UNLICENSE file for details. __release__ = '0.3.7.2'
from django.shortcuts import render from squealy.views import SqlApiView # Create your views here. class DatabaseTableReport(SqlApiView): query = "select name, sql, 5 as num, 123 as some_column from sqlite_master limit 4;" format = "GoogleChartsFormatter" transformations = [ {"na...
""" This file computes the set of small common multiples of two colored trees. """ from basic import * from m_alpha_beta import MOperation, SeqMOperation, get_seq_of_m def overlapping_possible(small_tree, big_tree, small_tree_vertex, big_tree_vertex, log): if isinstance(small_tree_vertex, Leaf): ...
# coding: utf8 from math import cos, sin, pi from random import choice, gauss from time import time from kivy.lang import Builder from kivy.uix.widget import Widget from kivy.factory import Factory from kivy.clock import Clock, mainthread from kivy.animation import Animation from kivy.properties import ( ListPrope...
from __future__ import division, print_function import matplotlib.pyplot as plt import numpy as np from numpy.random import rand from time import time """ INPUT: quantized mains fdiff, all-hot, first bit is sign. OUTPUT: appliance fdiff Code taken from Lasagne and nolearn! """ SEQ_LENGTH = 400 N_HIDDEN = 5 N_SEQ_PER...
import re from bson import ObjectId from bson.dbref import DBRef from bson.errors import InvalidId from django.utils.encoding import smart_str from django.utils.datastructures import MultiValueDict from rest_framework import fields from rest_framework.exceptions import ValidationError class DateTime000Field(fields.Da...
######################################### # # # Implementation of Basic Blockchain # # # ######################################### import hashlib import json from time import time from uuid import uuid4 from urllib.par...
import numpy as np from pymoo.util.dominator import Dominator def fast_non_dominated_sort(F, **kwargs): M = Dominator.calc_domination_matrix(F) # calculate the dominance matrix n = M.shape[0] fronts = [] if n == 0: return fronts # final rank that will be returned n_ranked = 0 ...
from __future__ import division import torch import cv2 import numpy as np def path_to_input(image_path, input_size, device): img = cv2.imread(image_path) img = cv2.resize(img, (input_size, input_size)) #Resize img = img[..., ::-1].transpose((2, 0, 1)) ...
# Generated by Django 3.0.12 on 2021-05-17 22:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gbe', '0010_auto_20210429_1745'), ] operations = [ migrations.AlterUniqueTogether( name='volunteerinterest', unique_togethe...
from click import ClickException class staticgennanException(ClickException): """Base exceptions for all staticgennan Exceptions""" class ConfigurationError(staticgennanException): """Error in configuration"""
from rcon.player_history import should_ban def test_should_not_ban(): assert not should_ban({"SteamId": "...", "CommunityBanned": False, "VACBanned": False, "NumberOfVACBans": 0, "DaysSinceLastBan": 0, "NumberOfGameBans": 0, "EconomyBan": "none"}, float('inf'), 1) assert not should...
# coding: utf-8 """ grafeas.proto No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v1beta1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import...
import dsuserapi as ds import time import asyncio import os tok = "Put token here :)" dmid = 83982479282 #Fake ID, put the real one def getLatest(token, dmid): latest_message = ds.getMessages(token, dmid, 1) return latest_message[0] async def listen_messages(token, dmid): lid = getLatest(token, dmid) ...
# # Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE. # # Distributed under 3-Clause BSD license. See LICENSE file for more information. # """ 2d lumped bar element. """ __all__ = [ ...
# model_graph.py # ==元数据关系转换成Neo4j图数据库关系 from py2neo import Relationship, NodeMatcher, Subgraph from db.neo4j_conn import neo4j_graph as graph from config.config import cfg as config logger = config.logger def name_format(name): if name is not None: name = name.strip() name = name.replace(' ', '_...
import glob import os import re import subprocess OMFS = glob.glob('../film_random_A20pJm-2_mu0Ms648e-3/*.omf') for OMF in OMFS: OMFNAME = os.path.basename(OMF) SEED = re.search('(?<=rseed)\d+(?=-)', OMFNAME).group(0) SAVE_FOLDER = 'film_random_rseed{}_field-sweep_omfs_smallDT'.format(SEED) if SEED ...
from datetime import datetime from sqlalchemy import Column, DateTime, ForeignKey, Text, Integer from sqlalchemy.schema import Index, UniqueConstraint from freight.config import db LOG_CHUNK_SIZE = 4096 class LogChunk(db.Model): __tablename__ = "logchunk" __table_args__ = ( Index("idx_logchunk_task...
#!/usr/bin/env python import rospy from std_msgs.msg import String from gazebo_msgs.msg import ModelStates """ string[] name geometry_msgs/Pose[] pose ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestCheckJournalEntry(TransactionCase): """ Check journal entries when the expense product is having tax which is tax included. """ def setUp(self): ...
#!/usr/bin/env python #-*- coding:utf-8 _*- """ @author:liruihui @file: loss_utils.py @time: 2019/09/23 @contact: ruihuili.lee@gmail.com @github: https://liruihui.github.io/ @description: """ import numpy as np import torch import torch.nn.functional as F NUM = 1.2#2.0 W = 1.0#10.0 #计算loss def cal_loss_raw(p...
"""Create the web scraper.""" import nltk import requests from bs4 import BeautifulSoup from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from hrp.common.util import KEYWORDS, URL_LIST from hrp.researches.models import Research requests.packages.urllib3.disable_warnings( requests.packages....
# coding=utf-8 import logging import random import string import sys import unittest from time import time, sleep import apiritif def setup(): vars = { } apiritif.put_into_thread_store(vars) class TestAPI(unittest.TestCase, ): def setUp(self): (self.vars,) = apiritif.get_from_thread_sto...
# Выведите 2ᴺ. exp = int(input()) print(2 ** exp)
from datetime import datetime import deezer, time def get_artist(artist_id_or_name): client = deezer.Client() try: artist = client.get_artist(int(artist_id_or_name)) except: artist = client.search(artist_id_or_name, relation='artist')[0] artist.albums = get_albums(artist) return a...