id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
1879061
""" Utility dialogs for starcheat itself """ import os import sys import hashlib import webbrowser from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QFileDialog from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QProgressDialog from PyQt5 import QtCore from urllib.request import urlope...
StarcoderdataPython
12835713
<filename>interface/__init__.py from PySimpleGUI import PySimpleGUI as sg from sys import exit sg.theme('DarkGray14') # sg.theme_previewer() def layout(): layout = [ [sg.Text('Recomeçar:'), sg.Radio('Sim', 'recomecar', key='rSim', default=True, enable_events=True), sg.Radio('Não', 'recom...
StarcoderdataPython
4908581
#### REST FRAMEWORK ##### from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response ##### SERIALIZERS ##### from users.serializers import UserSerializer from users.serializers import BuyerProfileSerializer from users.serializers import Seller...
StarcoderdataPython
3364128
#!/usr/bin/env python3 def test(i): print("coroutine starts") while True: value = yield i i += value b = test(5) # just created; main fn in control; next(b) # now corutine in control # execute print statement and then # yield val `i` to main fn # yield c...
StarcoderdataPython
5022187
<reponame>raymondyeh07/chirality_nets """Test for chiral batch_norm1d layer.""" import unittest import torch import torch.nn.functional as F from tests.test_chiral_base import TestChiralBase from chiral_layers.chiral_batch_norm1d import ChiralBatchNorm1d class TestChiralBatchNorm1d(TestChiralBase): """Implements ...
StarcoderdataPython
44180
''' Etapas do logger ''' import logging # Instancia do objeto getLogger() logger = logging.getLogger() # Definindo o level do logger logger.setLevel(logging.DEBUG) # formatador do log formatter = logging.Formatter( 'Data/Hora: %(asctime)s | level: %(levelname)s | file: %(filename)s | mensagem: %(message)s', ...
StarcoderdataPython
246872
<filename>odac_idp/__init__.py import os from flask import Flask # setup configs env = os.environ.get('FLASK_ENV', 'development') app = Flask(__name__) app.config['DEBUG'] = (env != 'production') import odac_idp.views
StarcoderdataPython
11242923
import random, lists, logging # Security levels levels = { '1' : {'length': 0, 'complex': False}, '2' : {'length': 8, 'complex': False}, '3' : {'length': 8, 'complex': True} } # Gen passwords class password: def gen_passwd(wordCount=3, separator='-', words=lists.words): passwd = '' fo...
StarcoderdataPython
3569185
<gh_stars>0 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Mail: """ ShareNews class by default need the next instances: -mail = senders_mail -mail_to = who will receive the mail -password = <PASSWORD> -smtp_server = The...
StarcoderdataPython
198375
<filename>examples/flask/htdocs/main.py """ # Python Flask # http://flask.pocoo.org/docs/1.0/quickstart/#quickstart # Code from # @see Rapid Flask [Video], PacktLib # --- # @see Learning Flask Framework # @see ... # run app server with "python routes.py" # open browser at "localhost:5000" # open browser at "localho...
StarcoderdataPython
1871560
import pytest # noqa from django.test import TestCase import ensure_footer import json import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings.dev') django.setup() import common.models # noqa class VariableValuesTest(TestCase): def test_migrate_html(self): """ Tests...
StarcoderdataPython
1918542
<filename>pkg/005_custom_application/cstraining.web/cstraining/web/__init__.py #!/usr/bin/env powerscript # -*- mode: python; coding: utf-8 -*- import datetime from cdb import auth from cdb import util from cdb.objects.core import Object from cdb.platform.gui import PythonColumnProvider class Ticket(Object): _...
StarcoderdataPython
9602176
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import os, threading, json, time, socket from http.server import BaseHTTPRequestHan...
StarcoderdataPython
3363355
<reponame>chubbymaggie/LibRadar import libradar import json import glob apks = glob.glob("/Volumes/banana/apks/*") i = -1 total = 10 while i < total: try: i += 1 print "Progress %d" % i apk_path = apks[i] lrd = libradar.LibRadar(apk_path) res = lrd.compare() print(...
StarcoderdataPython
172723
<reponame>FaceandControl/genshin-parser from src import api from src.resources.main import Main from src.resources.character import Сharacter from src.resources.characters import Сharacters # # Declarations of app routes in type of rest web-architecture # # routes api.add_resource(Main, '/', strict_slashes=False) api....
StarcoderdataPython
11258635
<reponame>redsnic/WGA-LP # --- default imports --- import os import multiprocessing # --- load utils --- from WGALP.utils.commandLauncher import run_sp from WGALP.utils.genericUtils import * from WGALP.step import Step description = """ Run merqury to asses WGA quality """ input_description = """ the original fastq f...
StarcoderdataPython
291615
<gh_stars>1-10 """ Definition of urls for djangoapp. """ from datetime import datetime from django.conf.urls import url import django.contrib.auth.views from django.urls import path,include from . import views # Uncomment the next lines to enable the admin: # from django.conf.urls import include # from django.contrib ...
StarcoderdataPython
9639230
from rest_framework import viewsets from .models import Category from .serializers import CategorySerializer # Create your views here. class CategoryViewSet(viewsets.ModelViewSet): # Operations to be performed queryset = Category.objects.all().order_by('-created_at') # Class responsible for serializing t...
StarcoderdataPython
1842934
<filename>ori/slow_down_cdf.py import numpy as np import pickle import matplotlib.pyplot as plt import environment import parameters import pg_network import other_agents from cycler import cycler def discount(x, gamma): """ Given vector x, computes a vector y such that y[i] = x[i] + gamma * x[i+1] + gam...
StarcoderdataPython
1656975
import json with open('data/classes.json') as f: data = json.load(f) list_of_classes = [] for book_class in data['classes']: name = book_class['Name'] list_of_classes.append(name) def get_key_ability(PC_class): if PC_class in list_of_classes: index = list_of_classes.index(PC_class) ...
StarcoderdataPython
11256140
"""Module for handling commands which may be attached to BinarySensor class.""" import logging from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional if TYPE_CHECKING: from xknx.xknx import XKNX logger = logging.getLogger("xknx.log") class ActionBase: """Base Class for handling commands.""" ...
StarcoderdataPython
6594342
""" Module for categorical kernels Please refer to the following papers and theses for more details: - <NAME>, <NAME>. "An investigation into new kernels for categorical variables." Master's thesis, Universitat Politècnica de Catalunya, 2013. """ import numpy as np from kernelmethods.base import BaseKerne...
StarcoderdataPython
5145715
from docker import DockerClient from aavm.utils.progress_bar import ProgressBar from cpk.types import Machine, DockerImageName ALL_STATUSES = [ "created", "restarting", "running", "removing", "paused", "exited", "dead" ] STOPPED_STATUSES = [ "created", "exited", "dead" ] UNSTABLE_STATUSES = [ "restarting"...
StarcoderdataPython
1947887
<reponame>giaccone/the_kirchhoff_bot from util.decorators import restricted @restricted def execute(update, context): """ 'kick' kick user out from the group :param update: bot update :param context: CallbackContext :return: None """ user_id = update.message.reply_to_message.from_user.id ...
StarcoderdataPython
4960838
<reponame>ADACS-Australia/SS2021B-DBrown from tempfile import TemporaryDirectory from unittest import mock from finorch.config.config import _ClientConfigManager, WrapperConfigManager from finorch.utils.cd import cd def test_client_get_port(): with TemporaryDirectory() as tmp: with mock.patch('appdirs.us...
StarcoderdataPython
3513007
''' Created on 29 de out de 2017 @author: gustavosaquetta ''' from src.model.cadastro.pessoa import Pessoa from src.controller.lib.ssqt import SSQt class PessoaController: def formata_cpf_cnpj(self, view): if view: #SSQt().pdb() if hasattr(view, 'tipo_1'): if view.tipo_1.isChecked(): view.cpf.s...
StarcoderdataPython
9629636
import unittest from logging import Logger, getLogger from numpy import ndarray, array, arange, allclose from freq_used.logging_utils import set_logging_basic_config from optmlstat.linalg.basic_operators.matrix_multiplication_operator import MatrixMultiplicationOperator logger: Logger = getLogger() class TestMatri...
StarcoderdataPython
1653713
<reponame>GameDungeon/DocStats<gh_stars>1-10 """Generate Callgraphs for documentation.""" import os import subprocess from typing import List from docutils.nodes import Node from docutils.parsers.rst import Directive from sphinx.ext.graphviz import graphviz from sphinx.util.typing import OptionSpec callgraph_count =...
StarcoderdataPython
1631923
<reponame>OLC-LOC-Bioinformatics/AzureStorage<filename>tests/test_azure_7_delete.py from azure_storage.methods import client_prep, delete_container, delete_file, delete_folder, extract_account_name from azure_storage.azure_delete import AzureDelete, cli, container_delete, file_delete, \ folder_delete from unitte...
StarcoderdataPython
3216999
<reponame>ridi/django-shard-library from django.db import connections, transaction from shard.exceptions import QueryExecuteFailureException from shard.services.execute_query_service import ExecuteQueryService from shard.utils.database import get_master_databases_by_shard_group class QueryExecutor: """ 해당 클래...
StarcoderdataPython
3224347
import traceback import training_code_metric_processing import os import subprocess import argparse import json import sys from timeit import default_timer as timer import running_utils def main(): # read the parameter argument parsing parser = argparse.ArgumentParser( description='Modify the training...
StarcoderdataPython
11270325
<reponame>GeorgeDavis-TM/aws-cloudwatch-logs-retention<filename>handler.py from distutils.command.config import config import os import json import boto3 def getLogGroupsDict(logsClient): describeLogGroupsResponse = logsClient.describe_log_groups() logGroupsDict = {} for logGroup in describeLogGroupsRes...
StarcoderdataPython
11305592
""" Settings for slackbot """ import os TRUE_VALUES = ('true', 'yes', 1) def is_true(arg): if str(arg).lower() in TRUE_VALUES: return True return False ##### SLACK ##### # SlackのAPIトークン # https://my.slack.com/services/new/bot で生成 API_TOKEN = os.environ['SLACK_API_TOKEN'] # 読み込むpluginのリスト PLUGINS =...
StarcoderdataPython
11315138
<reponame>zyedidia/boolector #!/usr/bin/env python import sys, getopt QUEENS_MODE = 0 QUEENS_MODE_NP1 = 1 QUEENS_MODE_GTN = 2 NO_THREE_IN_LINE_MODE = 3 NO_THREE_IN_LINE_MODE_2NP1 = 4 NO_THREE_IN_LINE_MODE_GT2N = 5 SEQ_ADDER_ENCODING = 0 PAR_ADDER_ENCODING = 1 ITE_ENCODING = 2 LOOKUP_ENCODING = 3 SHIFTER_ENCODING = 4 ...
StarcoderdataPython
8189313
from registry.extensions import db from registry.list.models import DonationCenter, Medals from registry.utils import capitalize, format_postal_code class Batch(db.Model): __tablename__ = "batches" id = db.Column(db.Integer, primary_key=True) donation_center_id = db.Column(db.ForeignKey(DonationCenter.id)...
StarcoderdataPython
5117973
<reponame>TadeasPilar/KiKit from pcbnewTransition import pcbnew, isV6 import tempfile import re from dataclasses import dataclass, field from kikit.drc_ui import ReportLevel import os @dataclass class Violation: type: str description: str rule: str severity: str objects: list = field(default_factor...
StarcoderdataPython
3255703
<reponame>danoliveiradev/PythonExercicios<filename>ex096.py def area(l, c): a = l * c print(f'A área de um terreno {l}x{c} é de {a:.1f}m².') # Programa Principal print(f'{"CONTROLE DE TERRENO":^30}') print('-'*30) largura = float(input('Largura (m): ')) comprimento = float(input('Comprimento (m): ')) area(lar...
StarcoderdataPython
9765413
from django.conf.urls import patterns, url from views import * urlpatterns = patterns('', url(r'factura/lista_ventas/$', ListaVentas.as_view(), name = 'lista_ventas'), url(r'^factura/venta$', 'apps.factura.views.facturaCrear', name="factura_venta"), url(r'^factura/buscar_cliente$', 'apps.factura.views....
StarcoderdataPython
1622625
<reponame>vinthedark/snet-marketplace-service import json import uuid from enum import Enum import web3 from eth_account.messages import defunct_hash_message from web3 import Web3 from common.logger import get_logger logger = get_logger(__name__) class ContractType(Enum): REGISTRY = "REGISTRY" MPE = "MPE" ...
StarcoderdataPython
1826219
# flake8: noqa E501 from dataclasses import dataclass, field from enum import Enum from typing import Any, Dict, List, Literal, Optional, Union import pytest from robotcode.language_server.common.lsp_types import ( CallHierarchyClientCapabilities, ClientCapabilities, ClientCapabilitiesWindow, ClientCa...
StarcoderdataPython
1807692
from django.urls import path from .views import ( DashboardView, CandidateListView, CandidateCreateView, CandidateDeleteView, CandidateUpdateView, CandidateLikeView ) app_name = 'customer' urlpatterns = [ path('', DashboardView.as_view(), name='dashboard'), path('job/', CandidateListView.as_view(), name='...
StarcoderdataPython
3374582
<filename>files2.py #!/usr/bin/env python # coding: utf-8 """ Simple program to iterate thru all files, fetch 1st digit from the file size and plot the distribution of the different values as an animated graph. This version will trigger a repaint not with frame rate, as a game, but when a certain amount of files have...
StarcoderdataPython
12864934
<reponame>zenranda/proj5-map<filename>flask_map.py import flask from flask import render_template from flask import request from flask import url_for import json import logging ### # Globals ### app = flask.Flask(__name__) import CONFIG ### # Pages ### @app.route("/") @app.route("/index") @app.route("/map") def in...
StarcoderdataPython
3507162
from ReferenceManual import createReferenceManual from ReferenceManual import printReferenceManual import ColorPair_test_data as td if __name__ == '__main__': td.test_functionalities() print('Reference Manual') printReferenceManual(createReferenceManual()) print('Done :)')
StarcoderdataPython
388572
<reponame>shingarov/cle """ CLE is an extensible binary loader. Its main goal is to take an executable program and any libraries it depends on and produce an address space where that program is loaded and ready to run. The primary interface to CLE is the Loader class. """ __version__ = (8, 20, 1, 7) if bytes is str:...
StarcoderdataPython
8017080
''' Bet365 D_ Token Fetcher Author: @ElJaviLuki ''' import subprocess import re PATH = './deobfuscator365/' def fetch_D_token(bootjs_code: str): filename = PATH + 'd_fetcher.js' file = open(filename, "w") file.write( """try { const jsdom = require("jsdom"); ...
StarcoderdataPython
12828890
from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.db import models from django.utils import timezone class AdvancedUserManager(BaseUserManager): def create_user(self, email, username, password=<PASSWORD>, **extra_fields): if not email: ...
StarcoderdataPython
3229185
import os import duckdb import pandas as pd from dagster import Field, check, io_manager from dagster.seven.temp_dir import get_system_temp_directory from .parquet_io_manager import PartitionedParquetIOManager class DuckDBPartitionedParquetIOManager(PartitionedParquetIOManager): """Stores data in parquet files...
StarcoderdataPython
381440
<gh_stars>0 from data import * import numpy as np import matplotlib.pyplot as plt from sklearn.learning_curve import learning_curve from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline pipe_lr = Pipeline([ ('scl', StandardScaler(...
StarcoderdataPython
170567
import numpy as np class RolloutWorker: def __init__(self, env, policy, cfg, env_params, language_conditioned=False): self.env = env self.policy = policy self.cfg = cfg self.env_params = env_params self.language_conditioned = language_conditioned self.timestep_cou...
StarcoderdataPython
8063075
<reponame>atpaino/stocktradinganalysis<gh_stars>1-10 #Contains functions that compute a statistic for a single HistoricData item from time #offset+n through time offset. import scipy.stats as sts def variation_wrapper(hd, n=20, offset=0): """ Calculates the variation on the closing price of hd from offset:offs...
StarcoderdataPython
4826152
<filename>test/optimization/test_slsqp.py # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2...
StarcoderdataPython
4926745
<filename>qdef2d/defects/calc_Eform_corr.py import os import argparse import pandas as pd def calc(dir_def,xlfile): """ Evaluate corrected defect formation energy. dir_def (str): path to the defect directory containing the excel file xlfile (str): excel filename to read/save the dataframe fr...
StarcoderdataPython
5024110
<filename>delfin/drivers/ibm/storwize_svc/ssh_handler.py # Copyright 2020 The SODA Authors. # 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://...
StarcoderdataPython
3340234
<filename>SUAVE/SUAVE-2.5.0/regression/scripts/cnbeta/cnbeta.py # test_cnbeta.py # Created: Apr 2014 <NAME> # Modified: Feb 2017, <NAME> # Reference: Aircraft Dynamics: from Modeling to Simulation, by <NAME> import SUAVE import numpy as np from SUAVE.Core import Units from SUAVE.Methods.Flight_Dynamics.Static_Stabili...
StarcoderdataPython
6512322
<reponame>dliess/capnzero<filename>scripts/capnp_file.py import global_types import subprocess from common import * def create_capnp_file_content_str(data, file_we): the_id = subprocess.check_output(['capnp', 'id']).decode('utf-8').rstrip() outStr = """\ {}; using Cxx = import "/capnp/c++.capnp"; $Cxx.namesp...
StarcoderdataPython
1623022
<reponame>nukui-s/mlens """ML-ENSEMBLE :author: <NAME> :copyright: 2017-2018 :licence: MIT Blend Ensemble class. Fully integrable with Scikit-learn. """ from __future__ import division from .base import BaseEnsemble from ..index import BlendIndex, FullIndex class BlendEnsemble(BaseEnsemble): r"""Blend Ensemb...
StarcoderdataPython
3273655
from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app import crud, schemas from app.api import depends router = APIRouter() @router.get("/", response_model=List[schemas.CourseTimeslotInDB]) def get_list_of_timeslots( db: Session = Depends...
StarcoderdataPython
18091
# -*- coding: utf-8 -*- """ This module defines a connexion app object and configures the API endpoints based the swagger.yml configuration file. copyright: © 2019 by <NAME>. license: MIT, see LICENSE for more details. """ import connexion app = connexion.App(__name__, specification_dir="./") app.app.url_map.strict...
StarcoderdataPython
3450163
<filename>jobbing/models_remote/org.py # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from jobbing.models.base_model_ import Model from jobbing import util class Org(Model): def __init__(self, org_id:int = Non...
StarcoderdataPython
9677327
import time import os import torch import math import sys import matplotlib.pyplot as plt from torch.utils.tensorboard import SummaryWriter # import numpy as np from matplotlib.patches import Circle, Polygon, Ellipse from matplotlib.collections import PatchCollection def calc_linear_covariance(x): peds = {} ...
StarcoderdataPython
9712042
''' @author: <NAME> @version: 1.0 ======================= This script creates an oracle module for the training of the parser. ''' ''' ******* ********* ********* ******* imports ********* ******* ********* ********* ''' from collections import deque from classes import * ''' ******* ********* ********* ******* f...
StarcoderdataPython
1696788
<filename>Python/minimum-average-difference.py<gh_stars>1-10 # Time: O(n) # Space: O(1) # prefix sum class Solution(object): def minimumAverageDifference(self, nums): """ :type nums: List[int] :rtype: int """ total = sum(nums) mn, idx = float("inf"), -1 pref...
StarcoderdataPython
3586359
<filename>maskrcnn_benchmark/modeling/roi_heads/attribute_head/loss.py<gh_stars>10-100 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch.nn import functional as F from maskrcnn_benchmark.layers import smooth_l1_loss from maskrcnn_benchmark.modeling.box_coder import BoxCode...
StarcoderdataPython
6585187
# Copyright 2018 SpiderOak, 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 required by applicable law or agreed to in writi...
StarcoderdataPython
9766747
<gh_stars>0 # this file came from https://www.caktusgroup.com/blog/2013/06/26/media-root-and-django-tests/ # used to delete all the media files created after a test run import os import shutil from django.conf import settings from django.test.runner import DiscoverRunner class TempMediaMixin(object): """ Mix...
StarcoderdataPython
1756096
<filename>main/py-set-symmetric-difference-operation/py-set-symmetric-difference-operation.py<gh_stars>0 def input_set(): raw_input() # ignore n return set(map(int, raw_input().split())) print len(input_set() ^ input_set())
StarcoderdataPython
11315081
<reponame>kzborisov/Juliany-Pizza from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from juliany_pizza.menu.models import Category, Ingredient, Product, Stock UserModel = get_user_model() class TestCartViews(TestCase): def setUp(self): UserMo...
StarcoderdataPython
6542217
# coding=utf-8 """ The MIT License Copyright (c) 2013 <NAME> 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, mer...
StarcoderdataPython
9696609
<filename>test_f_strings.py import datetime import decimal import unittest from f_strings import f class TestFStrings(unittest.TestCase): def test_fred(self): name = 'Fred' age = 50 anniversary = datetime.date(1991, 10, 12) self.assertEqual( f('My name is {name}, my ag...
StarcoderdataPython
11384650
<reponame>styx-dev/pystyx import json from typing import Callable, Dict from munch import munchify # Adapted from this response in Stackoverflow # http://stackoverflow.com/a/19053800/1072990 def _to_camel_case(snake_str): components = snake_str.split("_") # We capitalize the first letter of each component exc...
StarcoderdataPython
4838062
<filename>neutron_taas/services/taas/drivers/linux/ovs_taas.py<gh_stars>10-100 # Copyright (C) 2015 Ericsson AB # Copyright (c) 2015 Gigamon # # 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 # ...
StarcoderdataPython
5096024
<reponame>MateusPsi/erp-Core-N400<filename>N400 ERP CORE_1.py #!/usr/bin/env python # coding: utf-8 # --- # title: ERP Core N400 preprocessing in MNE-Python # date: 2021-02-25 # image: # preview_only: true # tags: # - Python # - EEG # - Preprocessing # categories: # - Python # - EEG # - English # summary: "Replicat...
StarcoderdataPython
8157739
import os import re import time import numpy as np import pandas as pd import requests from bs4 import BeautifulSoup from nba_api.stats.endpoints import leaguestandings scatter_vals = ['Team', 'Average Age', 'Wins', 'Losses', 'Pythagorean Wins', 'Pythagorean Losses', 'Margin of Victory', 'Strength of...
StarcoderdataPython
4935570
import pextant.backend_app.events.event_definitions as event_definitions import socket import selectors import traceback from pextant.backend_app.app_component import AppComponent from pextant.backend_app.events.event_dispatcher import EventDispatcher from pextant.backend_app.client_server.client_data_stream_handler im...
StarcoderdataPython
4950531
<filename>Advanced/Exercises/Multi_Dimentional_Lists_Exercise_1/2_diagonal_difference.py # Write a program that finds the difference between the sums of the square matrix diagonals (absolute value). # On the first line, you will receive an integer N - the size of a square matrix. # The following N lines hold the valu...
StarcoderdataPython
319643
# example of a very simple Python script # you can run this from inside TextPad: http://www.atug.com/andypatterns/textpad_and_python.htm # you first need to install Python for Windows of course: http://www.python.org/ # for Python reference and help: http://safari.oreilly.com/JVXSL.asp # this imports useful Python ...
StarcoderdataPython
11360967
# -*- coding: utf-8 -*- """Raspa input plugin.""" import os from shutil import copyfile, copytree from aiida.orm import Dict, FolderData, List, RemoteData, SinglefileData from aiida.common import CalcInfo, CodeInfo, InputValidationError #from aiida.cmdline.utils import echo from aiida.engine import CalcJob from aiida....
StarcoderdataPython
6414970
<filename>probs/continuous/gamma.py<gh_stars>0 from dataclasses import dataclass from scipy.stats import gamma # type: ignore[import] from probs.continuous.rv import ContinuousRV @dataclass(eq=False) class Gamma(ContinuousRV): """ The gamma distribution is a two-parameter family of continuous probability ...
StarcoderdataPython
1800438
""" Simple example showing how to control a GPIO pin from the ULP coprocessor. The GPIO port is configured to be attached to the RTC module, and then set to OUTPUT mode. To avoid re-initializing the GPIO on every wakeup, a magic token gets set in memory. After every change of state, the ULP is put back to sleep again...
StarcoderdataPython
9727915
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('',views.password_reset,name='password_reset'), path('send_password_reset_mail',views.send_password_reset_mail,name='send_password_reset_mail'), ]
StarcoderdataPython
11348602
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import onnx from onnx import shape_inference import warnings from onnx_tf.backend import prepare import numpy as np # %% def stride_print(input): tensor = input.flatten().tolist() length = len(tensor) size = 20 ...
StarcoderdataPython
8107705
import matplotlib.pyplot as plt from scipy.ndimage.filters import gaussian_filter1d from matplotlib.pyplot import figure def make_line_plot(save_to_folder: str, list_of_data_points, xlabel, ylabel, title, add_avg_line=False, sigma=0, all_xticks=False, custom_width=False, width=0): if custom_width: figure(...
StarcoderdataPython
1984550
# encoding=utf-8 import tensorflow as tf import numpy as np time_steps = 12 channel_size = 3 embedding_size = 64 embedding_fn_size = 312 filter_num = 8 filter_sizes = [1, 3, 5] threshold = 0.5 class CnnModel(object): def __init__(self, init_learning_rate, decay_steps, decay_rate): weig...
StarcoderdataPython
6635672
<filename>molmodmt/sequence.py<gh_stars>0 from molmodmt import convert as _convert from molmodmt import select as _select def sequence_alignment(ref_item=None, item=None, engine='biopython', prettyprint=False, prettyprint_alignment_index = 0, **kwards): alignment = None if engine=='bio...
StarcoderdataPython
1678057
<filename>Matlab and Python Scripts/PyAppNotes/PyAppNotes/AN24_02.py # AN24_02 -- FMCW Basics import Class.Adf24Tx2Rx4 as Adf24Tx2Rx4 from numpy import * # (1) Connect to Radarbook # (2) Enable Supply # (3) Configure RX # (4) Configure TX # (5) Start Measurements # (6) Configure calculation of range profi...
StarcoderdataPython
6549551
<reponame>Addovej/spotiplays<filename>src/conf/__init__.py from functools import lru_cache from .settings import Settings @lru_cache def get_settings() -> Settings: return Settings() settings = get_settings() __all__ = ( 'settings', )
StarcoderdataPython
8018478
<gh_stars>1-10 ''' Author: <NAME> Date: 2021-10-02 15:56:57 LastEditTime: 2021-10-06 10:04:04 LastEditors: <NAME> Description: FilePath: /INF/INF101/TD/1.3.14.py ''' n = float(input("Saissez un nombre n")) tmp = 0 def trouve_nombre_or(range): table = [] count = 0 table.append(1) table.append(1) ...
StarcoderdataPython
1811567
<filename>python/sum-and-prod.py import numpy n,m=map(int,input().split()) a=numpy.zeros((n,m),int) for i in range(n): a[i]=numpy.array(input().split()) print(numpy.prod(numpy.sum(a,axis=0),axis=None))
StarcoderdataPython
4811611
<reponame>eyalle/python_course<gh_stars>0 import sys, random, time sys.path.append("../../") from exercises.data import get_data data = get_data(5) users = [{'name': items['name']} for items in data] hobbies = [ 'football', 'strongman', 'mario', 'tekken-3', 'beach', 'soccer', 'bacon', ...
StarcoderdataPython
12823853
from phactori import * from paraview.simple import * #utilities for doing various data grid/geometric operations in parallel #in particular: #GetListOfGridPointsNearestListOfPointsV5 # takes a list of geometric points, and goes through all processors and all # blocks and finds the data grid point which is nearest t...
StarcoderdataPython
3523114
import warnings import numpy as np from sklearn.preprocessing import StandardScaler class SkLearnMixerHelper: def _input_encoded_columns(self, target_column, when_data_source): """ :param when_data_source: is a DataSource object :return: numpy.nd array input encoded values """ ...
StarcoderdataPython
8075658
<gh_stars>1-10 # coding: utf-8 """ MailSlurp API MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homep...
StarcoderdataPython
3284294
<filename>utils.py import torch import torch.nn as nn import numpy as np from scipy.interpolate import interp1d import os import sys import random import config def upgrade_resolution(arr, scale): x = np.arange(0, arr.shape[0]) f = interp1d(x, arr, kind='linear', axis=0, fill_value='extrapolate') scale_x ...
StarcoderdataPython
64999
#$Id$ class Category: """This class is used to create object for category.""" def __init__(self): """Initialize parameters for Category.""" self.id = "" self.name = "" def set_id(self, id): """Set id. Args: id(str): Id. """ se...
StarcoderdataPython
1703828
from __future__ import print_function import re import tempfile from .base import Base from .hash import HASH_ALGORITHM from .signature import SIGN_ALGORITHM _DIRTY_PATH = re.compile('(?:^|/)(\.\.?)(?:/|$)') class Downloader(Base): def _validate_entry_path(self, path): if path.startswith('/'): ...
StarcoderdataPython
1881308
<filename>auction_api/api/bidder_admin.py import pymongo from werkzeug.wrappers.response import Response import utils.globales as globales from bson.json_util import dumps def get_requests_by_status(status): if status not in ["0","1"]: return Response("Invalid Status",400) mongo_cli = pymongo.MongoCl...
StarcoderdataPython
1952711
numbers = [int(s) for s in input().split(', ')] def get_positive_numbers(numbers): return [str(s) for s in numbers if s >= 0] def get_negative_numbers(numbers): return [str(s) for s in numbers if s < 0] def get_odd_numbers(numbers): return [str(s) for s in numbers if s % 2 != 0] def get_even_numbers...
StarcoderdataPython
11205921
import datetime as dt from collections import Sequence from pandas_datareader.data import DataReader from .download_splits_dividends import download_splits_dividends def download_stock(symbol, start_date=dt.datetime(1990, 1, 1)): # Download assets. stock = DataReader(symbol, "yahoo", start_date) stock.ren...
StarcoderdataPython
3552544
<reponame>ghanigreen/pytest_code import textwrap from math import sqrt from pytest import approx def magnitude(x, y): return sqrt(x * x + y * y) def test_simple_math(): assert abs(0.1 + 0.2) - 0.3 < 0.0001 def test_simple_math2(): assert (-0.1 - 0.2) + 0.3 < 0.0001 def test_approx_simple(): ass...
StarcoderdataPython