text
string
size
int64
token_count
int64
import requests LANGUAGES_LIST = [ 'en-US', 'en-GB', 'en-AU', 'en-HK', 'en-NZ', 'en-SG', 'en-ZA', 'de-DE', 'ar-XA', 'ar-SA', 'bn-IN', 'bg-BG', 'ca-ES', 'cmn-CN', 'zh-HK', 'cmn-TW', 'cy-GB', 'cs-CZ', 'da-DK', 'de-CH', 'es-AR', 'es-CO', 'es-US', 'ga-IE', 'gu-IN', 'hr-HR', 'mr-IN', 'ms-MY', 'mt-MT', 'nl-N...
4,728
1,671
import tensorflow as tf import numpy as np from sklearn.datasets import fetch_california_housing housing = fetch_california_housing() m, n = housing.data.shape housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data] X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X") y = tf.constant(housing.targ...
1,365
537
# -*- coding: utf-8 -*- """ @author: Matthew Beauregard Smith (UT Austin) """ from common.peptide import Peptide from plotting.plot_pr_curve import plot_pr_curve from numpy import load from simulate.label_peptides import label_peptides TRUE_Y_FILE = 'C:/Users/Matthew/ICES/MarcotteLab/data/classification/c...
1,634
706
################# BEGIN AUTOMATICALLY GENERATED FIT PROFILE ################## ########################### DO NOT EDIT THIS FILE ############################ ####### EXPORTED PROFILE FROM SDK VERSION 20.33 AT 2017-05-17 22:36:12 ####### ########## PARSED 118 TYPES (1699 VALUES), 76 MESSAGES (950 FIELDS) ########## fro...
337,498
98,208
import requests from bs4 import BeautifulSoup def get_tickers(market=2): url = f"http://comp.fnguide.com/SVO2/common/lookup_data.asp?mkt_gb={market}&comp_gb=1" resp = requests.get(url) data = resp.json() codes = [] for comp in data: code = comp['cd'][-6:] codes.append(code) ret...
820
317
def set_font_from_style(xml, style): if "font" in style: xml.set("font-family", style["font"]) if "size" in style: xml.set("font-size", style["size"]) s = "" if "color" in style: s += "fill:{};".format(style["color"]) if style.get("bold", False): s += "font-weight: b...
1,882
610
from django.contrib import admin from django.utils.html import format_html from django.shortcuts import redirect from .models import * # Register your models here. admin.site.register(CategoryDes) class DestinationAdmin(admin.ModelAdmin): def edit(self, obj): return format_html('<a class="btn-primary" hr...
7,209
2,423
# Cookie clicker auto-clicker # Works for the classic version here: https://orteil.dashnet.org/experiments/cookie/ import pyautogui def locate_cookie(): """ Returns the locations of the Big Cookie Does not return until the cookie is found """ loc = None while loc == None: loc = pyaut...
1,428
462
# -*- coding: utf-8 -*- # # Copyright 2015, Ekevoo.com. # # 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 l...
1,485
460
# ------------------------------------------------------------------------------ # This module renders and writes HTML pages to disk. # ------------------------------------------------------------------------------ import re import os from . import site from . import events from . import filters from . import utils f...
3,305
920
"""Main module.""" from copy import deepcopy from datetime import datetime from difflib import Differ from io import StringIO from typing import IO, Iterable, AnyStr from datadiff.tools import assert_equal from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap class MVYamlVersionNotFoundException...
5,646
1,640
import unittest from unittest import TestCase class Test(TestCase): def test_02_vectorized_imports(self): print("test02") import py_vollib.black.implied_volatility import py_vollib.black_scholes.implied_volatility import py_vollib.black_scholes_merton.implied_volatility imp...
1,889
627
from elasticsearch_dsl import Q, TermsFacet from flask import has_request_context from flask_login import current_user from invenio_search import RecordsSearch from invenio_search.api import DefaultFilter from .permissions import admin_permission_factory def deposits_filter(): """Filter list of deposits. ...
1,137
338
import numpy as np from determine_source_type import determine_source_type #function to figure out how many sources are in cutout #and set up necessary tractor input for those sources def find_nconfsources(raval, decval, gal_type, fluxval, x1, y1, cutout_width, subimage_wcs, df): #setup to collect sources ...
1,586
561
from distutils.core import setup DISTNAME='earthdragon' FULLVERSION='0.1' setup( name=DISTNAME, version=FULLVERSION, packages=['earthdragon'], install_requires = [ 'asttools', 'toolz', 'typeguard', 'more_itertools', ] )
274
100
import os a = os.system("g++ sumatoria.cpp -o sumatoria.x") a = os.system("./sumatoria.x")
92
41
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('consultaticket', views.consultaticket, name='consultaticket'), path('consultadecredito', views.consultadecredito, name='consultadecredito'), path('mostrarticket', views.mostrarticket, name='most...
334
107
import streamlit as st from db_functions import * def order_history(): st.title("Order History") sorts = ['None','category','time'] sql_userids = f"select pk_user_id from Users" user_ids = query_db(sql_userids)['pk_user_id'].tolist() user_id = st.selectbox("Please select your userid", user_ids) ...
1,973
645
import discord from discord.ext import commands import random class EightBall(commands.Cog): def __init__(self, client): self.client = client @commands.command(aliases=["8ball", "8-ball"], description="Have the magic 8-ball answer your most burning questions.") async def eight_ball(self, ctx): ...
1,415
357
# code golf challenge # https://code.golf/fizz-buzz#python # wren 20210607 # Print the numbers from 1 to 100 inclusive, each on their own line. # If, however, the number is a multiple of three then print Fizz instead, # and if the number is a multiple of five then print Buzz. # For numbers which are multiples of both ...
1,441
451
from setuptools import setup setup( name='install-raspberry', version='', packages=[''], url='https://github.com/grro/httpstreamproxy', license='Apache Software License', author='grro', author_email='gregor.roth@web.de', description='test' )
275
90
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import unittest import inspect from py_privatekonomi.utilities import common from py_privatekonomi.tests.test_base import TestBase from py_privatekonomi.tes...
2,701
844
import sys import os import json import gzip def jsonReader(inputJsonFilePath,pos): flag = False with gzip.open(inputJsonFilePath, 'r') as jsonContent: for rowNumber, line in enumerate(jsonContent, start=1): try: #此处加上flag的目的在于,当程序挂掉时候,可以根据域名从指定位置开始,不必重头开始跑 ...
918
281
#!/usr/bin/python import pycurl from io import BytesIO def checkOpen(): isOpen = False buffer = BytesIO() c = pycurl.Curl() c.setopt(c.URL, 'https://www.winer.org/Site/Roof.php') c.setopt(c.WRITEDATA, buffer) c.perform() c.close() body = buffer.getvalue() if body.fi...
393
160
# Imports from egg.resources.console import get, clearConsole from egg.resources.constants import * from egg.resources.modules import install, upgrade, Repo from egg.resources.help import help from egg.resources.auth import login, register """ FUNCTION eggConsole(condition: bool = True) Display the Egg Console Curren...
2,238
601
#!/usr/bin/env python # -*- coding: utf-8 -*- from PIL import Image, ImageDraw, ImageFont, ImageFilter import random im = Image.open('F:/workspace/python/data/backpink.jpg') im2 = im.filter(ImageFilter.BLUR) im2.save('F:/workspace/python/data/backpink_blur.png', 'png') im2.save('F:/workspace/python/data/backpink_blu...
1,204
558
# Generated by Django 2.1.9 on 2019-07-16 10:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("terra_layer", "0027_auto_20190715_1631")] operations = [ migrations.AddField( model_name="layergroup", name="exclusive", ...
382
138
from aws_cdk import Stack from aws_lambda_handler_cookbook.service_stack.configuration.configuration_construct import ConfigurationStore from aws_lambda_handler_cookbook.service_stack.constants import CONFIGURATION_NAME, ENVIRONMENT, SERVICE_NAME from constructs import Construct class CookBookConfigurationStack(Stack...
605
174
from django.contrib.auth.models import AbstractUser from ..notifications.utils import TemplateKey, TemplateMailManager class User(AbstractUser): def notify(self, **kwargs): kwargs["user"] = self enabled = self.get_enabled_notifications() key = getattr( TemplateKey, f"{kwargs['...
653
175
import collections import math import numpy as np def mapeadora(value): valor_mapeado = int((value-1500)/800*255) return valor_mapeado def escribir_pixel(img, columna, linea, canal, valor): '''funcion encargada de escribir pixel por pixel la imagen''' if linea >= img.height: return if can...
2,689
1,066
""" Pong game by Michael Mishkanian """ import turtle wn = turtle.Screen() wn.title("Pong by Michael Mishkanian") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # Paddle A paddle_a = turtle.Turtle() paddle_a.speed(0) paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, ...
3,653
1,457
number = int(input()) counter = 1 while counter <= number: print(counter) counter = 2 * counter + 1
108
36
from pathlib import Path from string_finder.constants import TEST_DATA_DIR from typing import List import pytest @pytest.fixture def caw_xml_paths() -> List[Path]: xml_dir = TEST_DATA_DIR / "xmls" assert xml_dir.is_dir() _paths = [x for x in xml_dir.iterdir()] assert len(_paths) == 4, f"expected 4 xm...
385
139
import csv from utils import get_valid_colum_indices class Cleaner(): def clean(file, clean_columns, remove): print ("Cleaning {}".format(file)) print ("For columns {}".format(clean_columns)) new_file = file[0:-7] + "clean.csv" with open(file, 'r') as raw_file: reader...
1,432
365
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-06 15:41 from __future__ import unicode_literals from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), (...
516
179
############################################################################### # Univesidade Federal de Pernambuco -- UFPE (http://www.ufpe.br) # Centro de Informatica -- CIn (http://www.cin.ufpe.br) # Bacharelado em Sistemas de Informacao # IF968 -- Programacao 1 # # Autor: Bernardo Gomes de Melo # ...
6,203
2,042
"""DB utilities. """ __author__ = 'Md Jahidul Hamid <jahidulhamid@yahoo.com>' __copyright__ = 'Copyright © Md Jahidul Hamid <https://github.com/neurobin/>' __license__ = '[BSD](http://www.opensource.org/licenses/bsd-license.php)' __version__ = '0.1.0' import collections import re import asyncio import nest_asyncio #...
37,129
10,592
""" gistsig Derek Merck Winter 2019 Sign and verify Python packages using public gists. """ import logging from pprint import pformat from datetime import datetime import click from . import get_gist, update_gist from . import get_pkg_info, get_pkg_gist @click.group() @click.option('--verbose', '-v', is_flag=True, ...
4,197
1,494
""" Copyright 2018 Riley Murray 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 d...
2,397
768
product_type = input("Enter the product type(coffee, water, coke, snacks): ") quantity = int(input("Enter the quantity: ")) def price(): if product_type == "coffee": total_price = quantity * 1.50 return total_price elif product_type == "water": total_price = quantity * 1.00 retu...
557
176
import torch import torch.nn as nn import torch.nn.functional as F import math import time import random import matlab.engine def gaussian(spread): #spread controls the size of the array linspace = torch.linspace(-2.5,2.5,spread) # gaussian = e^((-x)^2/2) when standard dev is 1 and height is 1 ...
4,984
2,050
# Copyright (c) 2020 SBA- MIT License import getpass import argparse import sys import cmd import shlex from urllib.error import HTTPError from cryptography.hazmat.primitives import serialization from client.clientlib import login, Connection from client import smartcard def parse2(arg): args = list(shlex.sp...
4,438
1,356
import tweepy import datetime import os # get keys from evironment variable "TWITTER_KEYS" TWITTER_API_KEYS = (os.environ.get("TWITTER_KEYS").split(",")) consumer_key,consumer_secret,access_token_key,access_token_secret = TWITTER_API_KEYS # Authenticate to Twitter auth = tweepy.OAuthHandler(consumer_key, consumer_se...
1,867
680
# https://medium.com/datadriveninvestor/deep-autoencoder-using-keras-b77cd3e8be95 from keras.datasets import mnist from keras.layers import Input, Dense from keras.models import Model import numpy as np import pandas as pd import matplotlib.pyplot as plt (X_train, _), (X_test, _) = mnist.load_data() X_train = X_trai...
2,113
852
class AlertBoxPage: def __init__(self, driver): self.driver = driver self.title_css = "h1" self.title_text = "Alert Box Examples" self.explanation_css = "div.explanation > p" self.explanation_text = ( "There are three main JavaScript methods " "which ...
5,569
1,665
import random import typing from datetime import datetime, timedelta from random import randint from google.cloud import ndb from data_service.config.stocks import currency_symbols from data_service.store.mixins import AmountMixin from data_service.views.memberships import MembershipsView from data_service.store.member...
11,339
3,449
from padmini import filters as f from padmini import operations as op from padmini.constants import Tag as T from padmini.sounds import s from padmini.prakriya import Term, Prakriya from padmini.term_views import TermView from padmini.prakarana.utils import eka_ac def _double(rule: str, p: Prakriya, dhatu: Term, i: i...
3,893
1,706
import unittest def warn_the_sheep(queue): return 'Pls go away and stop eating my sheep' if queue[::-1].index('wolf') == 0 else f"Oi! Sheep number {queue[::-1].index('wolf')}! You are about to be eaten by a wolf!" class TestSolution(unittest.TestCase): def test_1(self): self.assertEquals(warn_the_she...
1,152
434
import logging logger = logging.getLogger("dbnd-scheduler") try: from dbnd_airflow.scheduler.scheduler_dags_provider import get_dags # airflow will only scan files containing the text DAG or airflow. This comment performs this function dags = get_dags() if dags: for dag in dags: ...
449
137
import datetime from django.contrib.contenttypes.models import ContentType from django.db.models import FieldDoesNotExist from django.db.models.base import ObjectDoesNotExist def create_model_type(instance, model_type, key, slugify, **kwargs): """ Create object by model type :param instance: Model manager...
4,268
1,210
from dtest import Tester import os, sys, time from ccmlib.cluster import Cluster from tools import require, since from jmxutils import make_mbean, JolokiaAgent class TestDeletion(Tester): def gc_test(self): """ Test that tombstone are fully purge after gc_grace """ cluster = self.cluster ...
2,588
869
# Generated by Django 3.0.2 on 2020-02-09 18:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('comments', '0003_auto_20200208_0812'), ] operations = [ migrations.AlterModelOptions( name='comment', options={'ordering': [...
355
132
# # mostly copied from # http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/socket/multicast.html # import socket import struct import sys import time message = 'data worth repeating' multicast_group = ('226.1.1.1', 4321) # Create the datagram socket sock = socket.socket(socket.AF_INET, socket.SOCK_D...
768
273
import numpy as np from chol_factor import chol_factor from triangular import triangular # TEST: Cholesky factorization (LL') # Symmetric positive definite matrix A = np.matrix('5 1.2 0.3 -0.6;' '1.2 6 -0.4 0.9;' '0.3 -0.4 8 1.7;' '-0.6 0.9 1.7 10'); print('A = ...
852
364
"""Build the tkinter gui root""" import math from PyQt5.QtWidgets import *#(QWidget, QToolTip, QDesktopWidget, QPushButton, QApplication) from PyQt5.QtGui import QFont from PyQt5.QtCore import QCoreApplication, QObject, QRunnable, QThread, QThreadPool, pyqtSignal, pyqtSlot from PyQt5.QtGui import QIntValidator, QDoubl...
11,245
3,776
# -*- coding: utf-8 -*- from __future__ import print_function, division from qsrlib_qsrs.qsr_dyadic_abstractclass import QSR_Dyadic_1t_Abstractclass import math class QSR_Cardinal_Direction(QSR_Dyadic_1t_Abstractclass): """Cardinal direction relations. Values of the abstract properties * **_unique_id*...
2,346
806
# NBA Stats Clustering # Copyright Matthew Strong, 2019 # gaussian mixture models with em algorithm import numpy as np from scipy import stats from clustering.Cluster import NBACluster # nba gmm class # gmm from scratch as well, more explained below class NBAGMM(NBACluster): def fit(self): self.method = '...
4,291
1,362
import torch from torch.utils.data import DataLoader import matplotlib.pyplot as plt import sys sys.path.append("./ML") import Definitions.models as models from Definitions.dataset import Data def main(imgpath="Data", noise_dim=100, vec_shape=100, root="./ModelWeights/"): netG = models.Generator...
1,484
627
from datetime import datetime, timedelta import pygame from pygame.mixer import Sound from screens.base_screen import BaseScreen from ui import colours from ui.widgets.background import LcarsBackgroundImage from ui.widgets.gifimage import LcarsGifImage from ui.widgets.lcars_widgets import LcarsButton from ui.widgets....
4,965
1,589
import swarm_tasks.utils.robot
31
12
# -*- coding: utf-8 -*- """ Created on Sun Mar 7 17:11:12 2021 @author: User SUMMATION OF PRIMES The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. 21min19s to find. """ from datetime import datetime as date def nextPrime(n, primes): is...
2,178
862
import numpy as np import pytest from l5kit.geometry import transform_points from l5kit.rasterization.render_context import RenderContext @pytest.mark.parametrize("set_origin_to_bottom", [False, True]) def test_transform_points_to_raster(set_origin_to_bottom: bool) -> None: image_shape_px = np.asarray((200, 200)...
1,124
451
import vim import functools import dbus class FcitxComm(): def __init__(self): bus = dbus.SessionBus() obj = bus.get_object('org.fcitx.Fcitx5', '/controller') self.fcitx = dbus.Interface(obj, dbus_interface='org.fcitx.Fcitx.Controller1') def status(self): return self.fcitx.State() == 2 def act...
1,528
608
import requests def post(): url1 = "http://165.227.106.113/post.php" headers1 = { 'Host': '165.227.106.113' } data = { 'username': 'admin', 'password': '71urlkufpsdnlkadsf' } r1 = requests.post(url=url1, data=data, headers=headers1) print(r1.text) post()
311
140
# -*- coding: utf-8 -*- from avioclient.send_data import SendControls from avioclient import config def send_data(): data_sender = SendControls(config.SERVER_URL) connections_done = 0 while True: connections_done += 1 print( data_sender.get_data( config.GET_ENDP...
828
233
c = float(input('Digite a temperatura em Ceusius: ')) f = (9*c + 160)/5 print(f'A temperatura de {c:.1f}ºC corresponde a {f:.1f}ºF')
132
66
# not yet finished for _ in range(int(input())):print(len(list(set(input().replace("-", "")))))
95
33
import os import unittest import despyfitsutils.fitsutils as utils TESTDIR = os.path.dirname(__file__) class MefTest(unittest.TestCase): """Tests for a MEF object. """ def setUp(self): inputs = [os.path.join(TESTDIR, 'data/input.fits.fz')] output = os.path.join(TESTDIR, 'data/output.fit...
906
309
#!/usr/bin/env python # -*- coding: utf-8 -*- from time import gmtime, strftime from gluon.custom_import import track_changes track_changes(True) from gluon import current from pydal import * import sys reload(sys) sys.setdefaultencoding('utf-8') if request.global_settings.web2py_version < "2.14.1": raise HTTP...
4,047
1,112
import os if (os.name == 'nt' or os.name == 'dos'): try: from win32com.shell import shell import pythoncom except Exception, e: print 'WARNING: Received exception ' + `e` + ' in doing import.' print 'WARNING: Unable to import win32com.shell.shell, pythoncom.' ...
2,066
618
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-28 08:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pigeon', '0002_auto_20160327_0723'), ] operations = [ migrations.AlterField(...
1,207
373
""" Group - SwimTime - Swim your way to success """ import ads1x15 import network import time import math import machine from umqtt.simple import MQTTClient import micropython from micropython import const from machine import Pin """ Define constant values """ run = False lapnr = 3 #default lap number temp = ...
10,839
5,011
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud 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, p...
40,102
11,697
""" Feeder for batch production""" from __future__ import absolute_import import ctypes from ddls.base import check_call, LIB, c_str, c_array from ddls.feeder.batch_iterator import BatchIterator class Feeder(object): """ The feeder """ def __init__(self): """ create a new Tensor instance "...
983
289
import pytest from mvlearn.example.example import example_function def test_example_function(): """ Test that example function returns correct value. """ assert example_function() == "param" assert example_function("hello") == "hello"
258
68
from flask_restful import Resource import requests from api.common.utils import file_response ENCODING = 'utf-8' SCHEMA_URL = 'http://127.0.0.1:8422' STORE_URL = 'http://127.0.0.1:8423' class FhirDatatypes(Resource): @staticmethod def get(): """Returns CSV list of available database schemas.""" ...
2,155
651
#!/bin/env python #coding: utf-8 import pymongo print [x for x in range(2)] con = pymongo.MongoClient("localhost", 27017) db = con.mars collection = db.users data = collection.find_one({"username":"hyr"}) print data data['age'] = 225 print collection.update({"_idd":data['_id']}, data) print collection.find_one({"u...
427
168
import numpy as np def CalcRhoAndBetaVectors(bid_vec, UB_bid, num_edges, index_Imps, adverPerImp, firstPrice): ## I will assume I want to evaluate the full vector. rhoBetaMat=np.zeros((num_edges,2)) for edge_num,impType in enumerate(index_Imps): rhoBetaMat[edge_num,:]=RhoBetaValue(bid_vec[edge_num]...
742
291
""" Greedy Module Solution for Utils control """ # Libraries from typing import List from functools import reduce # Modules from src.utils.math import ( list_negative, invert_positions, evaluate_fo ) # Constants COMPARE_VALUE = 99999999 def worst_solution(distance_matrix: List[List[float]]) -> List[in...
3,208
973
import math import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from models.modules.model.vgg16 import Vgg16 import os vgg = Vgg16() vgg.load_state_dict(torch.load(os.path.join(os.path.abspath('.'), 'models/modules/model/', 'vgg16.weight'))) params = list(vgg.named_parameters()) encodi...
5,649
2,062
import time import random import json import requests
56
15
""" Codemonk link: https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/equal-array-84cf6c5f/ You are given an array A of size N. Find the minimum non negative number X such that there exists an index j that when you can replace Aj by Aj+...
1,642
531
from itertools import chain phi = 1.61803398875 class PenroseModel: def __init__(self, start_state): self.tiles = start_state self.history = [] def split(self): self.history.append(list(self.tiles)) self.tiles = list(chain(*[tile.split() for tile in self.tiles])) def desp...
1,331
549
import unittest from unittest.mock import call, patch, Mock, MagicMock from qilib.configuration_helper import InstrumentAdapterFactory class TestKeysightE8267DInstrumentAdapter(unittest.TestCase): def test_read_filter_out_val_mapping(self): with patch('qilib.configuration_helper.adapters.keysight_e8267d...
1,465
426
import json import pprint import random from terra_sdk.core import AccAddress, Coins from terra_sdk.core.auth import StdFee from terra_sdk.core.broadcast import BlockTxBroadcastResult from scripts.deploy import owner, lt from terra_sdk.core.wasm import MsgExecuteContract def mint(contract_address: str): mint_ms...
1,364
479
from core.exceptions import BaseProjectException class InvalidUrlError(BaseProjectException): """Exception raised when invalid url is passed.""" pass class MissingPrimaryKeyError(BaseProjectException): """Exception raised when primary key is missing.""" pass
281
69
import math from nexinfosys.model_services import State materials = { "Aluminium", "Antimony", "Arsenic", "Baryte", "Beryllium", "Borates", "Cadmium", "Cerium", "Chromium", "Cobalt", "Copper", "Diatomite", "Dysprosium", "Europium", "Fluorspar", "Gadolini...
1,507
651
# defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in which the argument is called inner function can access the outer local functions like in this case "func" def inner1(): print("Hello, this is before function execution") # calling the actual function now ins...
2,933
867
#!/usr/bin/env python """ Info: This script performs topic modeling on the clean tweets by Donald Trump. The number of topics is estimated by computing coherence values for different number of topics, and an LDA model is constructed with the number of topics with the highest coherence value. Visualizations of the topic...
24,654
6,848
""" William DUong """ import os.path as osp import os import errno from .build import DATASET_REGISTRY from .base_dataset import Datum, DatasetBase,EEGDatum from scipy.io import loadmat import numpy as np from collections import defaultdict class ProcessDataBase(DatasetBase): dataset_dir = None file_name =...
15,086
4,908
import argparse import json from ursina import load_texture, Ursina, Entity, color, camera, Quad, mouse, time, window, invoke, WindowPanel, \ Text, InputField, Space, scene, Button, Draggable, Tooltip, Scrollable from pywolf3d.games.wolf3d import WALL_DEFS, WallDef, OBJECT_DEFS Z_GRID = 0 Z_OBJECT = 2 Z_WALL = 3...
9,321
2,994
"""Functions for loading and data management for EEG-FOOOF.""" from os.path import join as pjoin import numpy as np from fooof import FOOOFGroup from fooof.analysis import get_band_peak_fg from settings import BANDS, YNG_INDS, OLD_INDS, N_LOADS, N_SUBJS, N_TIMES ####################################################...
3,404
1,203
import sys import cv2 import numpy as np img1 = cv2.imread('source1.jpg',0) img2 = cv2.imread('source2.jpg',0) ret, thresh = cv2.threshold(img1, 127, 255,0) ret, thresh2 = cv2.threshold(img2, 127, 255,0) contours,hierarchy,a = cv2.findContours(thresh,2,1) cnt1 = contours[0] contours,hierarchy,a = cv2.findContours(th...
413
206
import os from __main__ import vtk, qt, ctk, slicer import EditorLib from EditorLib.EditOptions import HelpButton from EditorLib.EditOptions import EditOptions from EditorLib import EditUtil from EditorLib import LabelEffect class InteractiveConnectedComponentsUsingParzenPDFsOptions(EditorLib.LabelEffectOptions): "...
25,556
7,664
from django.urls import path from category.views import List,Detail,Create,Delete,Update,Search,All urlpatterns = [ path('all',All.as_view()), path('list/<int:pk>',List.as_view()), path('search/<str:pk>',Search.as_view()), path('detail/<int:pk>',Detail.as_view()), path('create', Create.as_view()), ...
415
149
# ------------------------------------------ # Description: This python script will update AWS Thing Shadow for a Device/Thing # ------------------------------------------ # Import package import paho.mqtt.client as mqtt import ssl, time, sys # ======================================================= # Set Following V...
3,488
1,259
import time from lightpi.hardware import strip, string1, string2 DELAY_SEC = 0.3 # Test the RGB Strip strip.red() time.sleep(DELAY_SEC) strip.green() time.sleep(DELAY_SEC) strip.blue() time.sleep(DELAY_SEC) strip.off() # Test the LED Strings string1.on() time.sleep(DELAY_SEC) string1.off() time.sleep(DELAY_SEC) st...
680
231
#!/usr/bin/env python # -*- coding: utf-8 -*- # # wind_direction.py # # Copyright 2020 <Simone Severini> # # This program 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 2 of the Licen...
3,141
1,235
# Copyright 2017 Cloudbase Solutions SRL # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
3,875
1,123
#!/usr/bin/python import rospy import rosbag import time def callback(topic, msg): global current_time try: header = getattr(msg, "header") if header.stamp < current_time: print "received old message, skipping '%s'" % topic return except AttributeError: pass global result result[topic] = msg def w...
2,572
1,136