content
stringlengths
5
1.05M
import os import pickle from tqdm import tqdm from sentence_transformers import SentenceTransformer root_dir = os.getcwd() class SentenceEncoder(): def __init__(self,name): self.name = name def load_model(self): sbert_model = SentenceTransformer(self.name) return sbert_model ...
from .base_sprite import BaseSprite class SimpleSprite(BaseSprite): def __init__(self, coordinates, speed_x, speed_y, image, transparent_color=None): super().__init__(coordinates, speed_x, speed_y, image, transparent_color) self.surf.blit(image.convert_alpha(), (0, 0))
#Copyright (c) 2016, Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Karrenbauer Oliver, Marek Felix, Meissner Pascal, Stroh Daniel, Trautmann Jeremias #All rights reserved. # #Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met...
def leapYear(year): if 0 == year % 4 and not 0 == year % 100 or 0 == year % 400: return True return False
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: user.py @time: 2018-04-04 17:33 """ from __future__ import unicode_literals import json from datetime import datetime from flask import ( request, flash, render_template, url_for, redirect, abort, json...
import random import numpy as np import torch def set_seed(seed: int): """ Set random seed for python, numpy and pytorch RNGs """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def get_random_state(): return { 'python': random.getstate(...
import subprocess import pwd import grp import os from config import Config as Configuration class UserDeleteFailed(Exception): pass class UserAddFailed(Exception): pass class UserManagement(): @classmethod def starting_user_id(cls): return Configuration.starting_uid_number() @classmetho...
# Generated by Django 4.0 on 2021-12-14 02:23 from django.db import migrations, models import posts_apis.helpers.src.image_file class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Posts', fields=[ ...
def generate_tree(base, trunk, leaves): for i in range(int(base / 2 + 1)): print(" " * int(base / 2 - i) + leaves * (i * 2 + 1)) print(" " * int(base / 2 - 1) + trunk * 3) def main(): arr_input = input("Enter the base-width, trunk, and leaves (space-delimited): ").split() generate_tree(int(arr...
from bs4 import BeautifulSoup as BS import requests, json import pandas as pd from common import * #Parser using an User Agent def parser(url): agent = {"User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'} page=requests.get(url,head...
# Copyright 2018-2019 Faculty Science Limited # # 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...
import getopt import os import sys from BaseHTTPServer import HTTPServer from composite_handler import CompositeHttpRequestHandler def usage(): print "" print "Usage: " + sys.argv[0] + " [OPTIONS]" print " -h HOST" print " -p Port" print "" if __name__ == "__main__": host = "" port = ...
import pytest import responses import requests from piperci.artman import artman_client _post_artifact_data = { "artman_url": "http://artman_url", "uri": "https://someminio.example.com/art1", "sri": "sha256-sCDaaxdshXhK4sA/v4dMHiMWhtGyQwA1fP8PgrN0O5g=", "type": "artifact", "caller": "pytest", ...
#!/usr/bin/env python import sys import math import time import StringIO from PIL import Image import scipy.constants from mathics.world import World from mathics.viewport import Viewport from mathics.machines import Pendulum, Timer, Point, Vector def write_gif(gif, frames, duration, nq): for i in range(len(fra...
import os import time import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.keras.preprocessing import image from tensorflow.python.saved_model import tag_constants from tensorflow.python.compiler.tensorrt import trt_convert as trt from tensorflow.keras.applications.resnet_v2 i...
# Copyright (c) OpenMMLab. All rights reserved. custom_imports = dict(imports=['r'], allow_failed_imports=False)
from .models import UserAuth, ContactUsData from .jwt import TokenAuth Contact_Us = ContactUsData() Token_Auth = TokenAuth() User_Auth = UserAuth()
import torch import unittest from models import FactorVAE from torchsummary import summary class TestFAE(unittest.TestCase): def setUp(self) -> None: # self.model2 = VAE(3, 10) self.model = FactorVAE(3, 10) def test_summary(self): print(summary(self.model, (3, 64, 64), device='cpu'))...
import math from random import randint special_mode=False class VectorX(tuple): def __new__(cls,*n): if special_mode: return tuple.__new__(VectorX, n[0] if isinstance(n[0],tuple) else n) else: return tuple.__new__(VectorX,n) def __add__(self, other): return Vector...
from pylons import config import ckan.plugins as p from ckan.common import json from geomet import wkt import re import logging import dateutil from datetime import date log = logging.getLogger(__name__) def extras_to_dict(pkg): extras_dict = {} if pkg and 'extras' in pkg: for extra in pkg['extras']: ...
""" Test beamshapes predictions given model data. Author: Thejasvi Beleyur, Acoustic and Functional Ecology, Max Planck Institute for Ornithology, Seewiesen License : This code is released under an MIT License. Copyright 2020, Thejasvi Beleyur Permission is hereby granted, free of charge, to any person obta...
# Import base tools import os ## Note, for mac osx compatability import something from shapely.geometry before importing fiona or geopandas ## https://github.com/Toblerity/Shapely/issues/553 * Import shapely before rasterio or fioana from shapely import geometry import rasterio import random from cw_tiler import main ...
#! -*- Encoding: Latin-1 -*- import threading CURRENT_VERSION = 1.0 Database = None
# Generated by Django 3.0.2 on 2020-02-29 15:07 from django.db import migrations import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20200201_1227'), ] operations = [ migrations.AlterField( model_name='role', ...
#!/usr/bin/python # -*- coding: utf-8 -*- import autonetkit.log as log import autonetkit.ank as ank_utils import itertools from autonetkit.ank_utils import call_log @call_log def mpls_te(anm): g_in = anm['input'] g_phy = anm['phy'] g_l3_conn = anm['l3_conn'] # add regardless, so allows quick check of...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from .core import UnitedStates class Arizona(UnitedStates): """Arizona""" martin_luther_king_label = "Dr. Martin Luther King Jr./Civil Rights Day" presidents_day_label = "L...
""" Written by Kushal, modified by Robik """ import sys import json import h5py import numpy as np DATA_PATH = '/hdd/robik/CLEVR' GENSEN_PATH = '/hdd/robik/projects/gensen' sys.path.append(f'{GENSEN_PATH}') from gensen import GenSen, GenSenSingle gensen_1 = GenSenSingle( model_folder=f'{GENSEN_PATH}/data/models...
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
"""Admin handler library."""
# Copyright 2012 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,...
from collections import defaultdict, namedtuple from enum import Enum from functools import total_ordering from itertools import product import random @total_ordering class Action(Enum): UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 def __lt__(self, other): if self.__class__ is other.__class__: ...
from django.urls import path, include from . import views app_name = 'wallet' urlpatterns = [ path('', views.wallet_home, name='wallet_home'), path('wallet_home', views.wallet_home, name='wallet_home'), # path('transfer_money', views.transfer_money, name='transfer_money'), path('transfer', views.trans...
""" JobsLib exceptions. """ __all__ = ['JobsLibError', 'TaskError', 'Terminate'] class JobsLibError(Exception): """ Base error, ancestor for all other JobsLib errors. """ pass class TaskError(JobsLibError): """ Task error. """ pass class Terminate(BaseException): """ Ind...
import random import numpy as np from enum import IntEnum class Directions(IntEnum): NW = 0 N = 1 NE = 2 W = 3 X = 4 E = 5 SW = 6 S = 7 SE = 8 class ADirections(IntEnum): E = 0 N = 1 W = 2 S = 3 X = 4 class Agent(): def __init__(self, controller): self.controller = controller self.viewsize = contr...
import datetime from keras import models import pandas as pd from sklearn.externals import joblib #loads .tsv file and pickles it in data folder, returns panda dataframes def load_tsv(filename:str): #make sure in data folder if 'tsv' not in filename: filename = filename + '.tsv' if 'data' not in fi...
from typing import Dict, Tuple, Union from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from cart.models import CartItem from cart.serializers im...
from functools import reduce from abc import ABC, abstractmethod from dataclasses import dataclass import numpy as np import pandas as pd import os class Data(ABC): @abstractmethod def classification(self): """Classification function""" @abstractmethod def classification_age_generation(self)...
from unittest import TestCase from contoso.app import App class AppTests(TestCase): def test_create_instance(self): app = App() self.assertEqual("bar", app.foo)
from __future__ import absolute_import from functools import wraps from django_ratelimit import ALL, UNSAFE from django_ratelimit.core import is_ratelimited from django_ratelimit.exceptions import Ratelimited from django_ratelimit.record_handlers.proxy import RateLimitRecordProxy __all__ = ["ratelimit"] def rateli...
import torch import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F class Classifier(nn.Module): def __init__(self, text_embedding_dim, hidden_dim, num_speakers): super(Classifier, self).__init__() self.hidden = nn.Linear(text_embedding_dim, hidden_dim) self.o...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=wrong-import-position, too-many-instance-attributes, too-many-locals """ Plot marginal distributions saved to JSON files by `summarize_clsim_table.py` for one or more tables. """ from __future__ import absolute_import, division, print_function __all__ =...
"""Plylist exceptions.""" class UnknownFormatException(Exception): """Raised if playlist format cannot be determined.""" pass class UnsupportedFormatException(Exception): """Raised if playlist format is not supported.""" pass class PlaylistReadError(Exception): """Raised if playlist file can...
import Adafruit_DHT import RPi.GPIO as gpio from modules.UUGear import * input_value_type = sys.argv[1] input_gpio_id = sys.argv[2] def get_dht11_value(value_type, value_id): humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, value_id) if humidity is not None and temperature is not None: ...
from google.appengine.ext import ndb class User(ndb.Model): """ User model for the FILL app. """ # User Properties name = ndb.StringProperty(required = True) username = ndb.StringProperty(required = True) email = ndb.StringProperty(required = True) password_hash = ndb.StringProperty(re...
from neo4j import GraphDatabase import json uri = "bolt://graph_db:7687" driver = GraphDatabase.driver(uri, encrypted=False) def get_gdb(): return driver def save_feedback(feedback): with driver.session() as session: with session.begin_transaction() as tx: tx.run(""" CREA...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Module documentation goes here.""" from __future__ import print_function __author__ = "First Last" __copyright__ = "Copyright 2018, First Last" __credits__ = ["C D", "A B"] __license__ = "Apache 2.0" __version__ = "1.0.1" __maintainer__ = "First Last" __email__ = "te...
from .constraint import Constraint import sys class Halfspace(Constraint): """Halfspace A halfspace is a set of the form H = {c'x <= b}, where c is a given vector and b is a constant scalar. """ def __init__(self, normal_vector, offset): """Construct a new halfspace H = {c'x <= b} ...
from mock import patch from randstr import randstr def test_default_randstr(): with patch('randstr.random') as random: random.choice.side_effect = 'helloworld' assert randstr() == 'hellowo' def test_length(): with patch('randstr.random') as random: result = 'helloworld' rando...
# Generated by Django 3.2.9 on 2021-11-15 14:41 import django.core.validators from django.db import migrations, models import django.db.models.deletion import rentcars.utils.paths import rentcars.validators class Migration(migrations.Migration): initial = True dependencies = [ ('tgbot', '0002_delet...
import sqlite3 import pandas as pd def connect_to_db(db_name='buddymove_holidayiq.sqlite3'): return sqlite3.connect(db_name) def execute_query(cursor, query): cursor.execute(query) return cursor.fetchall() df = pd.read_csv('buddymove_holidayiq.csv') GET_ALL= """ SELECT * FR...
#!/usr/bin/python # (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # most of it copied from AWX's scan_packages module from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' module: package_fac...
from utils import load_json_from_file from path import ( FIELDS_OF_STUDY_PATH, US_STATE_CODE_MAP, CANADA_STATE_CODE_MAP, SPAIN_STATE_CODE_MAP, ) USERS_TO_GENERATE = 120 # Percentage of users to be enrolled in at least one course. # Users will be divided evenly among the fake programs. PCT_USERS_ENROLLE...
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) async_parallel_load = 17 clock_in = 27 data_in = 22 clock_enable_pin = 23 def setup(): GPIO.setmode(GPIO.BOARD) GPIO.setup(async_parallel_load, GPIO.OUT) GPIO.setup(clock_enable_pin, GPIO.OUT) GPIO.setup(clock_in, GPIO.OUT) GPIO.setup(data_in, GPI...
import glob import os import sys import pandas as pd from murasame.divider import Divider from murasame.formatter import Formatter from murasame.maker import Maker from murasame.utils import load_setting tmpdir = load_setting()['system']['tmpdir'] resdir = load_setting()['system']['resdir'] def formatter(): se...
v = input('digite algo: ') print('o tipo primitivo desse valor é: ',type(v)) print('Só tem espaços? ',v.isspace()) print('É um número? ',v.isnumeric()) print('É alfabético? ',v.isalpha()) print('é alfanumérico? ',v.isalnum()) print('está em maiúsculas? ',v.isupper()) print('está em menúsculas? ',v.islower())
""" Django settings for gdshowreelvote project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ impor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Nov, 2019 @author: Nathan de Lara <ndelara@enst.fr> """ from abc import ABC import numpy as np from sknetwork.hierarchy.postprocess import split_dendrogram from sknetwork.utils.base import Algorithm class BaseHierarchy(Algorithm, ABC): """Base class ...
# Generated by Django 2.2.6 on 2019-10-27 07:10 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ontask', '0058_auto_20191027_1252'), ] operations = [ migrations.AlterField( model_name='schedu...
import click import binascii import os import yaml from ckan_cloud_operator import logs from . import driver @click.group() def postgres(): """Manage PostgreSQL databases unrelated to the operator or cluster""" pass @postgres.command() @click.option('--db-name') @click.option('--db-password') @click.optio...
from datetime import date, datetime import pandas as pd import pytest from pytz import timezone from liualgotrader.common import config from liualgotrader.common.data_loader import DataLoader # type: ignore from liualgotrader.common.types import DataConnectorType, TimeScale nyc = timezone("America/New_York") @pyt...
from PyQt5 import QtCore, QtGui import cv2 import urllib import numpy as np from ca import caget, caput import pv class CameraViewer(QtGui.QWindow): def __init__(self): super(CameraViewer, self).__init__() self.imageLabel = QtGui.QImage() self.imageLabel.setBackgroundRole(QtGui.QPalett...
""" Test script for BIDeN. This script will run all test cases ( 2^N -1, N = max number of component). We test the detailed case results of Task I using this script. """ import os from options.test_options import TestOptions from data import create_dataset from models import create_model from util import html import ut...
from unittest import TestCase import geopandas as gpd from xmlunittest import XmlTestMixin import logging from src.eq_fault_geom.geomio.cfm_faults import CfmMultiFault from src.eq_fault_geom.geomio.cfm_faults import CfmFault from src.eq_fault_geom.geomio.cfm_faults import required_fields from src.eq_fault_geom.geomio...
from django import forms from apps.usuario.models import Perfil from django.contrib.auth import authenticate from django.contrib.auth.forms import PasswordResetForm from apps.usuario.templatetags.utils import ROLES """ Funcion """ def must_be_gt(value_password): if len(value_password) < 7: raise forms.Vali...
""" Module for a R2T pulse shape: W.T. Franks FMP Berlin """ import de.bruker.nmr.mfw.root as root #import os import sys from sys import argv import TopCmds import math def dialog(): MAS=float(TopCmds.GETPAR("CNST 31")) TauR= float(1000000/MAS) input = TopCmds.INPUT_DIALOG("R2T input", "", \ ["Nominal RF ...
from hackerrank.ConsoleReader import * from hackerrank.SortingList import * from hackerrank.LambdaCollection import * from hackerrank.NumpyCollection import * # Enter your code here. Read input from STDIN. Print output to STDOUT print(createnumpyarray([1, 2, 3, 4]).T.flatten())
# -*- coding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp from datetime import datetime from openerp import SUPERUSER_ID, api from openerp.exceptions import except_orm, Warning, RedirectWarning class account_invoice(osv.osv): _in...
""" Unit tests for `execute_task`, `handle_failure`, and `run_shell` from `ScriptRunner.pipeline`. """ from unittest.mock import MagicMock import pytest from exceptions import StopKeywordFailures, UnknownKeywordFailures from pipeline import ( SKIP, STOP, UNKNOWN_KEYWORD_MESSAGE, execute_task, handl...
import string import base64 class VegaRenderer: script_code = string.Template(''' (function(spec) { var view = new vega.View(vega.parse(spec), { renderer: '${renderer}', container: '#${div_id}', hover: true }); view.runAsync().then(function() { parent.document.getElementById('${iframe_id}').onload...
import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from tensorflow.keras.layers import Input, Lambda, Embedding, Dense, Concatenate, Dropout from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras.ca...
#Snake Tutorial Python import dwave from pyqubo import Binary, solve_qubo from dwave.system import DWaveSampler, EmbeddingComposite from dimod import ExactSolver from pyqubo import Binary import networkx as nx #import dwave_networkx as dnx import math import random import pygame import tkinter as tk import dimod from t...
import unittest from escherauth.escherauth import EscherRequest class EscherRequestTest(unittest.TestCase): def test_object_basic(self): request = EscherRequest({ 'method': 'GET', 'host': 'host.foo.com', 'uri': '/?foo=bar', 'headers': [ ('Da...
from os.path import dirname, abspath, join PROJECT_PATH = join(dirname(abspath(__file__)), '..') RESOURCE_PATH = join(PROJECT_PATH, 'sinling', 'resources')
# Copyright (c) 2020 fortiss GmbH # # Authors: Patrick Hart, Julian Bernhard, Klemens Esterle, and # Tobias Kessler # # This software is released under the MIT License. # https://opensource.org/licenses/MIT import unittest import numpy as np import time from bark.runtime.commons.parameters import ParameterServer fro...
def inputli(): return list(map(int,input().split())) def inputls(): return input().split() def inputlf(): return list(map(float,input().split())) def lcs(a,b): dp = [[0]*(len(b)+1) for i in range(len(a)+1)] maxi = 0 for i in range(1,len(a)+1): for j in range(1,len(b)+1): if...
from sklearn.compose import make_column_transformer from sklearn.preprocessing import OneHotEncoder from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression def get_estimator(): categorical_cols = ['Sex', 'Pclass', 'Embarked'] numerica...
import time, random, sys import urllib, urllib2 import mechanize from bs4 import BeautifulSoup """TODO: do method for getting neopoints do auto food club betting/collecting refactor/clean up code """ b = mechanize.Browser() def init(): b.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebK...
""" This file contains a class that represents a game item. Author: Alejandro Mujica (aledrums@gmail.com) Date: 07/22/20 """ from src.game_object import GameObject class GameItem(GameObject): def __init__(self, collidable, consumable, on_collide=None, on_consume=None, *args, **k...
#----------------------------------------------------------------------------- # # Paper: When Crowdsourcing Fails: A Study of Expertise on Crowdsourced # Design Evaluation # Author: Alex Burnap - aburnap@umich.edu # Date: October 10, 2014 # License: Apache v2 # Descrip...
#Assignment 14 # #Total Sales # #Design a program that asks the user to enter a store's sales for each #day of the week and display the result. #use lists for storing
''' Function: 快递查询系统 Author: Car 微信公众号: Car的皮皮 ''' import os import time import pickle import random import requests from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5 import QtWidgets, QtGui '''快递查询系统''' class InquiryExpress(QWidget): tool_name = '快递查询系统' def __init__(self, par...
import unittest import numpy as np from plate_analysis import is_connected from plate_analysis import connectivity_hinges from plate_analysis import dijkstra from plate_analysis import connectivity_penalization class TestConnectivityChecker(unittest.TestCase): t2 = np.array([[0, 0, 0, 1, 1, 0], ...
from .l import l def func(name, body, kernel=None): f = l(body, kernel=kernel) kernel.define(name, f) return f
import time import random import discord from discord.ext import commands import subsys.R5MemCalls as mem import subsys.R5SoundCalls as snd from utility.R5config import DIS_KEY print("Vwooooo!") R5 = commands.Bot(command_prefix='R5:') #player resources rules = "Edge of the Empire sourcebook: https://drive.google....
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) """LinkTree class for setting up trees of symbolic links.""" from __future__ import print_function import filecmp import...
compass_dirs = { "N": 0.0, "NNE": 22.5, "NE": 45.0, "ENE": 67.5, "E": 90.0, "ESE": 112.5, "SE": 135.0, "SSE": 157.5, "S": 180.0, "SSW": 202.5, "SW": 225.0, "WSW": 247.5, "W": 270.0, "WNW": 292.5, "NW"...
import sys sys.path.append('/usr/users/oliverren/meng/check-worthy') from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Embedding, LSTM, Bidirectional, Dropout, Dense, Input, Merge from keras.layers import Conv1D, GlobalAveragePooling1D, MaxPo...
#!/usr/bin/env python3 import argparse import functools import logging import os import re import socket import sys import threading import time from http.server import BaseHTTPRequestHandler, HTTPServer # Domains that are not indended to be blocked # and which will be filtered out from block lists. # Some of these ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt works = pd.read_csv("./works.csv") m = works[works['gender'] == 'Мужской']['salary'] fm = works[works['gender'] == 'Женский']['salary'] pr = [i / 10 for i in range(1, 11)] ax = plt.subplots()[1] print("Мужчины:\n") ax.plot(m.quantile(pr)) plt.sho...
''' Testing the get_style_sheets function. ''' import os from qtstyles import get_style_sheets, Sheet class TestGetStyleSheets(object): ''' The get_style_sheets() function gets a list of styles and their associated sheet objects. ''' def setup_method(self, method): ''' Run the get...
def calculate_1D_consolidation(y_coord, H, T_v): """ Calculates the analytical solution for 1d consolidation on linear elastic soil [@@ref@@] :param y_coord: vertical coordinate :param H: sample height :param T_v: dimensionless time factor :return: relative excess pore pressure """ fro...
import subprocess import sys def npm(*npm_args): call_args = [__get_executable_name()] + list(npm_args) subprocess.check_call(call_args) def __get_executable_name(): executable = 'npm' if sys.platform == 'win32': executable += '.cmd' return executable if __name__ == '__main__': npm...
# ============================================================================= # SaltStack utils File # # NAME: _utils/convert_to_epoch_time.py # WRITTEN BY: Alek Tant of SmartAlek Solutions # DATE : 2016.07.11 # # PURPOSE: Convert Salt Event Times into Epoch Times # from __future__ import absolute_import from cale...
# # @lc app=leetcode id=83 lang=python3 # # [83] Remove Duplicates from Sorted List # # https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ # # algorithms # Easy (41.95%) # Likes: 774 # Dislikes: 82 # Total Accepted: 333.1K # Total Submissions: 779.9K # Testcase Example: '[...
import csv import os all_dialogs = os.getcwd() + '/dialogs' os.chdir(all_dialogs) list_dialogs = os.listdir(all_dialogs) for i_dialogs in list_dialogs: ith_dialogs = os.getcwd() + "/" + i_dialogs os.chdir(ith_dialogs) ith_list = os.listdir(ith_dialogs) print("Dialogs Folder {} # of tsv files: {}".form...
#!/usr/bin/env python3 from fpylll import BKZ, IntegerMatrix inv_mod = lambda a, m : pow(a, m-2, m) class Curve(): def __init__(self, p, a, b, q, x0, y0): self.p = p self.a = a self.b = b self.b2 = 2*b % self.p self.b4 = 2*self.b2 % self.p self.q = q self.b...
import os import sys import tempfile import unittest from cssdeadwood.dom_match import match_selectors_against_html_string class CssMatchTest(unittest.TestCase): def testSimple(self): html = '<html><head></head><body><p>hello world</p></body></html>' selectors = set(['p']) result = m...
class Solution(object): def XXX(self, nums): self.ret = [] def dfs(path): if len(path) == len(nums): temp = [] for i,n in enumerate(path): if n==1: temp.append(nums[i]) pass s...
# coding=utf-8 from pyecharts.chart import Chart from pyecharts.option import get_all_options from pyecharts.constants import (CITY_GEO_COORDS, SYMBOL) class GeoLines(Chart): """ <<< 地理坐标系线图 >>> 用于带有起点和终点信息的线数据的绘制,主要用于地图上的航线,路线的可视化。 """ def __init__(self, title="", subtitle="", **kwargs): ...
import requests import json import os user = "root" pwd = os.environ['GITLAB_ROOT_PASSWORD'] gitlab_external_url = "http://localhost:"+os.environ['GITLAB_PORT'] login_url=gitlab_external_url+"/oauth/token" loginRequest = { "grant_type" : "password", "username": user, "password" : pwd, } raw_response = ...