content stringlengths 5 1.05M |
|---|
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/python/ReconstructionSystem/sensors/realsense_recorder.py
# pyrealsense2 is required.
# Please see instructions in https://github.com/IntelRealSense/librealsense/tree/master/wrappers/python
import pyreal... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^job-meta/',views.job_meta, name='job_meta'),
url(r'^job-success-failure',views.job_success_failure_ratio, name='job_success_failure_ratio'),
url(r'^$',views.dashboard, name='dashboard'),
] |
# Copyright 2008-2018 Univa Corporation
#
# 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... |
import tweepy # To consume Twitter's API
import pandas as pd # To handle data
import numpy as np # For number computing
from textblob import TextBlob # for sentimental
import re
# For plotting and visualization:
from IPython.display import display
# for display use only import matplotlib.pyplot as... |
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from models import db_base as base
import os
import json
__author__ = "zadjii"
class Issue(base):
__tablename__ = "issue"
"""
Represents a single issue
"""
... |
port = 8888
logging = 'info'
log_file_prefix = "tivid-error.log"
redis_host = 'localhost'
redis_port = 6379
redis_db = 0
java_source = "http://www.importnew.com/all-posts"
python_source = "http://python.jobbole.com/all-posts/"
|
from threading import Thread
def async_func(f):
def wrapper(*args, **kwargs):
thr = Thread(target = f, args = args, kwargs = kwargs)
thr.start()
return wrapper |
from __future__ import unicode_literals
from django.apps import AppConfig
class SequencerConfig(AppConfig):
name = 'sequencer'
|
import os
import sys
import datetime
from glob import iglob
from skimage import io
import cv2
import tensorflow as tf
import numpy as np
import utils as ut
import training as tr
class VAE2predict:
def __init__(self, use_sampling=False):
self.use_sampling = use_sampling
self._build_model()
def... |
from django import template
register = template.Library()
from urlparse import urlparse
def domain_only(full_url):
parsed = urlparse(full_url)
return parsed.netloc.lstrip("www.")
register.filter('domain_only', domain_only) |
print('spam = 40')
spam = 40
print('eggs = 2')
eggs = 2
print('spam + eggs')
a = spam + eggs
print(a)
# Variable naming convention
# small then capital or sparated by _
# varA
|
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz>
#
# 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... |
from django.apps import AppConfig
class MagiclinkConfig(AppConfig):
name = 'magiclink'
|
from flask import Flask
import os
app = Flask(__name__)
healthy = True
@app.route('/')
def hello():
global healthy
if healthy:
return f"Hello from {os.environ['HOST']}!\n"
else:
return "Unhealthy", 503
@app.route('/healthy')
def healthy():
global healthy
healthy = True
retur... |
'''
Integration tests for states.
'''
import unittest as ut
import numpy as np
import dynamite_test_runner as dtr
from dynamite.states import State
class RandomSeed(dtr.DynamiteTestCase):
def test_generation(self):
'''
Make sure that different processors get the same random seed.
'''
... |
import requests
import os
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
def send_to_slack(msg: str) -> None:
URL = os.getenv("SLACK_WEBHOOK")
headers = {"content-type": "application/json"}
payload = {
"attachments": [
{
"fallback": "Plain-t... |
from flask import abort, request
from . import app
from .helpers import render_error_template
import logging
# Catch all route for everything not matched elsewhere
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path): # pragma: no cover
abort(404, "Not Found")
@app.errorhandler... |
'''
Created on Jun 21, 2016
@author: MarcoXZh
'''
import sys, re
import xml.etree.ElementTree as ET
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from PIL import Image
from ImageComparison import calcSSIM
... |
#!/usr/bin/env python3
# Xilinx CoolRunner II XC2C64A characteristics
bits_of_address = 7
bits_of_data = 274
bytes_of_data = (bits_of_data + 7) // 8
bits_in_program_row = bits_of_address + bits_of_data
address_sequence = (0x00, 0x40, 0x60, 0x20, 0x30, 0x70, 0x50, 0x10, 0x18, 0x58, 0x78, 0x38, 0x28, 0x68, 0x48, 0x08, ... |
# Copyright 2020 reinforced_scinet (https://github.com/hendrikpn/reinforced_scinet)
#
# 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.... |
#!/usr/bin/env python
import os
import sys
from chromedriver_py import binary_path
print(
"""This command will fail if you have not run the setup.py script AND "source environment/env.sh" first.\n\n\nIt is installing a headless chrome web browser driver to allow making an image out of the big demo script session... |
import unittest
from users import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestUser: TestUser class that helps in creating test cases
'''
# Items up here .......
def setUp(self):
'''
... |
import random
import time
import os
import discord
import triggers
import data
import cmd
import tools
################################################################################
lurker_data = dict()
lurker_data['emoji'] = '👀'
lurker_data['min_chance'] = 1
lurker_data['max_chance'] = 10
data.NewGuildEnvAdd('l... |
from enum import auto
from mstrio.utils.enum_helper import AutoName
class RefreshPolicy(AutoName):
ADD = auto()
DELETE = auto()
UPDATE = auto()
UPSERT = auto()
REPLACE = auto()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import unicode_literals, division, absolute_import, print_function
# to work around tk_chooseDirectory not properly returning unicode paths on Windows
# need to use a dialog that can be hacked up to actually... |
from django.apps import AppConfig
class EsgConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'esg'
|
from .base import * # noqa: F403,F401
DEBUG = True
INSTALLED_APPS += [ # noqa ignore=F405
'debug_toolbar',
]
MIDDLEWARE += [ # noqa ignore=F405
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ALLOWED_HOSTS = [
'0.0.0.0',
'127.0.0.1',
'art-backend.herokuapp.com'
]
INTERNAL_IPS = [
'0... |
# Version 3.1; Erik Husby; Polar Geospatial Center, University of Minnesota; 2019
from __future__ import division
import math
import os
import sys
import traceback
from warnings import warn
import numpy as np
from osgeo import gdal_array, gdalconst
from osgeo import gdal, ogr, osr
gdal.UseExceptions()
class Rast... |
import random
print('====================== \033[35mBEM-VINDO AO JOGO DA ADIVINHAÇÃO\033[m ======================')
print('Tente adivinhar o número entre 0 e 10 que eu estou pensando')
computador = random.randint(0, 10)
palpites = 0
acertou = False
while not acertou:
jogador = int(input('Qual é a sua tentativa? '))... |
# -*- coding: utf-8 -*-
# Imports
import json
import discord
import random
import datetime
import asyncio
client = discord.Client()
# Readiness Indicator
@client.event
async def on_ready():
print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
# Remind... |
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from markdown import markdown
register = template.Library()
@register.filter("markdown")
@stringfilter
def markdown_filter(value):
return mark_safe(markdown(value))
@regi... |
"""
This file is part of Advent of Code 2019.
Coded by: Samuel Michaels (samuel.michaels@protonmail.com)
11 December 2019
NO COPYRIGHT
This work is dedicated to the public domain. All rights have been
waived worldwide under copyright law, including all related and
neighboring rights, to the extent allowed by law.
Y... |
# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Resource, Api
from controller.TestSuit import TestSuit
from model.TestSuit import db as TestSuitDB
app = Flask(__name__)
api = Api(app)
api.add_resource(TestSuit, '/testsuit')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.sqlit... |
# Compact version
# ---------------
rule = (('0'*8 + bin(30)[2:])[-8:])[::-1]
cells = list('0'*40 + '1' + '0'*40)
for epoch in range(40):
print(''.join(cells).replace("0"," ").replace("1","█"))
cells = [cells[0]] + [rule[eval('0b' + cells[i-1]+cells[i]+cells[i+1])]
for i in range(1,len... |
import io
import os
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson
class GoogleVisionApi:
def __init__(self):
# Instantiates a client
self.client = vision.ImageAnnotatorClient()
self.requestsCache = {}
def request(self, imagePath):... |
from os import getenv, \
path
class Config(object):
API_KEY = getenv('API_KEY')
DEBUG = getenv('DEBUG', False)
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///' + path.dirname(__file__) + '/app/app.db').replace('mysql2:', 'mysql:')
SQLALCHEMY_ECHO = getenv('SQLALCHEMY_ECHO', ... |
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='main', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset', default='mag', choices=['mag', 'amazon'])
parser.add_argument('--num_motif', default=50, type=int)
parser.add_argument('--eta', default=2.0, t... |
from infi.pyutils.lazy import cached_method
from ..inquiry import InquiryException
from logging import getLogger
logger = getLogger(__name__)
class InfiniBoxVolumeMixin(object):
@cached_method
def _is_volume_mapped(self):
"""In race condition between a rescan and volume unmap operation, the device may... |
import discord
from discord.ext import commands
import random, string
from asyncio import sleep
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ascii(self, ctx, amount: int=1):
await ctx.message.delete()
for i in range(amount):
text=''
for i in... |
import requests
import lib.RModule as rmodule
import lib.RAudiostream as raudiostream
import lib.RAtmosphere as ratmosphere
import lib.RMonitoring as rmonitoring
class Project:
project_id = None
switchboards = []
neopixels = []
audiostream = None
monitoring = None
def __init__(self, projec... |
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble, svm,datasets
import brica1
# Randomforest Component Definition
class RandomForestClassifierComponent(brica1.Component):
def __init__(self, n_in):
super(RandomForestClassifierComponent, self).__init__()
... |
""" Parent class to inception models """
import tensorflow as tf
from . import TFModel
from .layers import conv_block
class Inception(TFModel):
""" The base class for all inception models
**Configuration**
body : dict
layout : str
a sequence of blocks in the network:
- ... |
# Generated by Django 3.0.4 on 2020-03-20 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('places', '0024_submittedplace'),
]
operations = [
migrations.RemoveField(
model_name='submittedplace',
name='website... |
"""Tests for claim_line model and the associated functions."""
from claims_to_quality.analyzer.models import claim_line
def test_str_method():
"""Test that claim lines are represented in a readable format."""
line = claim_line.ClaimLine(
{'clm_line_hcpcs_cd': 'code', 'mdfr_cds': ['GQ'], 'clm_pos_code'... |
#!/usr/bin/env python3
"""
Script to preprocess OCR output for Tesseract
Usage:
python3 preprocess.py /path/to/input/dir \
/path/to/output/dir
"""
from glob import glob
import os
import shutil
import sys
import cv2
import numpy as np
def preprocess(img):
"""Takes a given image and retu... |
from .davis import vis
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
# Copyright (C) 2019 Northwestern University.
#
# Invenio App RDM is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio Records Permissions API."""
from elasticsearch_dsl.query... |
#! python3
# aoc_13.py
# Advent of code:
# https://adventofcode.com/2021/day/13
# https://adventofcode.com/2021/day/13#part2
#
def part_one(input) -> int:
nmap =[]
ymap = []
coords = []
with open(input, 'r') as inp:
lines = inp.readlines()
for line in lines:
line.strip()
... |
# Copyright (C) 2018 Shriram Bhat
#
# 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,... |
"""Implements the Projection extension.
https://github.com/stac-extensions/projection
"""
from typing import Any, Dict, Generic, List, Optional, Set, TypeVar, cast
import pystac
from pystac.extensions.hooks import ExtensionHooks
from pystac.extensions.base import (
ExtensionManagementMixin,
PropertiesExtensi... |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def home_view(request, *args, **kwargs):
# return HttpResponse("<h1>Hello World</h1>")
return render(request,"home.html", {})
|
import re
import utils as u
with open(__file__ + ".input.txt", "r+") as file:
input_str = file.read()
regex = re.compile(r"(?P<from>\d+)-(?P<to>\d+)\s(?P<letter>\w):\s(?P<password>\w+)")
def is_valid_password(input_str):
nb_from, nb_to, letter, password = regex.search(input_str).groups()
return int(nb_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# libfv.py────────────────────────────────────────────────────────────────┐
# │ │
# │ A Python library module that supports read/modification/write of .otf │
# │ and .ttf font version str... |
import sys
def test_python_path():
paths = sys.path
workspace = '/workspaces/bestbot'
assert workspace in paths
|
def foo(x = []):
return x.append("x")
def bar(x = []):
return len(x)
foo()
bar()
class Owner(object):
@classmethod
def cm(cls, arg):
return cls
@classmethod
def cm2(cls, arg):
return arg
#Normal method
def m(self):
a = self.cm(0)
return a.cm2(1)
|
import hqm
import socket
class HQMBot():
def __init__(self, host, port, team, name):
self.team = team
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.session = hqm.HQMClientSession(name, 55)
self.syncing = True... |
import os
import random
check = """<input type="checkbox" id="{}" name="chord" value="{}">
<label for="{}"> {}</label><br>\n"""
def s(note):
t = note.lower()
return t[0] + "_" + t[2:5]
to_print = ""
for note in os.listdir("./Chords"):
to_print += check.format(note[:-4], note, s(note), note[... |
import unittest
from app import db
from app.crypto.pw_hashing import global_salt_hash, indiv_salt_hash
from app.data_access.db_model.user import User
from app.data_access.user_controller import create_user, user_exists, delete_user, activate_user, \
store_pdf_and_transfer_ticket, find_user, check_idnr, check_dob
f... |
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from wrappr_backend.detection.api import urlpatterns as api_urls
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api-auth/'... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUI_try.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
from flask import jsonify, request, Response
from jsonschema import RefResolutionError
from sqlalchemy.orm import Session
from flexget.api import APIResource, api
from flexget.api.app import NotFoundError
from flexget.config_schema import resolve_ref, schema_paths
schema_api = api.namespace('schema', description='Con... |
"""
Compare two integers given as strings.
Example
For a = "12" and b = "13", the output should be
compareIntegers(a, b) = "less";
For a = "875" and b = "799", the output should be
compareIntegers(a, b) = "greater";
For a = "1000" and b = "1000", the output should be
compareIntegers(a, b) = "equal".
"""
def compare... |
# This file is part of the faebryk project
# SPDX-License-Identifier: MIT
import faebryk.library.core
import faebryk.library.kicad
import faebryk.library.library
import faebryk.library.traits
|
from datetime import datetime
from .api import ApiObject
class Trigger(ApiObject):
"""
https://www.xibbaz.com/documentation/3.4/manual/api/reference/trigger/object
"""
DEFAULT_SELECTS = ('Items', 'Functions', 'Dependencies', 'DiscoveryRule', 'LastEvent', 'Tags')
RELATIONS = ('hosts', 'groups')
... |
################################################################### #
# Basic plot for two-strain SIR model:
# Bifurcation diagram for one parameter
####################################################################
import sys
import numpy as np
import pylab as plt
from matplotlib.font_manager impo... |
import tweepy , tkinter, datetime, os, sys, random, time, pytz
from keys import *
from tweepy import TweepError
#Create oauth handler for tokens setting
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(key,secret)
api = tweepy.API(auth)
random_lyrics = 'Lyrics.txt'
t... |
from mycroft import MycroftSkill, intent_file_handler
class Prepararrefeicoes(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('prepararrefeicoes.intent')
def handle_prepararrefeicoes(self, message):
self.speak_dialog('prepararrefeicoes')
def create_sk... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: ibc/core/commitment/v1/commitment.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _refl... |
import operator
from typing import Any, Callable, List, Optional, Type, Union
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.decl_api import DeclarativeMeta
from sqlalchemy.orm.relationships import RelationshipProperty
from sqlalchemy.sql impor... |
'''
*File: domain_restriction.py
*Author: Nicholas Mattei (nicholas.mattei@nicta.com.au)
*Date: March 18, 2014
*
* Copyright (c) 2014, Nicholas Mattei and NICTA
* All rights reserved.
*
* Developed by: Nicholas Mattei
* NICTA
* http://www.nickmattei.net
* ... |
import tensorflow as tf
from storage import run_dir
from train import train
from model import model
from predict import predict
model = model()
train(model)
|
import os
import re
import codecs
from setuptools import setup, find_packages
current_path = os.path.abspath(os.path.dirname(__file__))
def read_file(*parts):
with codecs.open(os.path.join(current_path, *parts), 'r', 'utf8') as reader:
return reader.read()
def get_requirements(*parts):
with codecs.... |
##!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import math
import random
from hashlib import sha256
from pathlib import Path
from typing import Optional, Tuple, Union
import aiohttp
import fsspec
from fsspec.core import url_to_fs
########################################################################... |
from subprocess import call
import glob
dirnames = glob.glob("samples/*")
for d in dirnames:
images = glob.glob(d+"/*.png")
print("")
print("### "+d)
images.sort()
for image in images:
print("")
print("")
|
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.label import Label
# from kivy.garden
from kivy.uix.textinput import TextInput
import time
from Code.Scripts.predi... |
from typing import Any, AsyncGenerator
from dependency_injector.wiring import Provide, inject
from graphql import GraphQLResolveInfo
from containers import SDContainer
from models import OnPathway
from .subscription_type import subscription
@subscription.source("onPathwayUpdated")
@inject
async def on_pathway_updated... |
import sys
import tableauserverclient as TSC
rob = TSC.RequestOptions.Builder()
ro = rob.file("==", "MyFile").project("==", "Default")._sort("foo", "desc")._pagesize(50)._build()
print ro.filters |
# -*- coding: utf-8 -*-
# Detect tissue regions in a whole slide image.
#############################################################################
# Copyright Vlad Popovici <popovici@bioxlab.org>
#
# Licensed under the MIT License. See LICENSE file in root folder.
#################################################... |
numbers = []
posbetter = []
poslower = []
for c in range(0, 5):
numbers.append(float(input('Type a number: ')))
for pos, value in enumerate(numbers):
if value == max(numbers):
posbetter.append(pos)
if value == min(numbers):
poslower.append(pos)
print(f'The better number typed was {max(number... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import statsmodels.formula.api as smf
import statsmodels.api as sm
import pickle
#df = pd.read_pickle('sav.txt')
X = pd.read_pickl... |
from numbers import Number
import numpy as np
import sympy
from collections.abc import Mapping
from sympy import Symbol
from sympy.core.relational import Relational
from toy.unit import DIMENSIONLESS, parse_unit_msg
from toy.utils import as_dict, is_numeric
from toy.core.value import Value
base_model = None
class ... |
import cv2
import time
import csv
import os
import picamera
import picamera.array
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(36, GPIO.OUT)
GPIO.setup(33, GPIO.OUT)
GPIO.setup(10, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
def gpio_fun():
val = ""
if GPIO.input(36) == 1:
## ... |
# -*- coding: utf-8 -*-
"""Module with utility functions to call the GPT translation API"""
import json
import requests
# ==============================================================================
# CONSTANT DEFINITION
# ==============================================================================
API_EXCEPTIO... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 14:33:34 2019
"""
import os
def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs,... |
import urequests
class InfluxDBClient():
def __init__(self,url, token, org, bucket):
self.url=url
self.token=token
self.org=org
self.params={"bucket":bucket ,"org":org}
self.headers={"Authorization":"Token {}".format(token)}
self.conveq=lambda x: ["{}={}".format(k,v)... |
'''
Calculate astrometric motion of star over given time frame using JPL Horizons ephermerides
and SIMBAD proper motion and parallax
'''
from __future__ import print_function
import matplotlib
matplotlib.use('agg')
import csv
import jplephem
import de421
from jplephem.spk import SPK
kernel = SPK.open('de430.bsp')
imp... |
# -*- coding: utf-8 -*-
"""
@Project : activationFunction
@Author : Xu-Shan Zhao
@Filename: activationFunction202003121138.py
@IDE : PyCharm
@Time1 : 2020-03-12 11:38:55
@Time2 : 2020/3/12 11:38
@Month1 : 3月
@Month2 : 三月
"""
import torch
import matplotlib.pyplot as plt
x_data = torch.arange(-6, 6, 0.01)
y_... |
with open('day1_input.txt') as file:
input = file.read()
# Part 1
sum = 0
for i in range(len(input) - 1):
if input[i] == input[i + 1]:
sum += int(input[i])
if input[len(input) - 1] == input[0]:
sum += int(input[0])
print(sum)
# Part 2
sum = 0
forward = len(input) / 2
for i in range(forward):
... |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from datadog_checks.dev.testing import requires_py3
from ..utils import get_check
pytestmark = [
requires_py3,
pytest.mark.openmetrics,
pytest.mark.openmetrics_transformers,
... |
# CSV to JSON
# 1. run the following from the root of project directory: `cd data/achievements; python3 achievements-gen.py`
# 2. commit and push changes
# 3. website will automatically update
import csv, json
with open("./achievements.csv", encoding='utf-8', mode='r') as fin:
with open("./achievements.json", mode=... |
"""
CODE ADAPTED FROM: https://github.com/sjblim/rmsn_nips_2018
Treatment Effects with RNNs:
Common routines to use across all training scripts
"""
import logging
import numpy as np
import pandas as pd
import tensorflow as tf
import treatments.RMSN.configs
import treatments.RMSN.libs.net_helpers as helpers
from t... |
#####################################
# ColumnRelationships.py
#####################################
# Description:
# * Map all relationships between columns.
from abc import abstractmethod, ABC
from enum import Enum
from itertools import combinations, product
import numpy as np
from pandas import DataFrame
from sorte... |
from collections import OrderedDict
from elasticsearch.exceptions import RequestError
from elasticsearch_dsl import Search
import settings
from core.cursor import decode_cursor, get_next_cursor
from core.exceptions import (APIPaginationError, APIQueryParamsError,
APISearchError)
from core... |
from setuptools import setup, find_packages
import sys
import platform
# python version check
python_min_version = (3, 6, 2)
python_min_version_str = '.'.join(map(str, python_min_version))
if sys.version_info < python_min_version:
print(
f"You are using Python {platform.python_version()}. At least Python >... |
import pytest
from spacy.lang.ja import Japanese
def test_ja_morphologizer_factory():
pytest.importorskip("sudachipy")
nlp = Japanese()
morphologizer = nlp.add_pipe("morphologizer")
assert morphologizer.cfg["extend"] is True
|
from base import CodeTyper, SNIPPETS_ROOT, COMMAND
import panel as pn
pn.extension(sizing_mode="stretch_width")
CodeTyper(
title="# Cross Filtering with hvPlot, Holoviews and PANEL",
value=SNIPPETS_ROOT/"holoviews_linked_brushing_app.py",
command="$ pip install panel holoviews hvplot shapely\n" + ... |
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <coherence@beebits.net>
'''
Transcoder classes to be used in combination with a Coherence MediaServer,
using GStreamer pipelines for the actually work and feeding the output into
a... |
import posix_ipc
import utils
params = utils.read_params()
try:
posix_ipc.unlink_message_queue(params["MESSAGE_QUEUE_NAME"])
s = "message queue %s removed" % params["MESSAGE_QUEUE_NAME"]
print (s)
except:
print ("queue doesn't need cleanup")
print ("\nAll clean!")
|
import keywords as kw
import pca_tsne as pt
import math
import re
import numpy as np
from collections import Counter
from sklearn.cluster import KMeans
def conventional_kmeans(data, tfidf, kmeans_size_keywords, k):
matrix = tfidf.fit_transform(data.setting_value)
fit = KMeans(n_clusters=k, random_state=20).... |
from yunionclient.common import base
class CdnDomain(base.ResourceBase):
pass
class CdnDomainManager(base.StandaloneManager):
resource_class = CdnDomain
keyword = 'cdn_domain'
keyword_plural = 'cdn_domains'
_columns = ["ID", "Name", "Status", "Cloudaccount_id", "External_id", "Cname", "Origins", "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.