id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3260018
<gh_stars>1-10 class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n = len(nums1) + len(nums2) if n%2 == 0: n2 = n//2 n1 = n2 - 1 else : n2 = -1 n1 = n//2 dp = [0] * ((len(nums1) + len(nums2...
StarcoderdataPython
3225248
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on Aug 29, 2016 ''' from __future__ import print_function from __future__ import unicode_literals import unittest from pprint import pprint from weblyzard_api.client.recognize import Recognize class TestRecognize(unittest.TestCase): DOCS_XML = [ ''...
StarcoderdataPython
3333566
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # @File : api.py # @Author : cgDeepLearn # @Create Date : 2020/11/16-3:40 下午 import datetime import random class TestApi(object): def __init__(self, req_data): self.req_data = req_data def process(self): """ 处理返回 """ ...
StarcoderdataPython
1710219
<gh_stars>0 from odoo import fields, models class StockPicking(models.Model): _inherit = 'stock.picking' ep_tracking_url = fields.Char("Easypost Tracking URL", copy=False) ep_order_id = fields.Char("Easypost Order", copy=False)
StarcoderdataPython
4825305
from mock import patch from datetime import datetime from django.conf import settings from django.core import mail from django.test import TestCase, override_settings from perma.tasks import update_stats, upload_all_to_internet_archive, upload_to_internet_archive, delete_from_internet_archive, cm_sync, send_js_errors...
StarcoderdataPython
3375745
from common.constant import StatusCode from common.exception_handler import exception_handler from common.logger import get_logger from common.utils import generate_lambda_response from utility.application.services.generate_grpc_python_stubs import generate_python_stubs from utility.application.services.proto_compilati...
StarcoderdataPython
4819870
<filename>lib/utils.py from enum import Enum import cv2 class MethodAveragePrecision(Enum): """ Class representing if the coordinates are relative to the image size or are absolute values. Developed by: <NAME> Last modification: Apr 28 2018 """ EveryPointInterpolation = 1 Ele...
StarcoderdataPython
1771462
<gh_stars>0 # this file has too much stuff in it. need to learn to import. import libtcodpy as libtcod #used sqrt at some points import math #used textwrap for messages import textwrap #used this to save/load import shelve SCREEN_WIDTH = 80 SCREEN_HEIGHT = 50 #GUI element constants BAR_WIDTH = 20 PANEL_HEIGHT = 7 ...
StarcoderdataPython
1705729
<gh_stars>0 import pandas as pd import pickle data = pd.read_csv("data/mm10_data/ChIP/Sox2_counts.csv", header=None, index_col=False) ids = [] count = [] for row in data[0]: ids.append(row) for row in data[1]: count.append(row) export_data = {} for x in range(len(ids)): export_data[ids[x]] = count[x] w...
StarcoderdataPython
1728745
<reponame>kkkkv/tgnms<gh_stars>10-100 #!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. from typing import Optional class TGLibError(Exception): """Base class for all :mod:`tglib` errors.""" pass class ConfigError(TGLibError): """Raised if there is an error reading or cons...
StarcoderdataPython
3368056
"""A method is a Python function that can be called by a JSON-RPC request. They're held in a dict, a mapping of function names to functions. The @method decorator adds a method to jsonrpcserver's internal global_methods dict. Alternatively pass your own dictionary of methods to `dispatch` with the methods param. ...
StarcoderdataPython
3231164
<reponame>tsyroid/tiny_python_projects # CH.9 abuse # Build the noun list for abuse.py def make_nouns(): '''Build a list of nouns for abuse.py''' nouns = ''' Judas Satan ape ass barbermonger begger block boy braggart butt carbuncle coward coxcomb cur dandy degenerate fiend fishmonger fool gull...
StarcoderdataPython
1779054
<filename>05-1.py f = open('05-1.input') rows = f.readlines() f.close() steps = 0 jumps = [int(x) for x in rows] j = 0 while (j >= 0 and j < len(jumps)): prevJ = j j += jumps[j] steps += 1 jumps[prevJ] += 1 print(steps)
StarcoderdataPython
1690266
<reponame>hawflau/serverless-application-model<gh_stars>0 from mock import Mock, patch from unittest import TestCase from samtranslator.model.eventsources.push import EventBridgeRule from samtranslator.model.lambda_ import LambdaFunction from samtranslator.model.exceptions import InvalidEventException class EventBri...
StarcoderdataPython
1770129
""" Asked by: Apple [Easy]. A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer: if n is even, the next number in the sequence is n / 2 if n is odd, the next number in the sequence is 3n + 1 It is conjectured that every such sequence eventually reaches the number 1. Test th...
StarcoderdataPython
3329593
<filename>solarvino/utils.py import json import numpy as np from typing import Dict def dump_beautiful_json(record: Dict, path: str): def convert(o): if isinstance(o, np.generic): return o.item() raise TypeError # now write output to a file json_file = open(path, "w") # magic happens ...
StarcoderdataPython
64968
#!/usr/bin/python import argparse import distutils.version import json import os import plistlib import subprocess import sys import tempfile import urllib import webbrowser def export_bundle(bundle_path): toplevel_path = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel']).rstrip() git =...
StarcoderdataPython
3303135
# coding: utf-8 from django import template __author__ = 'mhaze' register = template.Library() @register.inclusion_tag('textflow.html') def textflow(texts=None): if not isinstance(texts, str): raise Exception("Texts must be of type str") return { 'texts': texts }
StarcoderdataPython
172878
from django.conf import settings as site_settings from django.db import models, transaction from django.utils.translation import ugettext_lazy as _ from taggit.managers import TaggableManager from uuid import uuid4 from . import helpers, query, settings, tasks import django_rq import string class ContentObject(models...
StarcoderdataPython
3371024
<filename>ElevatorBot/commandHelpers/autocomplete.py from dis_snek.models import AutocompleteContext from rapidfuzz import fuzz, process from Shared.networkingSchemas.destiny import DestinyActivityModel, DestinyLoreModel, DestinyWeaponModel # all activities are in here at runtime activities_grandmaster: dict[str, Des...
StarcoderdataPython
1788493
<reponame>LarissaBrencher/Diffusion2D-Python-Package<filename>setup.py from setuptools import setup import setuptools import versioneer with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="brenchladiffusion2D", version=versioneer.get_version(), cmdclass=versio...
StarcoderdataPython
1690243
"""This example turns the little red LED on only while button B is currently being pressed.""" from adafruit_circuitplayground import cp # This code is written to be readable versus being Pylint compliant. # pylint: disable=simplifiable-if-statement while True: if cp.button_b: cp.red_led = True ...
StarcoderdataPython
5291
import numpy as np import torch import matplotlib.pyplot as plt from torch import optim, nn from pytorch.xor.multilayer_perceptron import MultilayerPerceptron from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations input_size = 2 output_size = len(set(LABELS)) num_hidd...
StarcoderdataPython
1636188
import unittest from followthemoney.types import registry numbers = registry.number class NumberTest(unittest.TestCase): def test_cast_num(self): self.assertEqual(numbers.to_number("1,00,000"), 100000.0) self.assertEqual(numbers.to_number(" -999.0"), -999.0) self.assertEqual(numbers.to_n...
StarcoderdataPython
3379513
<reponame>ah-choo/api.ahchoo.fun from src.api import app @app.api.get("/") def index(): """The welcome home page. Returns: dict: welcome message. """ return {"Hello": "World"}
StarcoderdataPython
4833856
def calc(x, y): """ Test calc function with doctest to execute: python -m doctest -v python_file.py >>> calc(1,2) 3 >>> calc(2,3) 1 >>> calc(1,3) 4 """ soma = x + y return soma
StarcoderdataPython
1720278
""" connect to twitter via the tweepy to makes posts on twitter last update by Ilyass on 5/14/21 """ import os import tweepy as tw import AstroNASA as an import PicNASA as pn import requests #necessary keys and tokens to validate account identity (keys are REDACTED for safety) consumer_key= 'REDACTED' consumer_secret=...
StarcoderdataPython
197052
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-26 02:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0008_userprofile_last_deal_sent_id'), ] operations = [ migrations.Ad...
StarcoderdataPython
20515
<gh_stars>10-100 """ tcp_message Inline Script Hook API Demonstration ------------------------------------------------ * modifies packets containing "foo" to "bar" * prints various details for each packet. example cmdline invocation: mitmdump --rawtcp --tcp-host ".*" -s examples/complex/tcp_message.py """ from mitmpr...
StarcoderdataPython
190289
#GNV_data_reader.py #loads data from GNV output; converts timestamps into epoch time to align with SSTDR measurements #data source, with info: https://mesonet.agron.iastate.edu/request/download.phtml?network=FL_ASOS """ GNV columns: station: station; GNV airport valid: timestamp at which data is valid ...
StarcoderdataPython
1696160
<reponame>CombatExtended-Continued/DiscordIssueBot from .bot import factory import sys from twisted.internet import reactor startLogging(sys.stdout) reactor.listenTCP(8080, factory) reactor.run()
StarcoderdataPython
197982
<gh_stars>0 import sublime import sublime_plugin from .core.configurations import is_supported_syntax from .core.documents import is_transient_view from .core.protocol import Range from .core.protocol import Request from .core.registry import session_for_view, sessions_for_view, client_from_session, configs_for_scope f...
StarcoderdataPython
3328591
# Generated by Django 3.0.6 on 2020-05-23 19:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("authentik_providers_saml", "0001_initial"), ] operations = []
StarcoderdataPython
8132
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import cv2 import numpy as np import os import math from PIL import Image, ImageDraw, ImageFont from caffe2.python import workspace from detectron.core.config import cf...
StarcoderdataPython
1794391
<filename>src/homework/b_in_proc_out/output.py<gh_stars>0 def get_number(num): return num
StarcoderdataPython
1684110
# -*- coding: utf-8 -*- """Extend werkzeug request handler to suit our needs.""" import time from werkzeug.serving import BaseRequestHandler class ShRequestHandler(BaseRequestHandler): """Extend werkzeug request handler to suit our needs.""" def handle(self): self.shRequestStarted = time.time() ...
StarcoderdataPython
3294797
import requests, tweepy, time, urllib def get_venmos(): vens = requests.get("https://venmo.com/api/v5/public") return vens.json()['data'] def summarize(json): actor = json['actor']['firstname'] if isinstance(json['transactions'][0]['target'], str): target = json['transactions'][0]['target'] ...
StarcoderdataPython
1747032
<reponame>agy-why/daiquiri from django.conf import settings from daiquiri.core.utils import import_class from daiquiri.core.adapter.stream import BaseServiceAdapter def CutOutAdapter(): return import_class(settings.CUTOUT_ADAPTER)() class BaseCutOutAdapter(BaseServiceAdapter): pass
StarcoderdataPython
65737
<reponame>apretori-tic/testplan<gh_stars>0 """FixServer driver classes.""" import os from six.moves import queue as Queue from schema import Use from testplan.common.config import ConfigOption from testplan.common.utils.strings import slugify from testplan.common.utils.sockets.fix.server import Server from testplan...
StarcoderdataPython
4804635
<gh_stars>1-10 from .manager import ExperimentManager class ExperimentsMiddleware(object): """Experiments middleware. Binds the convenient :class:`ExperimentManager` to the request. """ def process_request(self, request): assert hasattr(request, 'session'), \ 'Django Banana requi...
StarcoderdataPython
3285011
import re, json from abc import ABCMeta class Command(metaclass=ABCMeta): def __init__(self, trigger): self.trigger = trigger self.description = "Empty description." self.system = False self.privilege = False self.keyboard = { "action": { "ty...
StarcoderdataPython
4840939
import logging import os import structlog from flask import Blueprint from flask import make_response, request from werkzeug.utils import secure_filename from application.controllers.basic_auth import auth from application.controllers.survey_response import SurveyResponse, FileTooSmallError, SurveyResponseError log ...
StarcoderdataPython
184349
# lint-amnesty, pylint: disable=missing-module-docstring from django.core.management.base import BaseCommand, CommandError from opaque_keys.edx.keys import CourseKey from lms.djangoapps.courseware.courses import get_course class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring help ...
StarcoderdataPython
9106
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import os import argparse import logging import numpy as np from PIL import Image import matplotlib import matplotlib.pyplot as plt import torch import torch.nn as nn from torchvision import transforms import cv2 import tqdm from net.pspnet import PSPNet models = { ...
StarcoderdataPython
3370429
<gh_stars>1-10 # vim: fdm=marker ''' author: <NAME> date: 31/08/15 content: Store local divergence and diversity in a sliding window. ''' # Modules import os import sys import argparse from operator import itemgetter import numpy as np from Bio import SeqIO from hivwholeseq.utils.miseq import alpha from h...
StarcoderdataPython
1676967
<filename>lib/python3.8/site-packages/ansible_collections/cisco/ios/plugins/modules/ios_facts.py #!/usr/bin/python # # This file is part of Ansible # # Ansible 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, e...
StarcoderdataPython
134578
<filename>saucelab_api_client/base_classes/insights_api.py from datetime import datetime from saucelab_api_client.category import Base from saucelab_api_client.models.insights import Insight from saucelab_api_client.models.service import get_dict_from_locals, get_datetime_for_insights class Insights(Base): __sub...
StarcoderdataPython
1702883
<filename>calpurnia.py<gh_stars>0 #!/usr/bin/python3 import argparse import scraper import os.path import sqlite3 def get_course_string(course): GREEN = '\033[92m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' course_string = BOLD + GREEN + UNDERLINE+ course['section'] + '*' + course['code'] + " " + ...
StarcoderdataPython
3390905
#!/usr/bin/env python3 import math import sys from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) def is_point_on_line(origin, dest, test): if dest.x == origin.x: return True a = (dest.y - origin.y) / (dest.x - origin.x) # (y - y_0) = a * (x - x_0) => y = a * x - (a * x_0...
StarcoderdataPython
3333316
<gh_stars>0 import os import warnings import asyncio import requests import aiohttp from sqlalchemy.exc import SAWarning from werkzeug.local import Local, LocalProxy from flask import current_app from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_signalbus import SignalBusMixin, Atomic...
StarcoderdataPython
3245126
"""Tests for NonlocalGame class.""" import unittest import numpy as np from toqito.nonlocal_games.nonlocal_game import NonlocalGame class TestNonlocalGame(unittest.TestCase): """Unit test for NonlocalGame.""" @staticmethod def ffl_nonlocal_game(): """Define the FFL nonlocal game.""" num_...
StarcoderdataPython
1748161
<gh_stars>1-10 from itertools import chain import dash_html_components as html from dash.development._py_components_generation import ( filter_props, js_to_py_type, parse_events, reorder_props, ) def ApiDoc(component_metadata, component_name=None): component_props = component_metadata.get("props"...
StarcoderdataPython
3261755
import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, "README.rst")).read() setup( name="django-type_sense", version="0.1", packages=["type_sense"], description="Adds type_sense binding to your Django models", long_description=RE...
StarcoderdataPython
35585
from django import template register = template.Library() @register.filter def is_bbb_mod(room, user): return room.is_moderator(user)
StarcoderdataPython
3237612
<reponame>windsuzu/leetcode-python<gh_stars>1-10 from typing import List class Solution: def numIslands(self, grid: List[List[str]]) -> int: # the idea is to loop through all the cells # if we find any "1", then we DFS from it to all its adjancent cells # and mark the cell as visited by rep...
StarcoderdataPython
3263509
""" The ``agar.image`` module contains classes to help work with images stored in the `Blobstore`_. """ from __future__ import with_statement import logging import mimetypes import urlparse from google.appengine.api import images, memcache, files, urlfetch from google.appengine.api.images import NotImageError from ...
StarcoderdataPython
3356289
# coding: utf-8 ######################################################################### # 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> # # author yeeku.H.lee <EMAIL> # # # # version 1.0 ...
StarcoderdataPython
54493
from django.utils.deprecation import MiddlewareMixin class MyCors(MiddlewareMixin): def process_response(self, requesst, response): response['Access-Control-Allow-Origin'] = '*' if requesst.method == 'OPTIONS': response["Access-Control-Allow-Headers"] = "*" response['Access...
StarcoderdataPython
67479
<reponame>twardoch/TypeRig<gh_stars>1-10 #FLM: Glyph: Metrics # ---------------------------------------- # (C) <NAME>, 2018 (http://www.kateliev.com) # (C) Karandash Type Foundry (http://www.karandash.eu) #----------------------------------------- # No warranties. By using this you agree # that you use it at your own ...
StarcoderdataPython
4838739
letter_map = [[3,9,15,21,27,33,39],[5,10,20,25,30,35,40],[7,14,28],[8,16,24,32]] point_values = [["A","E"],["D","R"],["B","M"],["V","Y"],["J","X"]] lengths = [7,7,3,4] word_sum = 0 word_arr = (input("Enter the word: ")).split(",") score_map = [] for i in range(4): for j in range(5): if point_values[j][0] ...
StarcoderdataPython
3262702
<filename>tests/test_consumer.py #! /usr/bin/python3 # Tests to verify functionality of the consumer import consumer class AivenKafkaConsumerTest(object): def __init__(self): self.consumer = consumer.AivenKafkaConsumer('10', 'avnadmin', 'xavuesgxzeay1e8b', 'pg-mmn-kafka-snmohan83-3313.aiv...
StarcoderdataPython
171649
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: http://www.oidview.com/mibs/0/SNMPv2-MIB.html from typing import Iterator # pip install pysnmp from pysnmp.hlapi import nextCmd, SnmpEngine, CommunityData, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity def get_iterato...
StarcoderdataPython
3327182
<reponame>justinjeffery-ipf/python-ipfabric """ credentials.py """ from pprint import pprint from ipfabric import IPFClient from ipfabric.settings import Authentication if __name__ == '__main__': ipf = IPFClient() # Token must have Setting Permissions # ipf = IPFClient('https://demo3.ipfabric.io/', token='to...
StarcoderdataPython
145217
<filename>paww/augmentation.py<gh_stars>0 from typing import Any import albumentations as A from albumentations.pytorch import ToTensorV2 __all__ = ["get_transforms"] def get_transforms(cfg: dict, data: str) -> Any: if data == "train": return A.Compose( [ A.RandomResizedCrop...
StarcoderdataPython
3319408
''' 03 - Line plot [3] Now that you've built your first line plot, let's start working on the data that professor <NAME> used to build his beautiful bubble chart. It was collected in 2007. Two lists are available for you: life_exp which contains the life expectancy for each country and gdp_cap, which contains the GDP...
StarcoderdataPython
21784
<reponame>plasticuproject/DoodleNet import pygame import random import numpy as np import cv2 from dutil import add_pos #User constants device = "gpu" model_fname = 'Model.h5' background_color = (210, 210, 210) input_w = 144 input_h = 192 image_scale = 3 image_padding = 10 mouse_interps = 10 #Derived constants drawi...
StarcoderdataPython
1657255
<filename>wirelesstagpy/__init__.py #!/usr/bin/python # -*- coding: utf-8 -*- """ Simple python library for wirelesstags REST API. See http://wirelesstag.net/apidoc.html for more details. Current implementation includes: - loading info for all available to user sensor tags - manage local push notifications - arm/disa...
StarcoderdataPython
1745711
import os import glob import re import sys # access system routines, including writing console output to file import math import scipy import numpy as np import matplotlib.pyplot as plt import Common import Plotting import BER_Analysis import FR_Analysis labs = ['r*-', 'g^-', 'b+-', 'md-', 'cp-', 'yh-', 'ks-' ] # p...
StarcoderdataPython
3346208
<reponame>peterezzo/splunk-pwn-app import splunk.entity as entity import splunk.auth, splunk.search import getpass def huntPasswords(sessionKey): entities = entity.getEntities( ['admin','passwords'],owner="nobody", namespace="-",sessionKey=sessionKey) return entities def getSessionKeyFromCreds(): ...
StarcoderdataPython
1706847
from mock import Mock from oauth2 import Provider from oauth2.compatibility import json from oauth2.error import OAuthInvalidError, OAuthInvalidNoRedirectError from oauth2.grant import (AuthorizationCodeGrant, GrantHandler, RefreshToken, ResourceOwnerGrant) from oauth2.store import ClientStore...
StarcoderdataPython
3203236
<gh_stars>1-10 import os import numpy as np import torch import copy from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE from pytorch_pretrained_bert import BertTokenizer, BertModel # load data # processor = NerProcessor() # label_list = processor.get_labels() # num_labels = len(label_list) +...
StarcoderdataPython
177280
import logging import numpy as np from scipy.stats import nbinom, poisson, binom from scipy.special import gamma, factorial, gammaln, logsumexp, hyp2f1, hyp1f1, hyperu, factorial class CountModel: error_rate=0.01 class MultiplePoissonModel(CountModel): def __init__(self, base_lambda, repeat_dist, certain_coun...
StarcoderdataPython
1751562
# Copyright 2019, The TensorFlow Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
StarcoderdataPython
178718
<reponame>Itai12/Amanager<filename>cogs/help.py import discord, asyncio, json, requests from discord.ext import commands from discord_slash import cog_ext, SlashContext from discord_slash.utils.manage_commands import create_option class Slash(commands.Cog): def __init__(self, bot): self.bot = bot @cog...
StarcoderdataPython
3368489
<reponame>taotao1234abcd/machine-learning-and-artificial-intelligence-python #!/usr/bin/env python3 # encoding: utf-8 """ @version: 0.1 @author: lyrichu @license: Apache Licence @contact: <EMAIL> @site: http://www.github.com/Lyrichu @file: config.py @time: 2018/06/07 13:26 @description: basic config for GA """ class B...
StarcoderdataPython
160864
#Coded by <NAME> #02/09/2018 latest version. #Copyright (c) <2018> <<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...
StarcoderdataPython
3295614
from django.contrib.auth.models import User from django.db import models class Question(models.Model): title = models.CharField(max_length=1024) text = models.TextField() added_at = models.DateTimeField(auto_now_add=True) rating = models.IntegerField(blank=True, null=True, default=0) author = mode...
StarcoderdataPython
1799999
#!/usr/bin/env python """ This runner is controlled by evennia.py and should normally not be launched directly. It manages the two main Evennia processes (Server and Portal) and most importanly runs a passive, threaded loop that makes sure to restart Server whenever it shuts down. Since twistd does not allow for ...
StarcoderdataPython
4826077
#!/usr/bin/env python # -*- coding: utf-8 -*- from numbapro import cuda import numpy as np # define the kernel @cuda.jit('void(float64[:], float64, float64[:], float64[:])') def daxpy(yd, a, x, y): i = cuda.grid(1) # equals to threadIdx.x + blockIdx.x * blockDim.x yd[i] = a * x[i] + y[i] # initialize ve...
StarcoderdataPython
4036
<filename>bin/sort.py #!/usr/bin/env python3 """ usage: sort.py [-h] sort lines options: -h, --help show this help message and exit quirks: sorts tabs as different than spaces sorts some spaces ending a line as different than none ending a line examples: Oh no! No examples disclosed!! 💥 💔 💥 """ # FIXME...
StarcoderdataPython
1645404
from inference.gp_tools import GpOptimiser import matplotlib.pyplot as plt import matplotlib as mpl from numpy import sin, cos, linspace, array, meshgrid mpl.rcParams['axes.autolimit_mode'] = 'round_numbers' mpl.rcParams['axes.xmargin'] = 0 mpl.rcParams['axes.ymargin'] = 0 def example_plot_1d(): mu, sig = GP(x_g...
StarcoderdataPython
3387289
#!/usr/bin/env python import random import websockets import asyncio import os import numpy as np import cv2 import json import base64 #!/usr/bin/env python # WS server that sends messages at random intervals class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture('video2.mp4') ...
StarcoderdataPython
3349871
#!/usr/bin/env python3 from statistics import mean def c2f(celsius): return (celsius * 9 / 5) + 32 def f2c(fahrenheit): return (fahrenheit - 32) * 5 / 9 def print_results(all_readings): highest_temp = max(all_readings) lowest_temp = min(all_readings) average_temp = mean(all_readings) pr...
StarcoderdataPython
1715225
# Test of ability to connect to the Neo4j database from the credentials # in the environment variables NEO4J_HOST, NEO4J_USER, NEO4J_PASSWORD import os from BrainAnnex.modules.neo_access.neo_access import NeoAccess print("About to test the database connection, using the credentials STORED in the environment variables...
StarcoderdataPython
3212726
<gh_stars>1-10 import pytest from .solution import solve, solve2, parse, make_big_map INPUT = """1163751742 1381373672 2136511328 3694931569 7463417111 1319128137 1359912421 3125421639 1293138521 2311944581 """ def test_solve(): assert solve(INPUT) == 40 def test_solve2(): assert solve2(INPUT) == 315 def ...
StarcoderdataPython
3263068
import pytest from code_challenges.graph.graph import Graph,Vertex def test_add_node(): expected = 'a' graph = Graph() actual = graph.add_node('a').value assert actual == expected def test_add_edge_exists(): graph = Graph() node_a = graph.add_node('a') node_b = graph.add_node('b') grap...
StarcoderdataPython
174014
<filename>test/ResultsAndPrizes/joker/test_joker_winning_numbers_for_several_draws.py # Джокер + Выигрышные номера нескольких тиражей def test_joker_winning_numbers_for_several_draws(app): app.ResultAndPrizes.open_page_results_and_prizes() app.ResultAndPrizes.click_game_joker() app.ResultAndPrizes.click_...
StarcoderdataPython
4835050
<reponame>zju-zry/jueshaRearrangement. from typing import cast, Dict, Any import torch from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.abstract_loss import ( AbstractActorCriticLoss, ) from allenact.algorithms.onpolicy_sync.policy import ObservationType from ...
StarcoderdataPython
1688269
<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import streamlit as st import cv2 from keras.models import load_model # In[2]: model = load_model('E:\\Python\\intel_image.h5') # In[ ]: CLASS_NAMES = ['builidings','Forest','glacier','Mountain','Sea','Street'] # In[3]: st.tit...
StarcoderdataPython
3396600
<reponame>molguin92/Relay<filename>relay.py # Copyright 2019 <NAME> <<EMAIL>><<EMAIL>> # # 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 ...
StarcoderdataPython
1634223
## Lists, both lectures 1 and 2 # I have 3 lists declared below, play around with the following # functions, methods, slices or other ones you like on them # len(), min(), max(), append(), insert(), extend(), remove(), pop() # reverse() # Note: Some methods/functions above are covered in lecture 1 # while others are c...
StarcoderdataPython
1775897
<gh_stars>0 #!/usr/bin/env python #-*- coding:utf-8 -*- from django.db import models # Create your models here. # Create your models here. from django.urls import reverse class NNGModel(models.Model): address = models.CharField(max_length=255, default='', null=True, verbose_name=u"краткий адрес") full_addre...
StarcoderdataPython
3287835
<gh_stars>1-10 """Module for all constants""" CHARSETS = ['utf-8', 'ascii'] READ_ONLY_FIELDS = ['id', 'created_at', 'updated_at']
StarcoderdataPython
1604368
<filename>BOJ/11000~11999/11600~11699/11608.py a=list(input()) D=dict() for i in a: if i in D: D[i]+=1 else: D[i]=1 L=[] for i in D.items(): L.append([i[0],i[1]]) L.sort(key=lambda t: t[1]) ans=0 if len(L)>2: for i in L[:-2]: ans+=i[1] print(ans)
StarcoderdataPython
3206481
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using PrettyGood.Util; namespace PrettyGood.LastFm { public class Tag { public Tag( XmlElement el ) { this.name = Xml.GetTextOfSubElement(el, "name"); this.url = Xml....
StarcoderdataPython
46016
<filename>modules/User/UserServices.py<gh_stars>1-10 from flask import session from User import UserRepo import bcrypt from datetime import date class UserServices: def __init__(self, db) -> None: self.db = UserRepo.Repo(db) def login(self, user): if('@' not in user.userid or len(user.userid...
StarcoderdataPython
136672
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
StarcoderdataPython
1715583
#! /usr/bin/env python2.7 # MessageBlinker is a little program that listens to an MQTT channel and # blinks a quick pattern when a message is received, then prints the message. # MQTT is the protocol we use for communicating import paho.mqtt.client as mqtt # Rpi.GPIO is the library that lets us talk to the GPIO pin...
StarcoderdataPython
3314396
def initialize_module(app_context): app_context.state['something'] = "It's a me, MARIO!" print(app_context.state['something'])
StarcoderdataPython
53239
<reponame>IZUMI-Zu/CS61A from operator import add, sub def a_plus_abs_b(a, b): """Return a+abs(b), but without calling abs. >>> a_plus_abs_b(2, 3) 5 >>> a_plus_abs_b(2, -3) 5 """ if b < 0: b = -b f = add else: f = add return f(a, b) def a_plus_abs_b_syn...
StarcoderdataPython