content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by Kelly Hwong on 2018年09月18日16:16:19
# Part A: House Hunting
import math
annual_salary = int(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the cost o... |
'''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Para n > m > 0:
a = n^2 - m^2
b = 2nm
c = n^2 + m^2
a, b, c son terna
'''
... |
from logging import Handler
from queue import Queue
from threading import Thread
import logging.config
import logging
import asyncio
import datetime
import yaml
import sys
import os
from git import Repo
from functools import partial, wraps
from pythonjsonlogger import jsonlogger
RED = '\033[91m'
BLUE = '\033[94m'
BO... |
"""
Tools to put CP2K orbitals on a real space grid
"""
import os
import numpy as np
import scipy
import scipy.io
import scipy.interpolate
import scipy.ndimage
import time
import copy
import sys
import re
import io
import ase
import ase.io
from .cube import Cube
from .cp2k_wfn_file import Cp2kWfnFile
from mpi4py... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from google.appengine.ext import deferred
from dashboard import update_test_suites
from dashboard.common import datastore_hooks
from dashboa... |
from api.models import Api, Profile, ConnectLog
from api.serializers import ApiSerializer, ProfileSerializer, \
UserSerializer, ConnectLogSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework impor... |
from flask import Blueprint
from flask_restful import Resource
from atp.utils.common import get_request_json, make_response, username_to_nickname
from atp.api.mysql_manager import UITestCaseInfoManage, UICasePageInfoManager, UICasePageInfo, BaseSystemInfoManager
from atp.engine.exceptions import LoadCaseError
from atp... |
"""
Copyright 2019 Paul T. Grogan, Stevens Institute of Technology
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 ... |
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import EmailUser
class EmailUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = EmailUser
fields = ('email', 'name')
class EmailUserChangeForm(UserChangeForm):
class Meta:
model... |
# File: S (Python 2.4)
from direct.fsm.StatePush import AttrSetter, FunctionCall, StateVar
from pirates.pvp import PVPGlobals
class ShipRepairSpotMgrBase:
def __init__(self):
self._state = DestructiveScratchPad(health = StateVar(0), speed = StateVar(0), armor = StateVar(0), modelClass = StateVar(0), ... |
# -*- test-case-name: twisted.application.runner.test.test_pidfile -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
PID file.
"""
import errno
from os import getpid, kill, name as SYSTEM_NAME
from types import TracebackType
from typing import Optional, Type
from zope.interface import I... |
from manimlib.imports import *
class Dragon(MovingCameraScene):
CONFIG = {
"iterations":5,
"colors":[DARK_RED, YELLOW],
}
def construct(self):
path = VGroup()
line = Line(ORIGIN,UP / 10).set_color(DARK_RED)
path.add(line)
self.camera_frame.set_height(line.ge... |
# -*- coding: utf-8 -*-
"""Console script for alphashape."""
import os
import sys
import click
import click_log
import logging
import shapely
import geopandas
import alphashape
# Setup Logging
LOGGER = logging.getLogger(__name__)
click_log.basic_config(LOGGER)
@click.command()
@click.argument('source', type=click.... |
x = int(input())
count = [0,0,1,1]
for i in range(4,x+1):
count.append(count[i-1]+1)
if i%2==0: count[i] = min(count[i],count[i//2]+1)
if i%3==0: count[i] = min(count[i],count[i//3]+1)
print(count[x]) |
# coding=utf-8
"""
The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
d2d3d4=406 is d... |
# Generated by Django 2.2 on 2019-04-26 01:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Acao',
fields=[
... |
grafo = {}
grafo[1] = [7, 6]
grafo[2] = [3, 7]
grafo[3] = [2, 4, 6, 7]
grafo[4] = [3, 7]
grafo[5] = [7]
grafo[6] = [1, 3]
grafo[7] = [1, 2, 3, 4, 5]
c = 0
aux = grafo.copy()
tam = sorted(grafo.values(),key = len)[0]
lista = []
while c < len(grafo):
for i in tam:
for e in grafo:
if i in grafo[e... |
def method(method_class):
"""Decorator to use to mark an API method.
When invoking L{Registry.scan} the classes marked with this decorator
will be added to the registry.
@param method_class: The L{Method} class to register.
"""
def callback(scanner, name, method_class):
if method_clas... |
"""
Modeling Relational Data with Graph Convolutional Networks
Paper: https://arxiv.org/abs/1703.06103
Code: https://github.com/tkipf/relational-gcn
Difference compared to tkipf/relation-gcn
* l2norm applied to all weights
* remove nodes that won't be touched
"""
import argparse
import numpy as np
import time
import ... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Suite.cc_version'
db.add_column('library_suite', 'cc_version', self.gf('django.db.models.f... |
import snap
import os
filename = "facebook_combined.txt"
G = snap.LoadEdgeList(snap.PUNGraph,filename,0,1) #3rd and 4th parameters are column indices of source and destination nodes
#G is now the required undirected graph
n = G.GetNodes()
cls = snap.TIntFltH() # closeness centrality dict containing (node id, close... |
import os
from distutils.core import setup
from pathlib import Path
def read_requirements():
"Read requirements file and returns those lines corresponding to library dependencies"
pwd = Path(os.path.dirname(os.path.abspath(__file__)))
lines = []
with open(pwd / 'requirements.txt', 'rt') as fh:
... |
"""Provides formatted logging handler for distributey."""
import logging
import sys
from flask import has_request_context, session
import config
from splunk_handler import SplunkHandler
log_level = config.get_config_by_keypath('LOG_LEVEL')
splunk_enabled = config.get_config_by_keypath('SPLUNK_ENABLED')
if log_level... |
import logging
import smtplib
from email.message import EmailMessage
class EmailConfig():
def __init__(self, account, passwd, server_addr, server_port):
self.account = account
self.passwd = passwd
self.server_addr = server_addr
self.server_port = server_port
def send_code(config, e... |
from http import HTTPStatus
from flask_restplus import Resource, abort
from app.api.models import AttachmentModel
from app.api.namespaces import attachments
from app.authorization.permissions import EditThesisPermission, UserNeedPermission
from database import db
from database.models import Attachment
@attachments.... |
import json
import logging
import os
import torch
import requests
from typing import Dict, Optional
from torch import nn
from torch import Tensor
logger = logging.getLogger(__name__)
from huggingface_hub.constants import CONFIG_NAME, PYTORCH_WEIGHTS_NAME
from huggingface_hub.file_download import (
cached_download... |
"""Resource for SecurityGroups"""
import ipaddress
from typing import Type
from botocore.client import BaseClient
from altimeter.aws.resource.resource_spec import ListFromAWSResult
from altimeter.aws.resource.ec2 import EC2ResourceSpec
from altimeter.core.graph.field.dict_field import EmbeddedDictField
from altimeter... |
from cmndr import Middleware
import logging
class LoggingMiddleware(Middleware):
def execute(self, command, next_callable):
cmd_dict = command.__dict__
splitted_module = command.__module__.split('.')
domain = splitted_module[1]
log_string = '{} {}'.format(' '.join(splitted_module... |
from sfc_models import register_standard_logs
from sfc_models.objects import *
from sfc_models.sector import Sector
from sfc_gui.chart_plotter import ChartPlotterWindow2
from sfc_models.sector import Sector
from sfc_models.utils import Logger
class BusinessWithInvestment(FixedMarginBusiness):
def __init__(self,... |
#!/usr/bin/env python3
""" Generate performance graphs. """
import collections
import contextlib
import errno
import os
import platform
import subprocess
import sys
import tempfile
import timeit
FILE_SIZES_MB = tuple(2 ** x for x in range(12))
def generate_file(parent_dir, size_mb):
""" Generate a file, write r... |
#!/usr/bin/env python3
from collections import OrderedDict
ud = dict([('a', 1), ('b', 1), ('c', 1)])
print(ud)
od = OrderedDict([('a', 1), ('b', 1), ('c', 1)])
print(od) |
from os import path, mkdir
from data import DATA_PATH
# DATA_PATH = "."
class SolverBase(object):
def __init__(self, name):
self.name = name
class_name = self.__class__.__name__
ind = class_name.find("Solver")
self.data_dir = path.join(DATA_PATH, class_name[:ind].lower())
... |
import importlib
from logging import getLogger
from imblearn.ensemble import BalancedBaggingClassifier, RUSBoostClassifier
from imblearn.over_sampling import RandomOverSampler, SMOTE
from imblearn.pipeline import Pipeline
from imblearn.under_sampling import RandomUnderSampler
from keras.callbacks import EarlyStopping... |
import cv2
import glob
'''Cut images into 256*256 将目标图片裁剪为256*256 像素'''
i = 0
def crop(img, outdir):
img = cv2.imread(img) # 读入图片
#Row1
cropped = img[0:256, 0:256] # 裁剪坐标为[y0:y1, x0:x1]
cv2.imwrite("../corpped_PNG/{}.png".format(i+11000), cropped) # 裁剪并存储在指定文件夹中
# 图片名110xx,第xx张照片的第1行... |
#!/usr/bin/env python
# Copyright 2001 by Brad Chapman. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Test for graphics things that don't really deserve there own test modul... |
import scrapy
class PokemonSpider(scrapy.Spider):
name = "poke_spider"
start_urls = ['https://serebii.net/pokedex-sm/001.shtml']
def parse(self, response):
once_standard = True
once_alola = True
once_pre = True
file = open("pre_moves.json", "a+", encoding="utf-8")
... |
#!/usr/bin/env python
"""
Run this from the project root directory to perform tests.
There should be some music files in the music directory (source_dir) before
testing.
TODO: Everything.
"""
import os
import unittest
import shutil
import sys
import numpy as np
# I literally cannot believe this is how Python hand... |
# Time complexity: O(n^2) where n is length of string
# Approach: Recursion with memoizing boolean values.
class Solution:
def __init__(self):
self.mp = {}
def isScramble(self, s1: str, s2: str) -> bool:
if len(s1)!=len(s2):
return False
n = len(s1)
if not n or ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Correlation(nn.Module):
def __init__(self, max_displacement=4, *args, **kwargs):
super(Correlation, self).__init__()
self.max_displacement = max_displacement
self.output_dim = 2 * self.max_displacement + 1
sel... |
from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir
def generate_launch_description():
return LaunchDescription([
Node(
package=... |
# Generated by Django 3.0.8 on 2020-09-06 10:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0014_auto_20200906_0956'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='image... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
class Thresholds():
def __init__(self,img):
self._img = img
def _abs_sobel_thresh(self, img, orient='x', sobel_kernel=3, thresh=(0, 255)):
# Calculate directional gradient
# Apply th... |
#!/usr/bin/env python
"""
Models for info if needed
"""
class Product:
"""
A class for
ProductId – an integer uniquely identifying the Product
Name – a string name for the Product
Price – a floating point price at which the Product is sold (per unit, not per lot)
LotSize – an integer ... |
'''
Copyright (c) 2015, Salesforce.com, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the foll... |
# empty init file
|
'''
Several testcases around <Transformer> and it's arguments.
'''
import unittest
import utils
def suite():
suite = unittest.TestSuite()
suite.addTest(TransformerEncodeTestCase())
suite.addTest(TransformerEncode2TestCase())
suite.addTest(TransformerEncode3TestCase())
return suite
class Transforme... |
import unittest
from visuanalytics.tests.analytics.transform.transform_test_helper import prepare_test
class TestTransformCalculate(unittest.TestCase):
def setUp(self):
self.data = {
"testvalue1": 5,
"testvalue2": 3.7,
"testarray1": [5, 4, 7, 1, 3, 6],
"tes... |
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc 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 late... |
import sys, os
from faster.fastlist import fastlist
import cProfile
from pstats import SortKey
l = fastlist.from_sequence(list(range(10)))
l.insert(0, 4)
print(l)
print(l.count(5))
print(l)
del l
# mult = 2 ** 24
# length = 15
# print('mult:', mult)
# print('size:', mult * length)
# print('\nfastlist:')
# cProfile... |
from CTFe.views.auth_view import router as auth_router
from CTFe.views.user_view import router as user_router
from CTFe.views.team_view import router as team_router
from CTFe.views.challenge_view import router as challenge_router
from CTFe.views.attempt_view import router as attempt_router
from CTFe.views.player_view i... |
"""
Unit tests for the User Controller.
"""
from datetime import datetime
from unittest.mock import patch
from app.controllers.user_controller import UserController
from app.models import User, Role
from app.models.user_role import UserRole
from app.repositories import UserRepo, RoleRepo, UserRoleRepo
from tests.base_... |
from django import forms
class ContactForm(forms.Form):
""" Create form for contact page """
email = forms.EmailField(
required=True,
label='',
widget=forms.EmailInput(attrs={
'class': 'form-control border-black rounded-0 mb-3',
'placeholder': 'Email',
... |
def select_rows(df, where):
"""Performs a series of rows selection in a DataFrame
Pandas provides several methods to select rows.
Using lambdas allows to select rows in a uniform and
more flexible way.
Parameters
----------
df: DataFrame
DataFrame whose rows should be selected
... |
def fibonacci(n):
if n <= 1:
return 1
else:
return fibonacci(n-2) + fibonacci(n-1)
def factorial(n):
if n== 0:
return 1
else:
return n*factorial(n-1) |
import sys
import math
import scipy as sp
import scipy.stats
from scipy.stats import norm
from scipy.stats import poisson, binom, hypergeom
from permute.utils import binom_conf_interval, hypergeom_conf_interval
from numpy.random import choice
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.... |
# Copyright 2013-2019 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)
from spack import *
class PyMpi4py(PythonPackage):
"""This package provides Python bindings for the Message Passing
... |
from core.advbase import *
import adv.g_cleo
def module():
return Gala_Cleo
class Gala_Cleo(adv.g_cleo.Gala_Cleo):
def prerun(self):
super().prerun()
self.a1_zones = []
self.gleo_count = 4
self.wide = 'self'
self.comment = '{} GCleo'.format(self.gleo_count)
def fs_... |
#!/usr/bin/python3
# This program is the basic form of the sumobot program
# 1. Connect sensors and initialise motors
# 2. Wait 3 seconds before starting
from time import sleep
import sys, os
from ev3dev.ev3 import *
#Connect motors
rightMotor = LargeMotor(OUTPUT_B)
leftMotor = LargeMotor(OUTPUT_C)
# Connect touc... |
"""
MIT License
Copyright (c) 2021 Visperi
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
to use, copy, modify, merge, publish, distr... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/proto/spanner/v1/query_plan.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.pro... |
# Copyright 2017 University of Maryland.
#
# This file is part of Sesame. It is subject to the license terms in the file
# LICENSE.rst found in the top-level directory of this distribution.
|
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
if os.path.exists('README.txt'):
README = open('README.txt').read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.a... |
# Generated by Django 4.0.3 on 2022-03-09 03:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
import logging
import random
import time
import requests
from stem import Signal
from stem.control import Controller
from stem.util.log import get_logger
logger = get_logger()
logger.propagate = False
# site to get ip
IP_CHECK_SERVICE = 'http://icanhazip.com/'
class TorController:
def __init__(self, allow_reuse... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input params
"""
__author__ = "Saeed Moghimi"
__copyright__ = "Copyright 2017, UCAR/NOAA"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "moghimis@gmail.com"
from pynmd.plotting.vars_param import *
from collections import defaultdict
import datetime
cases ... |
import numpy as np
from sklearn import svm
from sklearn.externals import joblib
from dynamic_programming import neural_classif_usage as nn
class DynamicProgramming:
def __init__(self, model_path, model_file, offline_file):
self.model_path = model_path
self.model_file = model_file
self.off... |
"""Entry point"""
from domination.process import app
def main():
"""Run faust main"""
app.main()
if __name__ == '__main__':
main()
|
__author__ = 'Owais Lone'
__version__ = '0.7.0'
default_app_config = 'webpack_loader.apps.WebpackLoaderConfig'
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from onnx import numpy_helper
def get_parameter_name(name):
"""
Gets parameter name from parame... |
# -*- coding: utf-8 -*-
# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document
import requ... |
import json
from compare import expect
from django.test import TransactionTestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from lxml import etree
from tardis.tardis_portal.models import Experiment, License, ObjectACL, User
def _create_user_and_login(username='testuser', ... |
import os
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for, current_app
)
from .db import Database
bp = Blueprint('portal', __name__)
@bp.route('/admin', methods=['GET'])
def admin():
return render_template("admin/admin_home.html")
@bp.route('/admin/table/<string:table_... |
from cx_Freeze import setup, Executable
base = None
executables = [Executable("lzss3.py", base=base)]
packages = ["idna"]
options = {
'build_exe': {
'packages':packages,
},
}
setup(
name = "Decompress",
options = options,
version = "1.0.0.0",
description = "Decompress a f... |
from collections import defaultdict
from datetime import timedelta
import re
from typing import Dict, List
from django.core.exceptions import SuspiciousOperation
from django.db.models import Q, query, Sum
from django.http import Http404
from django.urls import reverse_lazy
from django.utils import timezone
from django... |
"""
AWGs
"""
from atom.api import Atom, List, Int, Float, Range, Enum, Bool, Constant, Str
from .Instrument import Instrument
import enaml
from enaml.qt.qt_application import QtApplication
import glob
import copy
class AWGDriver:
naming_convention = []
def get_naming_convention(self):
# return cop... |
from numpy import *
from matplotlib.pyplot import *
x=loadtxt('cluster_test.txt')
N=x.shape[0]
M=zeros((N,N))
# critical distance
dc=7
for i in range(N):
for j in range(i+1, N):
M[j, i] = M[i, j] = (sum((x[i, :]-x[j, :])**2))**0.5
print('matrix of distances is ready')
l1=[]
l2=[]
l3=[]
res... |
"""
Purpose: Summarizes the alternatives of the bluebooks
Status: Final -- 06/27/2019
@author: olivergiesecke
"""
###############################################################################
### Set packages ###
import pandas as pd
import re
import os
import matplotlib.pyplot as plt
import numpy as np
##########... |
# Copyright (c) 2018-2021, Texas Instruments
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of condition... |
from django.db import models
from utils.models import BaseModel
# Create your models here.
class Link(BaseModel):
""" 友情链接 """
name = models.CharField(max_length=32, verbose_name="名称")
url = models.URLField(max_length=64, verbose_name="URL地址")
def __str__(self):
return self.name
class ... |
"""Reference implementations of graph algorithms."""
import numpy as np
import scipy.sparse as sparse
def bellman_ford_reference(A, c):
"""Reference implementation of Bellman-Ford.
Parameters
---------
A : coo sparse matrix
n x n directed graph with positive weights
c : array_like
... |
import psycopg2
import psycopg2.extras
from Infrastructure import log
logger = log.get_logger("Postgres")
class Connector:
def __init__(self, config):
self.host = config['hostname']
self.database = config['database']
self.user = config['username']
self.password = config['password... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 18 20:10:30 2021
@author: Mohamed Salah
"""
# Import libraries and methods
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_erro... |
## @ingroupMethods-Noise-Fidelity_One-Propeller
# compute_broadband_noise.py
#
# Created: Mar 2021, M. Clarke
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import SUAVE
from SUAVE.Core import Units , Data
i... |
from collections import namedtuple
from board import Player, Point
def compute_game_result(game_state):
num_b, num_w = 0, 0
for r in range(1, 8):
for c in range(1, 8):
player = game_state.board._grid.get(Point(r, c))
if player is None:
if game_state.add_player ... |
#! /usr/bin/env python
from __future__ import print_function, unicode_literals
import sys
import pyATP
dat_lines = '''BEGIN NEW DATA CASE
LINE CONSTANTS
$ERASE
BRANCH IN___AOUT__AIN___BOUT__BIN___COUT__C
ENGLISH
3 0.0 .1357 0 .3959 1.18 5. 42. 30.
1 0.0 .1357 0 .3959 1.18 -5. ... |
from typing import Union, Sequence, Tuple
import numpy as np
import torch
from torch.utils.data import Dataset
from torchio import IMAGE, LOCATION
from torchio.utils import to_tuple
class GridSampler(Dataset):
"""
Adapted from NiftyNet.
See https://niftynet.readthedocs.io/en/dev/window_sizes.html
"""
... |
from .quiz import Quiz
def setup(bot):
bot.add_cog(Quiz(bot))
|
# palabras.py
# imprime palabras que no empiezan con "f"
# ni tienen menos que 4 caracteres
palabras = ['python', 'academy', 'fundamentals', 'ibm', 'kyndryl']
for p in palabras:
if len(p) < 4: # si <p> tiene menos que 4 caracteres
continue
if p.startswith('f'): # si <p> empieza con "f"
... |
import requests
import arrow
import os
import csv
from fuzzywuzzy import fuzz
SENSITIVITY = 60
def download_data():
'''Downloads and decodes the dataset
and passes to org_list function'''
dataset = []
timenow = arrow.now('GMT').format('MMYY')
filename = "{}paydata.csv".forma... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
import torch
torch.rand(10)
import torch.nn as nn
import torch.nn.functional as F
import glob
from tqdm import tqdm, trange
print(torch.cuda.is_available())
print(torch.cuda.get_device_name())
print(torch.cuda.current_device())
device = torch.device('cuda' if torch.cu... |
from selenium import webdriver
from time import sleep
from random import randint
from secrets import *
class GithubBot:
def __init__(self, username, pw, copyfollowers):
self.username = username
self.copyfollowers = copyfollowers
# START LOGIN PROCESS
self.driver = webdriver.Chrome... |
# -*- coding: utf-8 -*-
from flask_oauthlib.contrib.apps import RemoteAppFactory
mit = RemoteAppFactory('mit', {
'base_url': 'https://oidc.mit.edu',
'access_token_url': '/token',
'authorize_url': '/authorize',
'request_token_url': None,
'request_token_params': {'scope': 'openid,email,profile'},
})... |
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
# Let’s run the basic SIR model
# describe the model
def deriv(y, t, N, beta, k, delta, m ):
S, E, I, R, D = y
dSdt = -beta * S * I / N
dEdt = (beta * S * I / N - k * E)
dIdt = delta * E - k * I
dRdt = k * I ... |
#!/usr/bin/python
"""
Jamf Pro extension attribute to return a list of authorization rights
enabled on a Mac. The returned levels are...
- allow - unlocks the associated preference pane without admin rights
- authenticate-session-owner-or-admin - requires credentials, but
allows standard users to authent... |
import Snake as s
import Fruit as f
snake = s.Snake()
fruit = f.Fruit()
start = True
#processing option for screen
def setup():
size(400,400)
frameRate(20)
def draw():
global snake, fruit, start
#home screen
if start == True:
background(0)
fill(255)
textAlign(CENT... |
from __future__ import annotations
import os
from base64 import b64decode
from collections import defaultdict
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, replace
from enum import Enum
from ipaddress import IPv4Address, IPv4Network
from pathlib import Path
from typing import Any
im... |
import os, pymorphy2, string, math
import re
# Create pymorphy2 instance for methods that use pymorphy2
morph = pymorphy2.MorphAnalyzer(lang = 'uk')
ukrainian_letters = ['й','ц','у','к','е','н','г','ш','щ',
'з','х','ї','ґ','є','ж','д','л','о','р','п','а','в','і','i', #Cyrrilic and latin i
'ф','я','ч','с','м','и','т... |
import dash
import dash_html_components as html
import json
import dash_leaflet as dl
from examples import geojson_csf
from dash_extensions.transpile import inject_js, module_to_props
# Create geojson.
with open("assets/us-states.json", 'r') as f:
data = json.load(f)
js = module_to_props(geojson_csf) # do transc... |
from .fetcher import ResourceFetcher
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.