content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import sys
import argparse
import logging
import textwrap
from pathlib import Path
import contextlib
from tqdm.auto import tqdm
import ase.io
import torch
from nequip.utils import Config
from nequip.data import AtomicData, Collater, dataset_from_config
from nequip.train import Trainer
from nequip.scripts.deploy impo... | python |
#!/usr/bin/python3
import datetime
import inquirer
import requests
import re
import csv
import os
import json
repositories = [
"beagle",
"beagle-web-react",
"beagle-web-core",
"beagle-web-angular",
"charlescd",
"charlescd-docs",
"horusec",
"horusec-engine-docs",
"ritchie-cli",
"... | python |
# Generated by Django 3.2.4 on 2021-06-18 13:58
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0008_historicalproduct'),
]
operations = [
migrations.AlterField(
model_name='coupon',
... | python |
import sys, os, copy, time, random
# global_list is all possible guesses
# answer_list is all possible solutions
mode = input("Are you playing Unlimited? ")
if mode[0].lower() == "y":
answer_file = "all_words.txt"
all_file = "all_words.txt"
else:
answer_file = "answers.txt"
all_file = "all_words.txt"
... | python |
from django.urls import path
from .views import TodoListView, TodoDetailView, TodoCreateView
app_name = 'todos'
urlpatterns = [
path('', TodoListView.as_view(), name='todo_list'),
path('<int:pk>/', TodoDetailView.as_view(), name='todo_detail'),
path('novo/', TodoCreateView.as_view(), name='todo_new'),
] | python |
# Copyright 2016 Google 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 by applicable law or a... | python |
"""
Copyright 2016 Udey Rishi
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, software
dist... | python |
# Create a mesh, compute the normals and set them active, and
# plot the active vectors.
#
import pyvista
mesh = pyvista.Cube()
mesh_w_normals = mesh.compute_normals()
mesh_w_normals.active_vectors_name = 'Normals'
arrows = mesh_w_normals.arrows
arrows.plot(show_scalar_bar=False)
| python |
from __future__ import absolute_import
# Add search patterns and config options for the things that are used in MultiQC_bcbio
def multiqc_bcbio_config():
from multiqc import config
""" Set up MultiQC config defaults for this package """
bcbio_search_patterns = {
'bcbio/metrics': {'fn': '*_bcbio.txt... | python |
# Copyright (C) 2020 NumS Development 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/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | python |
from os import path
from json_database import JsonConfigXDG, JsonStorageXDG
from ovos_utils.log import LOG
from ovos_utils.messagebus import Message
from ovos_utils.json_helper import merge_dict
from ovos_skills_manager import SkillEntry
from ovos_skills_manager.appstores import AbstractAppstore
from ovos_skills_man... | python |
from torch.utils.data import Dataset
import pandas as pd
from ast import literal_eval
from os import path
import numpy as np
from newsrec.config import model_name
import importlib
import torch
try:
config = getattr(importlib.import_module('newsrec.config'), f"{model_name}Config")
except AttributeError:
print(f... | python |
# -*- coding: utf-8 -*-
import json
import functools
from TM1py.Objects import Chore, ChoreTask
from TM1py.Services.ObjectService import ObjectService
def deactivate_activate(func):
""" Higher Order function to handle activation and deactivation of chores before updating them
:param func:
:return:... | python |
from django.core.management.base import BaseCommand, CommandError
from gwasdb.hdf5 import get_hit_count, load_permutation_thresholds
from gwasdb.models import Study
from aragwas import settings
import os
class Command(BaseCommand):
help = 'Fetch number of SNPs passing filtering, adapt bonferroni thresholds and ad... | python |
"""
Simple training loop; Boilerplate that could apply to any arbitrary neural network,
so nothing in this file really has anything to do with GPT specifically.
"""
import math
import logging
import os
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as optim
from torch.optim.lr_scheduler imp... | python |
# Copyright 2019 Nokia
#
# 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, softwa... | python |
import datetime
from time import timezone
from django.db import models
# Create your models here.
from issue.models import IssueModel
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(... | python |
# Copyright 2015 PerfKitBenchmarker 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 |
# -*- coding: utf-8 -*-
from selenium import webdriver
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_it_worked(self):
self.brow... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-05-24 03:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import mooringlicensing.components.proposals.models
class Migration(migrations.Migration):
dependencies = [
('moorin... | python |
from py_tests_common import *
def TypeofOperatorDeclaration_Test0():
c_program_text= """
type T= typeof(0);
"""
tests_lib.build_program( c_program_text )
def TypeofOperatorDeclaration_Test1():
c_program_text= """
type T= typeof( 55 * 88 );
"""
tests_lib.build_program( c_program_text )
def TypeofOperatorD... | python |
# -*- coding: utf-8 -*-
"""Get image links of the book's cover."""
import logging
from .dev import cache
from .dev.webquery import query as wquery
LOGGER = logging.getLogger(__name__)
UA = 'isbnlib (gzip)'
SERVICE_URL = ('https://www.googleapis.com/books/v1/volumes?q=isbn:{isbn}'
'&fields=items/volum... | python |
from pytz import timezone
from django.test import TestCase
from django.urls import reverse, resolve
from django.contrib.auth.models import User
from ..models import SSHProfile, Task, TaskResult
class TaskViewTestCase(TestCase):
'''
A base test case of Task view
'''
def setUp(self):
# Setup a t... | python |
from math import * # This import statement allows for all other functions like log(x), sin(x), etc.
import numpy as np
import math
import matplotlib.pyplot as plt
class Visualizer:
def __init__(self, f_x, f_y):
# List of all colors
self.color_list = ['#e22b2b', '#e88e10', '#eae600', '#88ea00',
... | python |
#!/usr/bin/env python
"""
CREATED AT: 2021/12/6
Des:
https://leetcode.com/problems/rotate-list/
https://leetcode.com/explore/learn/card/linked-list/213/conclusion/1295/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
Tag: ListNode
See:
"""
from typing import Optional
from src.list_node import Lis... | python |
from .backends import JWTAuthentication as auth
from rest_framework import generics, status
from rest_framework.generics import RetrieveUpdateAPIView, ListAPIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
fr... | python |
from cli_args_system.args import Args
from cli_args_system.flags_content import FlagsContent | python |
# Copyright 2016 Quora, 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, so... | python |
import unittest
from unittest import TestCase
from unittest.mock import patch, Mock
import mysql.connector
from matflow.database.DatabaseTable import DatabaseTable
from matflow.exceptionpackage import MatFlowException
# TODO too complicated for first use of unittests. Come back to this after writing tests for other ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .quicktime_hold import QuickTimeHold
from .quicktime_mash import QuickTimeMash
| python |
# -*- coding: utf-8 -*-
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from .fields import features_modal
from .fields import fields
from .info_modal import info_modal
from app.custom_widgets import custom_button
store = [
# JSON string of Parameter... | python |
# -*- coding: utf-8 -*-
from model.contact import Contact
import random
def test_delete_random(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname="Nikto"))
oldcontacts = db.get_contact_list()
contact = random.choice(oldcontacts)
app.contact.delete_by_... | python |
from playwright.sync_api import sync_playwright
import socket
#Stage 2
from ipwhois.net import Net
from ipwhois.asn import IPASN
from pprint import pprint
import ssl, socket
class Solution:
def __init__(self, url):
#1.a
self.user_given_url = url
self.is_https = None
sel... | python |
# Copyright 2019 Contributors to Hyperledger Sawtooth
#
# 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 ... | python |
class QuestionStructure(object):
'''The QuestionStructure Will be imported
from the Questions package and used to model the question Structure
'''
def __init__(self, q_text, answer, options):
self.q_text = q_text
self.answer = answer
self.options = options
def check_answer(... | python |
#!/usr/bin/env python
'''
octoDNS Versions
'''
from __future__ import absolute_import, division, print_function, \
unicode_literals
from octodns.cmds.args import ArgumentParser
from octodns.manager import Manager
def main():
parser = ArgumentParser(description=__doc__.split('\n')[1])
parser.add_argumen... | python |
import boto3
import os
import json
from datetime import datetime
import logging
import json
'''
AWS Lambda Function to get all data. Requests come from Amazon API Gateway.
'''
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def get_data(id):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.... | python |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apach... | python |
from django.shortcuts import render
from rbac.models import Menu
from system.models import SystemSetup
def customerView(request):
if request.method == 'GET':
ret = Menu.getMenuByRequestUrl(url=request.path_info)
ret.update(SystemSetup.getSystemSetupLastData())
return render(request, 'adm/... | python |
# import unittest
# import os
# from testfixtures import tempdir, compare, TempDirectory
# from tests.context import categorize
# Pair = categorize.ArchivePair
# import json
# class test_archive_pair(unittest.TestCase):
# """
# Ensure that when something needs to be stored it can be gotten and set
# """
... | python |
# coding: utf-8
from datetime import datetime, timedelta
from .._base import to_base64
from .base import TestCase
from .base import create_server, sqlalchemy_provider, cache_provider
from .base import db, Client, User, Grant
class TestDefaultProvider(TestCase):
def create_server(self):
create_server(self... | python |
from sqlalchemy import (
Boolean,
Column,
ForeignKey,
Integer,
Text,
Unicode,
UniqueConstraint,
)
from sqlalchemy.orm import relationship
from nbexchange.models import Base
from nbexchange.models.actions import Action
class Assignment(Base):
"""The Assigments known for each course
... | python |
# Copyright (c) 2022 Keith Carrara <legocommanderwill@gmail.com> & Edward Kopp <edward@edwardkopp.com>
# Licensed under the MIT License. the LICENSE file in repository root for information.
from abc import abstractmethod
from kivy import Config
from kivy.app import App
from kivy.core.window import Window
from... | python |
import os
import random
import math
import json
import numpy as np
import pandas as pd
from scipy import stats
from scipy import sparse
from scipy.stats import poisson
from scipy.optimize import nnls
from fdr import qvalues
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import Lasso
from sklearn.... | python |
# coding: utf8
import clinica.pipelines.engine as cpe
class T1VolumeParcellation(cpe.Pipeline):
"""T1VolumeParcellation - Computation of mean GM concentration for a set of regions.
Returns:
A clinica pipeline object containing the T1VolumeParcellation pipeline.
"""
def check_custom_dependen... | python |
import os
import unittest
from tempfile import TemporaryDirectory
import numpy as np
from l5kit.visualization import write_video
class TestVideoVisualizationHelpers(unittest.TestCase):
def test_write_video(self) -> None:
# Just a smoke test
images = (np.random.rand(5, 512, 512, 3) * 255).astype(... | python |
"""This module contains implementations of 'array list' data structure"""
from typing import TypeVar, Generic, List, Callable
Item = TypeVar('Item')
class ArrayList(Generic[Item]):
def __init__(self, size: int, realloc_coeff: int, potential_formula: Callable[[int, int], int]):
if size < 0:
r... | python |
"""
pip install selenium
"""
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.actio... | python |
import time
import numpy as np
class Learner(object):
'''
Define interface of methods that must be implemented by all inhereting classes.
'''
def __init__(self, discount_factor=1, learning_rate=1):
self._values = {}
self._prev_values = {}
self._discount_factor = discount_factor... | python |
MOD = 1_000_000_007
L = [0, 2, 8]
n = int(input())
for i in range(3, n+1):
L.append((L[-1]*3 + 2)%MOD)
print(L[n]%MOD)
| python |
### mb-soil-moisture.py v1.2
### Show soil moisture on micro:bit display using resistive and capacitive sensors
### Tested with BBC micro:bit v1.5 and MicroPython v1.9.2-34-gd64154c73
### on a Cytron Edu:bit
### MIT License
### Copyright (c) 2021 Kevin J. Walters
### Permission is hereby granted, free of charge, to... | python |
# -*- coding: utf-8 -*-
import json
def save_json(file_path, data):
"""
Load data to json file.
>>> save_json("./JsonAccessorDoctest.json", "{"Fuji": {"Id": 30, "server": ["JP", "CN"]}}") # doctest: +SKIP
"""
with open(file_path, 'w', encoding='utf8') as outfile:
json.dump(data, outfile, ... | python |
"""
This lambda compares new batches to previous batches to detect
which records are missing from the new one. These indicate that
a membership has lapsed.
"""
import datetime
import json
import os
import boto3
from actionnetwork_activist_sync.actionnetwork import ActionNetwork
from actionnetwork_activist_sync.loggi... | python |
"""
vp_overlap.py
Do calculations for overlap type functionals
"""
import numpy as np
from scipy.special import erf
def vp_overlap(self):
const = 2
#Calculate overlap
self.E.S = self.grid.integrate((np.sum(self.na_frac, axis=1) * np.sum(self.nb_frac, axis=1))**(0.5))
self.E.F = erf( const * self.E.S... | python |
from datetime import datetime
def voto(ano):
global idade
idade = datetime.now().year - ano
if idade < 16:
return 'NEGADO'
elif idade < 18:
return 'OPCIONAL'
else:
return 'OBRIGATORIO'
idade = 0
tip = voto(int(input('Em que ano vc nasceu?: ')))
print(f'com {idade} anos, O seu... | python |
# -*- coding: utf-8 -*-
import base64
import urlparse
import urllib
import hashlib
import re
from resources.lib.modules import client
from resources.lib.modules import directstream
from resources.lib.modules import trakt
from resources.lib.modules import pyaes
RES_4K = ['4k', 'hd4k', 'hd4k ', '4khd', '4khd ', 'uhd... | python |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from copy import deepcopy
import errno
import fnmatch
import logging
import os
import random
import shutil
import string
import subprocess
import yaml
import sys
from ansible_vault import Vault
def _is_py3():
return True if sys.version_info >= (3, 0) el... | python |
def a(z):
print(z + z)
a(0)
a('e')
a([0])
| python |
# Generated by Django 2.2.5 on 2019-10-26 18:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cat... | python |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
RESOLUTION = ["Performance Tuning of Cortex XSOAR Server: https://docs.paloaltonetworks.com/cortex/cortex-xsoar/6-0/"
"cortex-xsoar-admin/cortex-xsoar-overview/performance-tuning-of-cortex-xsoar-server"]
def ana... | python |
class DSN:
def __init__(self,
user,
password,
database="test", host="localhost", port: int = 3306, charset="utf8"):
self.user = user
self.password = password
self.host = host
self.port = port
self.database = database
... | python |
from vart.sampler.walkers import Walkers
class SamplerBase(object):
def __init__(self,nwalkers=1000, nstep=1000, nelec=1, ndim=3,
step_size = 3, domain = {'min':-2,'max':2},
move='all'):
self.nwalkers = nwalkers
self.nstep = nstep
self.step_size = step_s... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Johns Hopkins University (Jiatong Shi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import codecs
import sys
def get_parser():
parser = argparse.ArgumentParser(description="language identification scoring")
parser... | python |
# -*- coding: utf-8 -*-
import pytest
import csv
import sys
import os
from filecmp import cmp
from feature_extractor.feature_extractor import FeatureExtractor
__author__ = "Harvey Bastidas"
__copyright__ = "Harvey Bastidas"
__license__ = "mit"
class Conf:
""" This method initialize the configuration variables f... | python |
# coding:utf-8
from . import api
from ..models import User,Bucketlist
from flask import request, jsonify, abort, make_response
@api.route('/bucketlists/', methods=['POST', 'GET'])
def bucketlists():
# get the access token
access_token = request.headers.get('Authorization')
if access_token:
user_id... | python |
# Standard Library
import asyncio
import json
import logging
import os
import time
from datetime import datetime
# Third Party
import kubernetes.client
from elasticsearch import AsyncElasticsearch, exceptions
from elasticsearch.helpers import async_streaming_bulk
from kubernetes import client, config
from kubernetes.c... | python |
from django import template
from django.contrib.auth.models import User
from ..forms import UserCreateForm
register = template.Library()
@register.inclusion_tag('registration/_signup.html')
def signup_form():
return {'form': UserCreateForm(instance=User())}
| python |
coordinates_E0E1E1 = ((128, 86),
(129, 81), (129, 84), (129, 86), (130, 82), (130, 86), (130, 97), (130, 116), (130, 119), (131, 69), (131, 82), (131, 84), (131, 86), (131, 96), (131, 97), (131, 112), (131, 114), (131, 116), (131, 117), (131, 119), (132, 70), (132, 71), (132, 83), (132, 85), (132, 87), (132, 96), (13... | python |
# =============================================================================
#
# Jade Tree Personal Budgeting Application | jadetree.io
# Copyright (c) 2020 Asymworks, LLC. All Rights Reserved.
#
# =============================================================================
from flask.views import MethodView
from... | python |
from setuptools import setup
import codecs
from fns import __version__
with codecs.open('README.md', 'r', 'utf-8') as readme:
long_description = readme.read()
setup(
name='fns',
version=__version__,
description='Revise receipt client',
author='Sergey Popov',
author_email='poserg@gmail.com',
... | python |
from pyconvcli import PyConvCli
import os
def main():
cli = PyConvCli('pyconvcli_internal_cli',os.path.dirname(os.path.realpath(__file__)),'pyconvcli')
cli.run()
def visualize():
cli= PyConvCli('pyconvcli_internal_cli',os.path.dirname(os.path.realpath(__file__)),'pyconvcli')
args,parsers = cli.parse_a... | python |
class VectorUtils:
def __init__(self):
pass
@staticmethod
def norm_2(vec):
return vec[0]**2 + vec[1]**2 + vec[2]**2
@staticmethod
def norm(vec):
return VectorUtils.norm_2(vec)**(1./2)
| python |
import time # so we can use "sleep" to wait between actions
import RPi.GPIO as io # import the GPIO library we just installed but call it "io"
from ISStreamer.Streamer import Streamer # import the ISStreamer
## name the bucket and individual access_key
#streamer = Streamer(bucket_name="Locker Protector", bucket_key="l... | python |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.utils.translation import ugettext_lazy as _
title = _("Reporters and Groups")
tab_link = "/reporters"
| python |
# persistence.py
"""
Wrapper to edit the persistent settings
"""
import os
import sys
import pathlib
import argparse
import configparser
import thinkpad_tools_assets.classes
from thinkpad_tools_assets.cmd import commandline_parser
from thinkpad_tools_assets.utils import NotSudo
try:
if os.getuid() != 0:
... | python |
from .interval import Interval, str_to_iv
from dataclasses import dataclass
from itertools import product
from math import prod
@dataclass(frozen=True)
class Cuboid:
points: list[Interval]
value: any = None
def volume(self) -> int:
return prod((x.get_length() for x in self.points))
def di... | python |
import argparse
from .display import LINE_SIZE
class Args:
def __init__(self, * args, mutex: list = [], group: list = [], **kargs):
self.args = args
self.kargs = kargs
self.group = group
self.mutex = mutex
self.arguments = None
def build(self, parser=None):
i... | python |
from datetime import datetime as dt
import requests, re
import pandas as pd
import numpy as np
import json
import time
import os
import tushare as ts
import logging
from bs4 import BeautifulSoup
logger = logging.getLogger('main.fetch')
def fetch_index(index_name):
path = os.path.dirname(os.path.abspath(__file__))... | python |
import os.path
from nbt.nbt import NBTFile
from PIL import Image
from config import *
def main():
# Read map files to sort by scale
print("Reading map files...")
mapfiles = []
for i in range(0,5):
mapfiles.append([])
i = 0
while os.path.isfile(inputDir + "map_" + str(i) + ".dat"):
# read file
nbt = NBTFil... | python |
from queue import Queue
import threading
class Synchonizer:
def __init__(self):
return
| python |
nome = str(input('Digite o seu nome completo: ')).strip().title()
fatiar = nome.split()
fatiar2 = nome.split()
print(f'Primeiro nome: {fatiar[0]};')
print(f'Último nome: {fatiar2[-1]}.')
| python |
#!/usr/bin/env python3
import os
import numpy as np
from shutil import copyfile
import glob
import argparse
import h5py
import datetime
from dateutil.parser import isoparse
import time
import decimal
import shutil
from scipy.interpolate import interp2d
import pybind_isce3 as isce3
from shapely import wkt
from alos_t... | python |
from django.conf.urls import url
from django.urls import include, path
from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy
from envelope.views import ContactView
from . import views
from .forms import MyContactForm
urlpatterns = [
# path('change-password/', auth_views.Passwo... | python |
"""
Finds all possible combinations of integers below value to generate value
Author: Juan Rios
"""
import math
"""
Calculate the possible number of partitions
"""
def find_partitions_dict(limit_value):
p = {(1,1):0}
for i in range(2,limit_value+1):
tmp = 1
index = 1
while index<=(i-ind... | python |
""" This script generates google search queries and uses requests to go get
the HTML from the google search page. This was the most time-consuming
step in the process.
Certain lines are commented out as evidence of debugging and
to help me remember what I had already done.
Anyways, this script ma... | python |
from django import forms
from django.core.exceptions import ValidationError
import re
def validar_exclucion_numeros(value):
if value != 'None':
numeros = re.sub("[^0-9]", "", value)
if numeros:
raise ValidationError("No permite numeros")
else:
return value
retur... | python |
class Solution:
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def prep(nums, k):
dr = len(nums) - k # 要删除的数目
stay = [] # 保留的list
for num in ... | python |
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
import re
print("Searching... please wait")
emails=[]
url="http://www.bbe.caltech.edu/people-public/all/all"
data=urlopen(url)
parse=BeautifulSoup(data).findAll('a')
b=[parse[k]['href'][7:] for k in range(len(parse)) if "@" in parse[k]['hre... | python |
from __future__ import absolute_import
from .base import ViewTest, TemplateViewTest, RedirectViewTest
from .dates import (ArchiveIndexViewTests, YearArchiveViewTests,
MonthArchiveViewTests, WeekArchiveViewTests, DayArchiveViewTests,
DateDetailViewTests)
from .detail import DetailViewTest
from .edit import (Mod... | python |
#!/usr/bin/env python
"""
Insert blank notes at the top of every set of cards.
Useful for creating new cards in bulk with an editor.
This is undone by running the normalization code, `sort.py`.
"""
import glob
from collections import OrderedDict
from library import DynamicInlineTableDict
from library import NoteLi... | python |
from math import sqrt
class cone():
def __init__(self,radius,height):
self.radius = radius
self.height = height
def volume(self):
r = 3.14*self.radius**2*(self.height/3)
print("Volume of Cone a is : ",r)
def surfaceArea(self):
import math
c = 3.1... | python |
# Copyright 2018 by Paolo Inglese, National Phenome Centre, Imperial College
# London
# All rights reserved.
# This file is part of DESI-MSI recalibration, and is released under the
# "MIT License Agreement".
# Please see the LICENSE file that should have been included as part of this
# package.
import t... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
vi $HOME/.LoginAccount.txt
[mailClient]
host = smtp.qq.com
port = 25
user = ***
pass = ***
fr = xxxxxx@qq.com
to = xxxxxx@gmail.com
debuglevel = True
login = False
starttls = False
'''
__all__ = ['get_smtp_client', 'sendmail']
import os, sys
from ConfigParser import ... | python |
from django.urls import path
from . import views
urlpatterns = [
path("", views.profil, name="profil"),
path('sport_profil/', views.create_sport_profil, name="createSportProfil"),
]
| python |
from __future__ import division, absolute_import
__copyright__ = """
Copyright (C) 2013 Andreas Kloeckner
Copyright (C) 2018 Matt Wala
Copyright (C) 2018 Hao Gao
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the ... | python |
"""
Render shortest/fastest paths for intervals as HTML.
"""
from typing import Any, List, Optional, Tuple
import attr
import osmnx as ox
from jinja2 import Template
from .routing import RestrictedGraph
from .calculation import IntervalCalculation
@attr.define
class Page:
"""
A full HTML page of interval calc... | python |
# -*- coding: utf-8 -*-
from .Cardstack import *
from .Exception import *
from copy import deepcopy
playPreds = ("PLAY", "PLAY COIN", "THRONE", "THRONE GENERIC", "THRONE COIN", "KING")
# -- Standard Exceptions -- #
def persistent(exc):
newExc = deepcopy(exc)
newExc.persistent = True
return newExc
def... | python |
import unittest
import numpy as np
import mesostat.utils.iterators.sweep as sweep
class TestUtilIterSweep(unittest.TestCase):
pass
# TODO: Implement me
unittest.main()
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################
# Script that runs all regression tests.
#
#
# MWetter@lbl.gov 2011-02-23
#######################################################
#
from collections import defaultdict
from contextlib import ... | python |
#! /usr/bin/env python3
# coding: utf-8
from __future__ import annotations
import logging
from logging import StreamHandler
import os
log = logging.getLogger()
formatter = logging.Formatter("%(filename)s %(levelname)s - %(message)s")
handler = StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
l... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.