content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# from contextlib import contextmanager
from datetime import datetime, timedelta
import requests
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen
from kivy.weakproxy import WeakProxy
from kivymd.uix.bottomsheet import... |
#
# Copyright 2020, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any commercial
# use must be negotiated with the Office of Technology Transfer at the
# California Institute of Technology.
#
"""
======================
transaction_on_disk.py
==... |
import os
from ansys.mapdl.core import __version__
from ansys.mapdl.core.misc import is_float
from ansys.mapdl.core.commands import Commands
def convert_script(
filename_in,
filename_out,
loglevel="WARNING",
auto_exit=True,
line_ending=None,
exec_file=None,
macros_as_functions=True,
u... |
#Ler a opção do usuário e "jogar" pedra, papel, tesoura "com" ele
from random import choice
print("-=" * 10,"Vamos jogar PEDRA PAPEL TESOURA!", "-=" * 10);
usuario = str(input("Sua vez! Digite PEDRA PAPEL ou TESOURA: ")).upper().strip();
jogadas = ['PEDRA','PAPEL','TESOURA'];
pc = choice(jogadas);
if usuario ... |
"""
Author: Alexandra Lee
Date Created: 10 August 2021
Scripts to analyze relationships between gene types
"""
import pandas as pd
import numpy as np
def get_relationship_in_genome_space(core_acc_df, offset_to_bin, operon_df=None):
"""
For each accessory gene, is the 1-NN/2-NN/3-NN core or accessory? This fu... |
import logging
import math
from random import gauss
import numpy as np
from functools import lru_cache
from mesa import Agent
# from linetimer import CodeTimer
from elecsim.market.electricity.bid import Bid
from elecsim.plants.availability_factors.availability_factor_calculations import get_availability_factor
from el... |
# -*- coding: utf-8 -*-
import os
import sys
import json
import getopt
from .core.datagen import DataGenerator
__version__ = "0.0.0"
def usage():
os.system('clear')
print """
***********
* PyDummy *
***********
Python command line tool for creation of dummy/fake/mocked data
Parameters
... |
class BoardingPassScanner:
def __init__(self, data):
self.__data=data
self.__boardingPasses=[]
self.__parse()
def __parse(self):
for d in data:
bP = BoardingPass(d)
#print(bP.getRow())
self.__boardingPasses.append(bP)
def getBoardin... |
import numpy as np
import torch
from torch.optim import Adam
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import gym
import time
from tqdm import tqdm
import os, sys
from json import JSONEncoder
import json
import spinup.algos.pytorch.vpg.core as core
from spinup.algos.pytorch.ppo.broil_ppo impo... |
from typing import Optional, List
from pydantic import BaseModel
class FileMetadata(BaseModel):
id: str
referenceId: Optional[str] = None
newName: Optional[str] = None
folder: Optional[str] = None
class FileMetadataPostRequest(BaseModel):
metaData: List[FileMetadata]
|
import json
from dbconn import lyncdb
# userinfo ={'2': ['f', '3'],'3':['e','4']} # 用户名 年龄 联系方式
def add_user(info):
userinfo[info[0]] = info[1:]
print(userinfo) # 保存用户信息
def delete_user(username):
if username in userinfo:
db.dml('delete from user where name = "{}"'.format(username))
else:
... |
# server that can host multiple client processses
# importing th necessary packages
import socket
import random
import threading
from threading import Thread
# function that checks whether a user has a login record or not in that user dictionary
def check_id(id):
if id in user.keys(): ... |
_base_ = './cityscapes.py'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (768, 768)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(type='LoadNsctNpy'),
dict(type='ResizeWithNSCT', img_scale=(2049, 1... |
from coincap.coincap import CoinCap
import unittest
class TestCoinCap(unittest.TestCase):
"""
Unit tests
"""
def setUp(self):
self.coin_cap = CoinCap()
def test_history_failure(self):
with self.assertRaises(Exception):
self.coin_cap.get_coin_history('BTC', 9)
def... |
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import requests
import json
app = FastAPI()
security = HTTPBasic()
# Load configuration
with open('config/config.json', 'r') as file:
config = json.load(file)
@app.get("/ddns/{new_ip}")
def dyndns(... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# This program is optimized for Python 2.7
import subprocess
import shlex
command_line = "ping -c 1 www.baidu.com"
args = shlex.split(command_line)
try:
subprocess.check_call(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
print "能p... |
import pytest
from process_reports import read_buckets, read_bucket_sheet
import os
import pandas as pd
import logging
import numpy as np
good_bucket = os.path.join('Sample_Reports', '2_1_18Bucket_Scrubbed.xls')
updated_bucket = os.path.join('Sample_Reports', 'Daily_Queues_by_Bucket.7.3.18_Scrubbed.xls')
mixed_bucket ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-30 02:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('groups', '0001_initial'),
('tracker', '0004_auto_20... |
def prime_or_composite(number):
"""
- Add code in the defined function to figure out whether or not the given number is a prime number or not.
- A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not ... |
from ds.data_source_mapping_config import DataSourceMappingConfig
from ds.data_source_mapper import DataSourceMapper
class DataSourceMappingManager:
"""description of class"""
def __init__(self, base_path, mapping_config):
self.__cfg = DataSourceMappingConfig(base_path,
... |
import pytest
from kiali_qe.tests import (
ServicesPageTest,
ApplicationsPageTest,
WorkloadsPageTest,
IstioConfigPageTest
)
from kiali_qe.components.enums import (
ServicesPageFilter,
ApplicationsPageFilter,
WorkloadsPageFilter,
IstioConfigPageFilter,
IstioSidecar,
HealthType,
... |
"""add experiment_type
Revision ID: 2abf47f3721a
Revises: 69484796482
Create Date: 2018-04-09 09:46:00.107024
"""
# revision identifiers, used by Alembic.
revision = '2abf47f3721a'
down_revision = '69484796482'
import sqlalchemy as sa
from alembic import op
def upgrade():
try:
op.add_column('AnalysisT... |
from unittest import mock
from .. import *
from bfg9000.languages import Languages
from bfg9000.path import Root
from bfg9000.tools import cc, common
known_langs = Languages()
with known_langs.make('c') as x:
x.vars(compiler='CC', flags='CFLAGS')
def mock_which(*args, **kwargs):
return ['command']
def mo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 21:13:58 2020
@author: safir
"""
# Building the DataSet
fields = ['State', 'Climate', 'Age', 'Body_Shape', 'Immune_Strength', 'Mood', 'Migrant', 'Chocolate_Lover', 'Hangout', 'Stressed', 'Depressed', 'Literate', 'Food_preference', 'Friend_Circl... |
# -*- coding: utf-8 -*-
"""
a Lattice object with reduction algorithms
"""
import sys
import time
import random
from fpylll import IntegerMatrix, LLL, BKZ
from fpylll.algorithms.bkz2 import BKZReduction as BKZ2
from fpylll.util import gaussian_heuristic, ReductionError
from g6k.algorithms.pump import pump
from g6k.si... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tools/modelbase.py
#
#
# MODEL DEFINITION:
# 1. create a subclass.
# 2. set each definitions as below in the subclass.
#
# __structure__ = {} # define keys and the data type
# __required_fields__ = [] # lists required keys
# __default_values__ = {} # set def... |
from . import _py2java_double_array, _nparray2breezevector, _nparray2breezematrix
from ._model import PyModel
from pyspark.mllib.common import _py2java, _java2py
"""
Models a time series as a function of itself (autoregressive terms) and exogenous variables, which
are lagged up to degree xMaxLag.
"""
def fit_model(y... |
# pylint: disable=W0401
from .test_views import *
from .test_filters import *
|
import braintree
import stripe
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response i... |
preço = float(input('Digite o preço do produto: R$'))
novo = preço - (preço*0.05)
print('O produto com 5% de desconto fica por R${:.2f}'.format(novo)) |
from __future__ import annotations
import os
import tqdm
import collections
BASE_PATH = os.path.dirname(__file__)
INPUT_PATH = os.path.join(BASE_PATH, "input.txt")
def main() -> int:
print(f"Day №{os.path.basename(BASE_PATH)}")
print(f"Part №2")
with open(INPUT_PATH, mode="r") as file:
raw_inpu... |
# encoding: utf-8
"""
@author: lileilei
@site:
@file: __init__.py
@time: 2017/7/13 16:38
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from config import lod
from apscheduler.schedulers.background import BackgroundSchedule... |
from .toaststack import PopupStack
from .toast import Popup, popup, cancel_all, cancel_id |
import setuptools
with open("tomsup/about.py") as f:
v = f.read()
for l in v.split("\n"):
if l.startswith("__version__"):
__version__ = l.split('"')[-2]
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="tomsup",
version=__version__,
de... |
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import numpy as np
class Dataset(object):
def __init__(self, txt_file, vocab):
self.text = txt_file
self.vocab = vocab
def load_data(self):
with ... |
#!/usr/bin/env runaiida
#Not required by AiiDA
import os.path as op
import sys
#AiiDA classes and functions
from aiida.engine import submit
from aiida.orm import load_code
from aiida.orm import (Dict, StructureData, KpointsData)
from aiida_siesta.calculations.siesta import SiestaCalculation
from aiida_siesta.data.ion... |
# Copyright 2021 Fedlearn authors.
# 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 writi... |
from web_app.scripts.init_settings import Settings
from web_app import create_app
from config import Config
import eventlet
eventlet.monkey_patch()
def init_app(app):
# initialize db config records
settings = Settings()
settings.populate_db()
# Enable Web-Sockets support
from flask_socketio impor... |
import sys
sys.path.insert(0,'..')
import time
import gym_aeris.envs
from AgentRandomMulti import *
env = gym_aeris.envs.SwarmFoodGatheringEnv()
env.reset()
agent = AgentRandomMulti(env)
k = 0.998
fps = 0
while True:
time_start = time.time()
agent.main(verbose=False)
time_stop = time.time()
f... |
"""Test suite for the renault_api CLI."""
import os
from typing import Optional
from tests.const import TEST_ACCOUNT_ID
from tests.const import TEST_LOCALE
from tests.const import TEST_LOGIN_TOKEN
from tests.const import TEST_PERSON_ID
from tests.const import TEST_VIN
from tests.fixtures import get_jwt
from renault_a... |
from header_common import *
from module_info import *
from module_sounds import *
def write_python_header(sounds):
file = open("./ID_sounds.py","w")
for i_sound in xrange(len(sounds)):
file.write("snd_%s = %d\n"%(sounds[i_sound][0],i_sound))
file.write("\n\n")
file.close()
def write_sounds(soun... |
"""The app command."""
from json import dumps
from .base import Base
import ruamel.yaml
class Add_config(Base):
"""Cluster commands"""
def run(self):
self.append_launch_file(self.options['<app>'])
|
import pyeccodes.accessors as _
def load(h):
h.add(_.Position('startOfHeaders'))
h.add(_.Ascii('identifier', 4))
h.alias('ls.identifier', 'identifier')
h.add(_.Transient('missingValue', 9999))
h.add(_.Constant('ieeeFloats', 0))
h.add(_.Constant('zero', 0))
_.Template('diag/section.1.def')... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from ..monitoring import MonitoredEntity_pb2 as monitoring_dot_MonitoredEntity__pb2
from ..monitoring import MonitoredModel_pb2 as monitoring_dot_MonitoredModel__pb2
class MonitoredModelServiceStub(object):
# missing associated docum... |
from sortingandsearching.reading_books import *
class TestReadingBooks:
def test_case_1(self):
assert solve([2, 8, 3]) == 16
def test_case_2(self):
assert solve([1000, 1000, 1000, 1000, 1000]) == 5000
def test_case_3(self):
assert solve([1, 2, 3, 4, 5, 6, 9, 8, 7, 16])... |
import multiprocessing
bind = 'unix:/var/run/gunicorn.sock'
worker_class = 'gevent'
worker_connections = (multiprocessing.cpu_count() * 2 + 1) * 1000
workers = multiprocessing.cpu_count() * 2 + 1
|
from torch import nn
import torch.nn.functional as F
import math
# MNIST Fully Connected Net ----------------------------------------------------
class MNISTNet(nn.Module):
def __init__(self):
super(MNISTNet, self).__init__()
self.fc1 = nn.Linear(28 * 28, 512)
self.fc2 = nn.Linear(512, 10... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-04-28 18:26
from __future__ import unicode_literals
from django.db import migrations, models
from intake.models import ApplicationEvent
def backfill_submissions_with_followups_from_events(apps, schema_editor):
db_alias = schema_editor.connection.alias
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright 2014 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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 th... |
import numpy as np
import pandas as pd
from pandas.tools.merge import concat
from scipy.stats import ranksums
from munge import toPrettyCsv
# from utils import *
from results_utils import *
COMBINED_CSV_FILE = 'combined.csv'
ERRS_CSV_FILE = 'errRates.csv'
RANK_CSV_FILE = 'combined_rank.csv'
ZVALS_CSV_FILE = 'combine... |
desired_value = 200 # 2£ in pennies
currency_dict = {"1p": 1, "2p": 2, "5p": 5, "10p": 10, "20p": 20, "50p": 50, "1£": 100, "2£": 200}
currency_list = ["1p", "2p", "5p", "10p", "20p", "50p", "1£", "2£"]
coin_combinations = []
def value_coins(coins_list):
return sum([currency_dict[coin]*coefficient fo... |
# -*- coding: utf-8 -*-
from unittest import TestCase
from ....Classes.Mesh import Mesh
from ....Classes.NodeMat import NodeMat
from ....Classes.ElementMat import ElementMat
import numpy as np
class unittest_get_coord(TestCase):
"""unittest for NodeMat get_node methods"""
def setUp(self):
self.mesh ... |
from ._feedback import Feedback
from .math import ray_casting_walls, compute_dist_bins
from .datastructures import LazyFrames
|
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_shape_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/shape/dbfopen.c",
"../gdal/ogr/ogrsf_frmts/shape/dbfopen_wrapper.c",
"../gdal/ogr/ogrsf_frmts/shape/ogrshapedatasource.cpp",
"../gda... |
"""
Single place to register all signals and slots helping to avoid cupling
between GUI elements and function providing objects
"""
__version__ = '0.01'
__author__ = 'Adrian Phung'
from Operations.config import Config
class globalInformationOps():
def __init__(self, globalInformation):
self.global_info... |
# coding=utf-8
# Copyright 2022 DataLab Authors and the current dataset script contributor.
#
# 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
... |
import numpy as np
import pandas as pd
from glob import glob
from tqdm import tqdm
for ethn in ['WC', 'EA']:
print(f"Processing ethnicity {ethn}")
files = sorted(glob(f'data/ratings/{ethn}/sub-*.tsv'))
mega_df = pd.concat([pd.read_csv(f, sep='\t', index_col=0).assign(sub_split='test' if i % 3 == 0 else '... |
from back.settings.routes.api import register_api_routes
from front.tree.home.route import register_home_route
from front.tree.home.countries.route import register_countries_route
from front.tree.home.countries.country.route import register_country_route
from front.tree.home.indicators.route import register_indicato... |
########################################################################
#
# Vision Network - Python source code - file generated by vision
# Tuesday 20 December 2005 14:00:56
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoff... |
import argparse
from collections import defaultdict
import time, os
import numpy as np
from softlearning.environments.gym.locobot import *
from softlearning.environments.gym.locobot.utils import *
from softlearning.environments.adapters.gym_adapter import GymAdapter
from softlearning.environments.gym.locobot.locobot... |
import os
import setuptools
import setuptools.ssl_support
# configure ssl certifiate bundle from environment, if set
ssl_cert_file = os.environ.get("SSL_CERT_FILE") or os.environ.get("PIP_CERT")
if ssl_cert_file:
setuptools.ssl_support.cert_paths = [ssl_cert_file]
setuptools.setup(
name="geomag-algorithms",
... |
"""Kata url: https://www.codewars.com/kata/5a58d46cfd56cb4e8600009d."""
def halving_sum(n) -> int:
r: int = n
while n != 1:
n //= 2
r += n
return r
|
#!/usr/bin/python
# 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
# di... |
from abc import ABC
from tradingkit.pubsub.core.subscriber import Subscriber
from tradingkit.pubsub.event.plot import Plot
class Plotter(Subscriber, ABC):
def subscribed_events(self) -> list:
return [Plot]
|
from turtle import Turtle, Screen
t = Turtle() # turtle instance creation
for i in range(5):
t.forward(50) # turtle instance method
t.right(144) # turtle instance method
screen = Screen() # access sole screen instance
screen.mainloop() # screen instance method
|
from utils.activities import ActivitiesUtil
def build_like_activity(like_actor, liked_object):
return {
"@context": ActivitiesUtil.rabble_context(),
'type': 'Like',
'object': liked_object,
'actor': {
'type': 'Person',
'id': like_actor,
},
}
|
"""Constants for the Minecraft Server integration."""
from collections import defaultdict
from typing import Dict, List, Literal, Set, Tuple
ATTR_PLAYERS_LIST = "players_list"
DEFAULT_HOST = "localhost:25565"
DEFAULT_NAME = "Minecraft Server"
DEFAULT_TYPE = "JAVA"
DEFAULT_PORT = 25565
DOMAIN = "minecraft_server"
IC... |
'''
Author - Abhishek Maheshwarappa and Jiaxin Tong
'''
import os
import sys
import time
import json
import datetime
import logging
import numpy as np
import pandas as pd
from libraries.ABTestSimulator import ABTestReplayer
from libraries.MAB import ThompsonSamplingReplayer
from libraries.EpsilonGree... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay Inc.
#
# Licensed under th... |
from itertools import product
import yaml
import os
import sys
import subprocess
import re
import h5py
import numpy
def get_result_fn(dataset, algorithm, eps, mu):
dir_name = os.path.join("results", dataset, algorithm, mu)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
return os.path.join(d... |
import numpy as np
from integration import a, b, c, A, N_sat, n
# Analytical solution calculated by hand.
# -(b**3*A*N_sat*(x/b)**a*(c*(x/b)**c-a+3)*e**(-(x/b)**c))/x**4
analytical_solution_x_equal_to_b = -A*N_sat*(c-a+3)/(b*np.e)
# Define the numerical differentiator using central difference method.
def central_dif... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contribution',
fields=[
('id', models.AutoField... |
"""Common test interfaces."""
from typing import Any
class SomeClass:
"""Testing class."""
def foo(self, val: str) -> str:
"""Get the foo string."""
...
def bar(self, a: int, b: float, c: str) -> bool:
"""Get the bar bool based on a few inputs."""
...
def do_the_thin... |
#!/usr/bin/env python3
import sys
import argparse
import re
import quopri
from functools import partial
class VCard:
BEGIN = 'BEGIN:VCARD'
END = 'END:VCARD'
FN = re.compile('FN[:;]')
NICKNAME = re.compile('NICKNAME[:;]')
def __init__(self, prune_empty=False):
self.reset()
self._pru... |
#!/usr/bin/python
from __future__ import print_function
import requests
device = 'dddddddddddddddddddddddd'
authorization = {
'Authorization': 'Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
}
def getgdstatus(device_id, auth_id):
data = {
'arg': 'gdstatustest'
}
response = requests.get('https://... |
PO4_PDB_CODES = ['A', 'C', 'G', 'T', 'U', 'DA', 'DC', 'DG', 'DT', 'DU', 'IC', 'IG']
PO4_ATOM_NAMES = {
'P': 'P',
'OP1': 'OP1',
'O1P': 'OP1',
'OP2': 'OP2',
'O2P': 'OP2',
"O5'": "O5'",
"O5*": "O5'",
"O3'": "O3'",
"O3*": "O3'",
"C5'": "C5'",
"C5*": "C5'",
"C3'": "C3'",
... |
from ..optics import OpticalElement
class Propagator(OpticalElement):
pass
|
default_app_config = "example.drf_integrations_example.apps.IntegrationsExampleConfig"
|
#!/usr/bin/python3
import PySimpleGUI as sg
from app import PreciousApp
from init_db import reset_db
from get_icon import get_icon
from time import sleep
"""
Overall flow:
If sqlite database does not exist -- create it (this happens only once
at the start of the app for the first time)
SQLite is the best because it... |
# coding: utf-8
from functools import wraps
from os import path
import json
import ssl
import certifi
from redis_wrap import get_hash, get_list, SYSTEMS
__name__ = 'eth0_bot'
__bot__ = 'eth0'
__config__ = path.abspath(path.join(path.dirname(__file__), 'config.json'))
with open(__config__, 'r') as cfr:
config = j... |
#sliceing :
# a=[1,3,5,7,9,0,2,4,6,8]
# # print(a[len(a)-1:0:-1]) # 모두 프린트 하고 싶으면 0이면 안된다
# # print(a[len(a)-1:-1:-1]) #[] : 확인이 필요
# print(a[len(a)-1::-1]) #모두 프린트 됨
#
# print(a[::-2]) #2칸 간격으로 출력
# print(a[-2::-2]) #맨 뒤가 음수이기때문에 역순 출력 : 맨 앞도 음수여야 한다.
# #폴더에 c... |
"""
A small Python program that uses the GitHub search API to list
the top projects by language, based on stars.
"""
import requests
GITHUB_API_URL = "https://api.github.com/search/repositories"
def create_query(languages, min_stars=50000):
query = f"stars:>{min_stars} "
for language in languages:
... |
def get_major_version(filename):
return int(filename[14])
def get_elasticsearch_base_url(version):
if version < 5:
return 'https://download.elasticsearch.org/elasticsearch/elasticsearch'
return 'https://artifacts.elastic.co/downloads/elasticsearch'
def get_elasticsearch_generic_command(version, ... |
import os
from dotenv import load_dotenv
workingdirectory = os.getcwd()
filename = os.path.join(workingdirectory, '.env')
if os.path.exists(filename):
load_dotenv(filename)
print('env file loaded from {0}'.format(filename))
|
def S(T):
return 0 if T==1 else [S(T[0])]+T[1:]
def Helper(T, c, B=None):
pass
def R(T, c, B=None):
U=T[0]
V=T[1:]
#global B
print(T)
try:
print("B:", B)
except:
pass
if T[-1]==0:
B=T
try:
print("B':", B, "\n")
except:
pass
if U==1:
return [S(B)]+V, B
return ... |
"""Base tools for visualizing data."""
# --- import --------------------------------------------------------------------------------------
import numpy as np
import matplotlib
from matplotlib.axes import SubplotBase, subplot_class_factory
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axe... |
import client , server
def main():
portno = 61619
id = "client"
host = "data.cs.purdue.edu"
message = "Message from client"
c1 = client.client(portno , id , host)
c1.sendMsg(message)
c1.receive()
if __name__ == '__main__':
main() |
def get_fields_from_query(q):
fields = [k for k in q.split() if k.isalnum()]
return fields
def get_depth(q):
depth = 0
for i in q.split():
if i == '{':
depth += 1
return depth
|
from itertools import combinations
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
a=[]
for x in range(len(nums)+1):
a+=set(list(itertools.combinations(sorted(nums), x)))
a[:]=[list(x) for x in a ]
return a
|
#!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: icx_copy
author: "Ruckus Wireless (@Commscope)"
short_descri... |
#!/usr/bin/env python3
# Copyright 2021 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... |
from datetime import date
import pytest
from django.urls import reverse
from supply_chains.models import StrategicActionUpdate
from supply_chains.test.factories import (
SupplyChainFactory,
StrategicActionFactory,
StrategicActionUpdateFactory,
)
from supply_chains.templatetags.supply_chain_tags import ge... |
import pandas as pd
import csv
import json
from functools import reduce
from string import printable
import math
def checkfloat(v):
try:
float(v)
return True
except ValueError:
return False
semantictype=['person_name','business_name', 'phone_number', 'address', 'street_name', \
'city', 'neig... |
from chessgame.chessBoard import Board
chessboard = Board()
chessboard.create_board()
chessboard.add_pieces()
print(chessboard.game_matrix[6][0].color)
|
import argparse
import logging
from pathlib import Path
import numpy as np
import pandas as pd
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem
from rdkit.ML.Cluster import Butina
from sklearn.model_selection import train_test_split
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("Sp... |
'''
Author: Eric P. Nichols
Date: Feb 8, 2008.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tuples.
x is the column, y is the row.
'''
imp... |
import socket
try:
import horovod.tensorflow as hvd
except ImportError:
hvd = None
import tensorflow.compat.v1 as tf
def is_rank0():
if hvd is not None:
return hvd.rank() == 0
else:
return True
global IS_HVD_INIT
IS_HVD_INIT = False
def hvd_try_init():
global IS_HVD_INIT
if... |
from options.test_options import TestOptions
from data import DataLoader
from models import create_model
from util.writer import Writer
def run_test(epoch=-1):
print('Running Test')
opt = TestOptions().parse()
opt.serial_batches = True # no shuffle
dataset = DataLoader(opt)
model = create_model(o... |
import unittest
class LexerTestCase(unittest.TestCase):
def makeLexer(self, text):
from spi import Lexer
lexer = Lexer(text)
return lexer
def test_tokens(self):
from spi import (
INTEGER_CONST, REAL_CONST, MUL, INTEGER_DIV, FLOAT_DIV, PLUS, MINUS, LPAREN, RPAREN,
... |
#!/usr/bin/env python3
import os
import json
import sys
import templates
print("Content-Type: text/html\r\n\r\n")
print("<!doctype html><title>Hello</title>\r\n<h2>hello world</h2>\r\n")
#Q1
jsonObject = json.dumps(dict(os.environ), indent=4)
#print(jsonObject)
print("\r\n")
#Q2
for keys, value in os.environ.items():... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.