content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""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... | python |
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", {})
| python |
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_... | python |
#!/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... | python |
import sys
def test_python_path():
paths = sys.path
workspace = '/workspaces/bestbot'
assert workspace in paths
| python |
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)
| python |
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... | python |
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[... | python |
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... | python |
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/'... | python |
# -*- 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):
... | python |
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... | python |
"""
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... | python |
# 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
| python |
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')
... | python |
################################################################### #
# 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... | python |
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... | python |
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... | python |
# -*- 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... | python |
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... | python |
'''
*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
* ... | python |
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)
| python |
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.... | python |
##!/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
########################################################################... | python |
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("")
| python |
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... | python |
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... | python |
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 | python |
# -*- 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.
#################################################... | python |
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... | python |
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... | python |
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 ... | python |
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:
## ... | python |
# -*- coding: utf-8 -*-
"""Module with utility functions to call the GPT translation API"""
import json
import requests
# ==============================================================================
# CONSTANT DEFINITION
# ==============================================================================
API_EXCEPTIO... | python |
# -*- 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,... | python |
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)... | python |
'''
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... | python |
# -*- 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_... | python |
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):
... | python |
# (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,
... | python |
# 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=... | python |
"""
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... | python |
#####################################
# 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... | python |
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... | python |
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 >... | 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
| python |
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" + ... | python |
# -*- 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... | python |
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!")
| python |
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).... | python |
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", "... | python |
import simplejson
import urllib2
import feedparser
import logging
from datetime import timedelta
from django.http import Http404, HttpResponse
from django.template import loader, TemplateDoesNotExist, RequestContext
from django.shortcuts import render_to_response
from django.core.cache import cache
from molly.utils.v... | python |
from rpy import r
import os.path
# find out where the temp directory is
tempdir = r.tempdir()
# write its name into a file
f = open('tempdir','w')
f.write(tempdir)
f.close()
# put something there..
r.postscript(os.path.join(tempdir,"foo.ps"))
r.plot(1,1)
r.dev_off()
| python |
import os
from math import ceil
from fastapi import FastAPI, Form
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
from app.aws_s3 import S3
from app.mongo import MongoDB
API = FastAPI(
title='DocDB DS API',
version="1.0.0",
docs_url='/',
)
API.db = MongoDB()
... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
""" Analyse des efforts statiques dans un treillis
(assemblage de barres et de pivots)
Le problème est traité en 2D (dans un plan)
Pierre Haessig — Mars 2013
"""
from __future__ import division, print_function, unicode_literals
import numpy as np
import matplotlib.pyplot as p... | python |
import logging
from datetime import datetime
from enum import Enum
import ntplib
from scapy.layers.ntp import NTPHeader
from ntp_raw import RawNTP
_PCK_1_YEAR = 1995
_PCK_2_YEAR = 2000
class CP3Mode(Enum):
"""
In CP3 an NTP package can be marked as a type 1, or 2 package or as nothing. This class represent... | python |
from helusers.oidc import ApiTokenAuthentication as HelApiTokenAuth
from django.conf import settings
class ApiTokenAuthentication(HelApiTokenAuth):
def __init__(self, *args, **kwargs):
super(ApiTokenAuthentication, self).__init__(*args, **kwargs)
def authenticate(self, request):
jwt_value = se... | python |
from inquire_sql_backend.semantics.embeddings.vector_models import VECTOR_EMBEDDERS
def vector_embed_sentence(sent, tokenized=False, model="default"):
embed_func = VECTOR_EMBEDDERS[model]
return embed_func(sent, batch=False, tokenized=tokenized)
def vector_embed_sentence_batch(sent, tokenized=False, model="... | python |
import torch.nn as nn
import torch
from .conv2d_repeat import Conv2dRepeat
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __ini... | python |
from flask import Blueprint
socket_client = Blueprint('socket_client', __name__)
from . import events | python |
from rest_framework import serializers
from puzzle.models import Offer
class OfferSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(
source="author.user.username", read_only=True)
class Meta:
model = Offer
fields = ["id", "author_name", "created",
... | python |
"""Collection of PBM-based click simulators."""
from typing import Optional
from typing import Tuple
import torch as _torch
from pytorchltr.utils import mask_padded_values as _mask_padded_values
_SIM_RETURN_TYPE = Tuple[_torch.LongTensor, _torch.FloatTensor]
def simulate_pbm(rankings: _torch.LongTensor, ys: _torch... | python |
import ila
import riscv_um
def genVlg():
rm = riscv_um.riscvModel()
rm.loadUnprivNxtFromDir('unpriv_asts')
rm.model.generateVerilog('RISC-V-VLG.v')
if __name__ == '__main__':
genVlg()
| python |
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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 requi... | python |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#import libraries
import string
import ast
from itertools import islice
import csv
from nltk.tokenize import RegexpTokenizer
def createTsvFile_Search1(listUrl_Movies3):
#create tsv file in 'tsv_correct' directory wehere we have preprocessed the tsv file (just creat... | python |
from django import template
from classytags.core import Options
from classytags.helpers import AsTag
from classytags.arguments import Argument
from ..models import CallToActionRepository
class GetCallToAction(AsTag):
name = 'get_call_to_action'
options = Options(
Argument('code', required=True),
... | python |
import json
def get_list():
with open("config.json", "r") as f_obj:
f_json = json.load(f_obj)
return f_json
def get_lang(item):
return get_list()[item]
def set_lang(item, lang):
with open("list_lang.json", "r") as f_obj:
list_lang = json.load(f_obj)
if not (lang in list_lan... | python |
import os
import os.path as osp
import copy
import yaml
import numpy as np
from ast import literal_eval
from utils.collections import AttrDict
__C = AttrDict()
cfg = __C
# ---------------------------------------------------------------------------- #
# MISC options
# -------------------------------------------------... | python |
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
def rules_clojure_dependencies():
jvm_maven_import_external(
name = "org_clojure",
artifact = "org.clojure:clojure:1.10.1",
artifact_sha256 = "d4f6f991fd9ed2a59e7ea4779010b3b069a2b905f3463136c42201106b4ad21a",
... | python |
from django.apps import AppConfig
class ApacheKafkaConfig(AppConfig):
name = 'apache_kafka'
| python |
import click
from neobox.cmd.list import list_
from neobox.cmd.clear_cache import clear_cache
from neobox.cmd.login import login
from neobox.cmd.logout import logout
from neobox.cmd.search import search
from neobox.cmd.play import play
from neobox.cmd.pause import pause
from neobox.cmd.stop import stop
@click.group(... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : yasin
# @time : 18-12-28 下午9:28
# @File : config.py
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("novel-update-monitor-account")
bindIp = '0.0.0.0'
bindPort = 12126
token = 'VqmB965wOEBrPLNoMkHCfIOpxF0WWFM6'
g... | python |
"""User profile model"""
# Django
from django.db import models
# Utilities
from mydea.utils.models import MyDeaModel
class Profile(MyDeaModel):
"""Profile model.
A profile holds a user's data"""
# user
user = models.OneToOneField('users.User', on_delete=models.CASCADE)
def __str__(self):
... | python |
#----------------------------------------------------------------------
# Deep learning for classification for contrast CT;
# Transfer learning using Google Inception V3;
#-------------------------------------------------------------------------------------------
import os
import numpy as np
import pandas as pd
import... | python |
import os
from time import time
import krgram.tl.protocol
import krgram.tl.protocol.auth
from krgram.client.crypto import TLEncryptor
from krgram.client.errors import SecurityError
from krgram.mtproto.connection import MTProtoAbridgedConnection
from krgram.mtproto.dcs import DataCenters
from krgram.mtproto.errors impo... | python |
import sqlalchemy
from pydantic import BaseModel
from .model import Base
class Category(BaseModel):
""""""
name: str
color: str
class CategoryTable(Base):
__tablename__ = "category"
name = sqlalchemy.Column(sqlalchemy.String, primary_key=True)
color = sqlalchemy.Column(sqlalchemy.String)
... | python |
#!/usr/bin/env python3
import sys
import gzip
import ast
import json
class Dumper:
def __init__(self, path):
self.path = path
self.open_file = {}
def close_all(self):
#close previous file(s)
for name in self.open_file:
self.open_file[name].close()
self.open... | python |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 th... | python |
import os
class Config:
title = 'VocView'
# URL root of this web application. This gets set in the before_first_request function.
url_root = None
# Subdirectory of base URL. Example, the '/corveg' part of 'vocabs.tern.org.au/corveg'
SUB_URL = ''
# Path of the application's directory.
AP... | python |
list1=['car','ara','cabc']
c=0
for i in list1:
a=list1
if(
c=c+1
print(c)
| python |
import pyeccodes.accessors as _
def load(h):
h.add(_.Unsigned('n2', 2))
h.add(_.Unsigned('n3', 2))
h.add(_.Unsigned('nd', 3))
h.alias('numberOfDiamonds', 'nd')
h.alias('Nj', 'nd')
h.add(_.Unsigned('Ni', 3))
h.add(_.Codeflag('numberingOrderOfDiamonds', 1, "grib1/grid.192.78.3.9.table"))
... | python |
import struct
from io import BytesIO
p8 = lambda x:struct.pack("<B", x)
u8 = lambda x:struct.unpack("<B", x)[0]
p16 = lambda x:struct.pack("<H", x)
u16 = lambda x:struct.unpack("<H", x)[0]
p32 = lambda x:struct.pack("<I", x)
u32 = lambda x:struct.unpack("<I", x)[0]
p64 = lambda x:struct.pack("<Q", x)
u64 = lambda x... | python |
from sacnn.core.we import get_word_to_vector
word_to_vector, WORD_DIMENSION = get_word_to_vector()
| python |
from __future__ import annotations
import collections
import copy
import json
import logging
import operator
import os
from typing import Any, Dict, List, Optional, Tuple
import joblib
from poker_ai import utils
from poker_ai.poker.card import Card
from poker_ai.poker.engine import PokerEngine
from poker_ai.games.sh... | python |
import json
class SwearWords(object):
def __init__(self):
self.data = json.load(open('data.json'))
def filter_words(self,text,symbol="*"):
text = text.split()
print(text)
for i in range(len(text)):
if text[i] in self.data['word']:
text[i] = symbol * ... | python |
import RPi.GPIO as GPIO
led_pin = 29
button_pin = 40
buzzer_pin = 31
GPIO.setmode(GPIO.BOARD)
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(buzzer_pin, GPIO.OUT)
while True:
if GPIO.input(button_pin) == GPIO.HIGH:
GPIO.output(led_pin, True)
GPIO.output(buz... | python |
"""
MIT License
Copyright (c) 2021 isaa-ctaylor
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, ... | python |
"""
The Importer feature sets up the ability to work with cuneiform text(s)
one-on-one, whether it is the Code of Hammurabi, a collection of texts such as
ARM01, or whatever your research desires.
This cdli_corpus module is for working with text files having already been read
by file_importer. The file_lines required ... | python |
# Copyright (c) 2016-2018, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
import asyncio
import pylru
from aiorpcx import run_in_thread
from electrumx.lib.hash import hash_to_hex_str
class ChainState(object):
'''Used a... | python |
import sys
from secret import FLAG, REGISTER, TAPS
assert FLAG.startswith('flag')
assert len(REGISTER) == 16
assert len(TAPS) == 5
class LFSR:
def __init__(self, register, taps):
self.register = register
self.taps = taps
def next(self):
new = 0
ret = self.register[0]
... | python |
# -*- coding: utf-8 -*-
# External import
import pytest
from numpy import array, pi
from os.path import join
from multiprocessing import cpu_count
# Pyleecan import
from pyleecan.Classes.ImportGenVectLin import ImportGenVectLin
from pyleecan.Classes.ImportMatrixVal import ImportMatrixVal
from pyleecan.Classes.Simu1 i... | python |
#!/usr/bin/env python3
"""SERVICE YET TO BE IMPLEMENTED. THIS FILE IS JUST A PLACEHOLDER."""
print("Sorry! This service has not yet been implemented\n(will you be the one to take care of it?\n --- RIGHT NOW THIS FILE IS JUST AN HANDY PLACEHOLDER ---")
| python |
# Copyright 2020, The TensorFlow Federated 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 o... | python |
# Generated by Django 2.1.3 on 2018-11-09 05:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('restapi', '0010_annotatedrecording_recitation_mode'),
]
operations = [
migrations.CreateModel(
name='TajweedInformation',
... | python |
# MIT License
#
# Copyright (c) 2021 TrigonDev
#
# 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, pu... | python |
import torch
from numpy import histogram, random
from scipy.stats import skewnorm
from torch import Tensor, from_numpy
from torch.nn.functional import softmax
class WGAN:
def __init__(self) -> None:
super().__init__()
def discriminator_loss(self, real_scores: Tensor, fake_scores: Tensor) -> Tensor:
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-01 13:53
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_auto_20170801_1819'),
]
operations = [... | python |
import pytest
from pathlib import Path
from coolcmp.cmp.source_code import *
from unit_tests.utils import run_test_codegen
tests = []
with open('unit_tests/compiled_files.txt') as f:
for line in f:
tests.append(Path(line.rstrip()).resolve())
@pytest.mark.complete
@pytest.mark.parametrize('file', tests, i... | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
from common.log import logger
from common.globalvar import db_related_to_project_dic
from unittesttestcase import MyUnittestTestCase
__all__ = ['DBUnittestTestCase']
class DBUnittestTestCase(MyUnittestTestCase):
def test_select_one_record(self)... | python |
"""
Simple HTTP Server with GET that waits for given seconds.
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import time
ENCODING = 'utf-8'
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
"""Simple multi-threaded HTTP Server."""
pass
class MyR... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.