id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6434336 | from pwn import *
PROGNAME = "./geelang-compiler"
if args.REMOTE:
p = process(["./cli-relay", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImNhZmZAZ2VlZ2xlLm9yZyIsInNlcnZpY2UiOiJ1YmVycHJveHlAc2VydmljZXMuZ2VlZ2xlLm9yZyIsImV4cCI6MTU3NTE0OTgwMn0.p-lpYOJ6RaImmd7HXm66pfZsUkk_Vbp206dDOqPSCzF0xuNEC6wDSeesh8ku... | StarcoderdataPython |
3598328 | from msdi_io import *
class batchLoader():
def __init__(self,batch_size,path_msdi,max_size=30712):
self.i = 0
self.batch_size= batch_size
self.path_msdi = path_msdi
self.max_size = max_size
self.msdi = get_msdi_dataframe(msdi_path)
def load(self,batch_nb,img_size):
batch_size = min(self.i+self.batch... | StarcoderdataPython |
3339970 | """
-- UnmaintableCode: C Module --
Author: @CosasDePuma <<EMAIL>>(https://github.com/cosasdepuma)
"""
# pylint: disable=too-few-public-methods, no-self-use, unused-argument, dangerous-default-value
import re
from random import randint
class Module:
""" Rename variables to _ or __ """
def __init__(self, var... | StarcoderdataPython |
1842945 | from sqlalchemy.orm import relationship
from db import db
import datetime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Comments(db.Model,Base):
id = db.Column(db.Integer, primary_key = True)
publishedOn = db.Column(db.DateTime(),nullable =False, default=datetime.date... | StarcoderdataPython |
4881203 | <reponame>leighmforrest/frankenblog
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.core.exceptions import PermissionDenied
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib import messages
from django.shortcuts i... | StarcoderdataPython |
3599230 | from flask import Flask, render_template, redirect, jsonify
from flask_pymongo import PyMongo
import scrape_mars
#Create an instance of Flask
app = Flask(__name__)
#Use PyMongo to establish mongo connection
mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_app")
@app.route("/")
def home():
mars_collectio... | StarcoderdataPython |
253918 | from __future__ import absolute_import, division, print_function
import os
import sys
sys.path.append('/'.join([os.environ['_CIOP_APPLICATION_PATH'], 'util']))
sys.path.append('../util')
import numpy as np
import gdal
import osr
import urllib.parse as urlparse
import pandas as pd
import datetime
from vam.whittaker ... | StarcoderdataPython |
4886570 | <filename>api/services/vote_service.py
from django.http import HttpResponse, JsonResponse
from rest_framework import serializers
from api.services.home_service import error
from repository.repos import Vote
from api.dto.vote_dto import VoteSerializer
def votes(request):
data = Vote.get_all()
serializer = Vot... | StarcoderdataPython |
11356879 | <gh_stars>1-10
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
from setuptools import setup, find_packages
setup(
name="django-expenses",
version="0.5.0",
description="A comprehensive system for managing expenses",
keywords="django,expenses",
author="<NAME>",
author_email="<EMAIL>",
... | StarcoderdataPython |
310250 | from kratos import Interface
class GlbConfigInterface(Interface):
def __init__(self, addr_width: int, data_width: int):
Interface.__init__(self, f"glb_cfg_ifc_A_{addr_width}_D_{data_width}")
# Local variables
self.wr_en = self.var("wr_en", 1)
self.wr_addr = self.var("wr_addr", add... | StarcoderdataPython |
4985008 | # -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
import importlib
import uuid
from flask import flash, jsonify
from cartunningservice.constants.http_status_codes import STATUS_CODES
def flash_errors(form, category='warning'):
"""Flash all errors for a form."""
for field, errors in form.errors.... | StarcoderdataPython |
4911678 | <gh_stars>0
#AOJ_rowの.pyファイル達を一つのテキストファイルにするコード
#python3 yomikaki.py >> aoj_row.txt
import glob
from tqdm import tqdm
import csv
# input_files = glob.glob("/Users/t_kajiura/AOJ_raw/*.py")
#AOJ_rowの.pyファイル達を一つのテキストファイルにするコード
def pytotxt(input_files):
for input_file in input_files:
with open(f'{input_file}... | StarcoderdataPython |
9727717 | # -*- coding: utf-8 -*-
"""
NotiHub
Copyright 2017 <NAME> <<EMAIL>>
Unofficial Facebook Chat API for Python [https://github.com/carpedm20/fbchat]
Unofficial Facebook Chat API [https://github.com/Schmavery/facebook-chat-api]
The following code is licensed under the MIT License
"""
import fbchat
from .__stub__ import... | StarcoderdataPython |
1891137 | from __future__ import annotations
from typing import cast
from coredis._utils import EncodingInsensitiveDict
from coredis.response._callbacks import ResponseCallback
from coredis.response._utils import flat_pairs_to_dict
from coredis.response.types import LibraryDefinition
from coredis.typing import (
AnyStr,
... | StarcoderdataPython |
128420 | <filename>utils/__init__.py
import utils.tokenizer
import utils.colouring | StarcoderdataPython |
229186 | # -*- coding: utf-8 -*-
"""
Class: LinearProgramming
"""
import numpy as np
import gurobipy as gp
class LinearProgramming():
"""
LinearProgramming defines and solves a LP problem.
"""
def __init__(self, *args):
"""
__init__ creates a LP problem.
"""
try:
pro... | StarcoderdataPython |
3415290 | import tetris_blocks
import numbersforscore
import color
class NumberToBlock:
@staticmethod
def get_block(number: int):
numbers_list = NumberToBlock.get_list_of_single_numbers(number)
blocks = []
for number in numbers_list:
block = numbersforscore.NumbersForScore.number[nu... | StarcoderdataPython |
9705617 | from functools import partial
from typing import Union, Dict, Optional
from http_async_client.enums import SupportedProtocols, Methods
import httpx
import re
from dataclasses import dataclass
from httpx._types import RequestContent, URLTypes, RequestData, RequestFiles, QueryParamTypes, HeaderTypes, CookieTypes
from nan... | StarcoderdataPython |
9658222 | import heapq
class Elem(object):
def __init__(self, x, y, reachable):
self.reachable = reachable
self.x = x
self.y = y
self.parent = None
self.g_cost = 0
self.h_cost = 0
self.f_cost = 0
class AStar(object):
def __init__(self, grid, start, end):
... | StarcoderdataPython |
3432699 | import pytest
import dowhy.datasets
from dowhy import CausalModel
class TestCausalModel(object):
@pytest.mark.parametrize(["beta", "num_instruments", "num_samples"],
[(10, 1, 100),])
def test_graph_input(self, beta, num_instruments, num_samples):
num_common_causes = 5
... | StarcoderdataPython |
4882284 | <filename>pages/views.py
from django.shortcuts import render
from schedule.models import Routine,Schedule
from schedule.views import get_routine
from academicnotice.models import AcademicNotice
from ClassNotice.models import ClassNotice
from Assignments.models import Assignments
# Create your views here.
def HomePageV... | StarcoderdataPython |
1720472 | <reponame>ankur198/TravelLite
# Generated by Django 2.0.4 on 2018-05-07 05:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('travellite', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='hotel... | StarcoderdataPython |
3204172 | from .academicIO import AnalogInput, AnalogOutput, DigitalInputOutput, Encoder, PWM, LEDs, I2C, SPI, ButtonIRQ, DIIRQ, AIIRQ, TimerIRQ, UART, Button
from .enums import * | StarcoderdataPython |
3388382 | <gh_stars>0
# Python
import os
import sys
import traceback
# Pycompss
from pycompss.api.task import task
from pycompss.api.parameter import FILE_IN, FILE_OUT
# Adapters commons pycompss
from biobb_adapters.pycompss.biobb_commons import task_config
# Wrapped Biobb
from biobb_md.gromacs.grompp import Grompp # Importing ... | StarcoderdataPython |
1603879 | from multiprocessing import Process
import os
import time
# git remote set-url origin https://mgrecu35@github.com/mgrecu35/cmbv7.git
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def fsh(fname):
cmb1=fname... | StarcoderdataPython |
4900986 | import hashlib
from hvm import constants
from hvm.utils.numeric import (
ceil32,
)
def sha256(computation):
word_count = ceil32(len(computation.msg.data)) // 32
gas_fee = constants.GAS_SHA256 + word_count * constants.GAS_SHA256WORD
computation.consume_gas(gas_fee, reason="SHA256 Precompile")
in... | StarcoderdataPython |
5003278 | from sklearn import preprocessing
from xgboost import XGBClassifier
from classifiers.abs_classifier import ABSClassifier
class XGBoostScaledOptuna(ABSClassifier):
def __init__(self):
self.clf = XGBClassifier(booster="dart",
alpha=2.1585186469130006e-06,
... | StarcoderdataPython |
220483 | # точка в правоъгълник
# Проверка дали точка {x, y} се намира вътре в правоъгълника {x1, y1} – {x2, y2}. Входните данни се четат от конзолата и се състоят от 6 реда:
# десетичните числа x1, y1, x2, y2, x и y (като се гарантира, че x1 < x2 и y1 < y2).
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = flo... | StarcoderdataPython |
353550 | import argparse
import os
description="""
Quick-and-dirty way of simulating a beam profile by using an arbitrary
number of processed. The principle of operation is to divide the discrete
simulation grid into N equal sizes (outer index).
"""
if __name__ == "__main__":
parser = argparse.ArgumentParser(... | StarcoderdataPython |
6575815 | <reponame>readerbench/ReaderBench<gh_stars>1-10
from enum import Enum, auto
from rb.core.pos_features.pos_feature import POSFeature
from rb.core.pos_features.ro_pos_features.ro_features_name import RoFeaturesName
from rb.core.lang import Lang
from rb.core.pos import POS
from typing import List
import re
class RoNumTy... | StarcoderdataPython |
9747614 | <filename>DeepFilterNet/df/scripts/test_df.py
#!/usr/bin/env python
import os
import unittest
from typing import Dict, List, Union
import numpy as np
import torch
from loguru import logger
import df
from df.enhance import DF, enhance, init_df, load_audio
from df.evaluation_utils import composite, si_sdr_speechmetric... | StarcoderdataPython |
156573 | import math
t = int(input())
result = []
for _ in range(t):
T1,T2,R1,R2 = map(int, input().split())
if ((math.pow(T1,2)/math.pow(R1,3)) == (math.pow(T2,2)/math.pow(R2,3))):
result.append("Yes")
else:
result.append("No")
print(*result, sep = "\n") | StarcoderdataPython |
247704 | <reponame>pasmuss/cmssw<filename>RecoMuon/Configuration/python/RecoMuonPPonly_cff.py
import FWCore.ParameterSet.Config as cms
# Seed generator
from RecoMuon.MuonSeedGenerator.standAloneMuonSeeds_cff import *
# Stand alone muon track producer
from RecoMuon.StandAloneMuonProducer.standAloneMuons_cff import *
# refitte... | StarcoderdataPython |
3260224 | import os
import unittest
from tests.config_reader import read_tpc_config
from wbtools.lib.nlp.literature_index.textpresso import TextpressoLiteratureIndex
@unittest.skipIf(not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data",
"loca... | StarcoderdataPython |
8057235 | <gh_stars>10-100
from .utils import execute_code
def test_LDA_LDM():
program = '''
.data
.teststr string 'Hello'
.testnum 20
.memory_loc 500
.text
.global main:
main:
LDV A, .testnum
LDM A, .memory_loc
LDA B, .memory_loc
HLT
... | StarcoderdataPython |
11277476 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | StarcoderdataPython |
5138931 | from django.contrib import admin
from api.models import DevEvent,DevEventType,DevProject,WeekSummary,SaleActiveType,SaleCustomer,SalePhase,SaleTarget,SaleEvent
import xadmin
# Register your models here.
#class FelixProjectsAdmin(admin.ModelAdmin):
# class ApiProjectsAdmin(object):
# list_display = ('pj_name', 'pj_g... | StarcoderdataPython |
223495 | # --------------------------------------------------------------------------------------
# Copyright 2020 by Oculy Authors, see git history for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# -------------------------------... | StarcoderdataPython |
1897095 | <filename>src/python/nimbusml/tests/pipeline/test_pipeline_get_schema.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------... | StarcoderdataPython |
5117905 | <filename>src/bpp/tests/tests_legacy/test_util.py
# -*- encoding: utf-8 -*-
from django.test import TestCase
from model_mommy import mommy
from bpp.models import Autor
from bpp.util import get_copy_from_db, has_changed, slugify_function
class TestUtil(TestCase):
def test_slugify_function(self):
test = "... | StarcoderdataPython |
173795 | """Collection of apicast gateways with different deployments or options"""
# flake8: noqa
from .system import SystemApicast, SystemApicastRequirements
from .containers import ContainerizedApicast
from .operator import OperatorApicast, OperatorApicastRequirements
from .selfmanaged import SelfManagedApicast, SelfManagedA... | StarcoderdataPython |
3477627 | # -*- coding: utf-8 -*-
"""
.. _tutorial06_ref:
Tutorial 6: Regions and Parcellations
=====================================
This tutorial demonstrates how to plot brain regions.
Regions and parcellations can be plotted with ``brainplot`` as one or more
layers, and it's possible to add region outlines by simply addi... | StarcoderdataPython |
374265 | '''
(ab)uses wheresmycellphone.com to call a phone
'''
import urllib2,urllib,sys,time
def usage():
print '''
Dials a phone number at specified intervals forever (until ctrl+c).
Usage: callme.py <number> <delay>
E.G.: callme.py 3015551234 90
Number: A phone number, no punctuation or spaces
Delay: How many seconds... | StarcoderdataPython |
6542744 | # Set up your imports here!
# import ...
from flask import Flask
app = Flask(__name__)
@app.route('/') # Fill this in!
def index():
# Welcome Page
# Create a generic welcome page.
return "<h1>Welcome! Go to /puppy_latin/name to see your name in puppy latin!</h1>"
@app.route('/puppy_latin/<name>') # Fill... | StarcoderdataPython |
3249328 | <reponame>ic-labs/django-icekit<filename>icekit_events/migrations/0007_type_fixtures.py<gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def make_type_fixtures(apps, _):
EventType = apps.get_model("icekit_events", "EventType")
EventType.... | StarcoderdataPython |
1840950 | <reponame>gampel/neutron<filename>neutron/plugins/ofagent/agent/flows.py
# Copyright (C) 2014 VA Linux Systems Japan K.K.
# Copyright (C) 2014 <NAME> <yamamoto at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complia... | StarcoderdataPython |
3395587 | <gh_stars>0
from datetime import datetime, date
from decimal import Decimal
from typing import Optional, List
from fastapi import APIRouter, Depends
from sqlmodel import Field, SQLModel
from ...db import get_session
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
router = APIRouter()
... | StarcoderdataPython |
6559865 | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
url = models.TextField()
image = models.ImageField(upload_to='images/')
hunter = models.Forei... | StarcoderdataPython |
5092145 | <filename>venv/lib/python3.6/site-packages/ansible_collections/community/hrobot/plugins/module_utils/failover.py
# -*- coding: utf-8 -*-
# Copyright (c), <NAME> <<EMAIL>>, 2019
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_im... | StarcoderdataPython |
4836785 | from connect_Db import Connect_db
import mysql.connector
from termcolor import colored
from prettytable import PrettyTable
from Validation import Validations
from os import system
class Tb_profil:
Valid = Validations()
conn = Connect_db()
#method untuk menampilkan data, dimana pada method ini... | StarcoderdataPython |
8125162 | import numpy as np
from ._single_layer_model import SingleLayerModel
from ._classifier import Classifier
from . import _functions
class LogisticRegression(SingleLayerModel, Classifier):
'''
Implements logistic regression for classification.
'''
def __init__(self, input_size, output_size, reg_param=0):... | StarcoderdataPython |
11210717 | class OECS(object):
def __init__(self, window, view, state_loader, entity_manager, system_manager, input_manager, asset_manager):
"""
@param window The SFML window object that the state is to be loaded onto.
@param view This is SFML's View object and allows us to zoom in on the what would be sh... | StarcoderdataPython |
388372 | #-*-coding:utf8-*-
import copy, os
from gen_conf_file import *
from dataset_cfg import *
def gen_nbp_lstm(d_mem, init, lr, dataset, l2, max_norm2, negative_num):
net = {}
ds = DatasetCfg(dataset)
g_filler = gen_uniform_filter_setting(init)
zero_filler = gen_zero_filter_setting()
g_upda... | StarcoderdataPython |
4887390 | import os
import errno
from cse.util import PackerUtil
from bisect import bisect_left
class DocumentMap(object):
def __init__(self, document_map_index, document_map_dict):
if not os.path.exists(os.path.dirname(document_map_index)):
try:
os.makedirs(os.path.dirname(document_map_... | StarcoderdataPython |
1651190 | responses.mock.assert_all_requests_are_fired = True
class MarketoApi(unittest.TestCase):
@responses.activate
def test_auth(self):
marketo_auth_url = "".join(["https://066-eov-335.mktorest.com/", "identity/oauth/token?", "grant_type=client_credentials&client_id=123", "&client_secret=321"])
marketo_auth_payload = {... | StarcoderdataPython |
4954327 | <reponame>LocalghostFI/MuurameAllsky
#!/usr/bin/python
import http.client
import httplib2
import os
import random
import sys
import time
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from ... | StarcoderdataPython |
286235 | <filename>src/rubrix/server/users/api.py
from fastapi import APIRouter, Depends
from rubrix.server.security.api import get_current_active_user
from .model import User
router = APIRouter(tags=["users"])
@router.get(
"/me",
response_model=User,
response_model_exclude_none=True,
operation_id="whoami",
... | StarcoderdataPython |
12856143 | <reponame>fiee/croisee<filename>croisee/croisee/models.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import unicodedata
import re, os
import logging
from django.utils.translation import ugettext_lazy as _
from django.db import models
from... | StarcoderdataPython |
1974277 | <reponame>UrosOgrizovic/FIFA-19-player-position-predictor<gh_stars>1-10
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import globals as GLOBALS
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
def plot_number_of_players_by_position(players):
sns.set(style="darkgrid... | StarcoderdataPython |
3517338 | # https://www.hackerrank.com/challenges/simple-array-sum
import sys
if __name__ == '__main__':
f = sys.stdin
n = int(f.readline())
numbers = list(map(int, f.readline().strip().split()))
print(sum(numbers))
| StarcoderdataPython |
4840457 | # -*- coding: utf-8 -*-
"""
Application Constants, Defualt Values
:author: <NAME>
:version: 0.1
:date: 14 Sep. 2017
"""
__docformat__ = "restructuredtext"
SCENARIO_NAME = "PlanHeat"
SCENARIO_VERSION = 15
CONFIG_FILE_PATH="/config/"
CONFIG_FILE_NAME="PlanHeat.cfg"
TEMP_DIR_PATH="temp"
LOG_DIR_PAT... | StarcoderdataPython |
1892880 | import numpy as np
import os
import pandas as pd
'''
Takes in a pair file of .ades and .dat and extracts the channel names and the corresponding SEEG time series
places them into four different files
- raw numpy
- headers csv
- annotations csv
- channels csv
Which follows format that we place data from .edf files. M... | StarcoderdataPython |
321067 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-12-20 17:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ping', '0006_auto_20180113_0247'),
]
operations = [
migrations.RemoveField... | StarcoderdataPython |
4818468 | import copy
n = int(input())
v = input().split()
x = []
y = []
for i in range(n):
if i % 2 == 0:
x.append(v[i])
else:
y.append(v[i])
x.sort()
y.sort()
q = []
r = []
s = []
t = []
countx = 1
county = 1
for j in range(int(n / 2)):
if x[j - 1] == x[j] and j != 0:
countx += 1
if... | StarcoderdataPython |
305709 | '''
Implementation of the paper 'Tensorizing Neural Networks', <NAME>, <NAME>, <NAME>, <NAME>, NIPS, 2015
to compress a dense layer using Tensor Train factorization.
TTLayer compute y = Wx + b in the compressed form.
'''
from keras import backend as K, activations, initializers
from keras.engine.topology import Layer
i... | StarcoderdataPython |
3407295 | class SubscriptionItem(object):
def __init__(self, name=None, state=None):
self.name = name
self.state = state
def __str__(self):
return self.name
| StarcoderdataPython |
78967 | import pytest
from multi_bracket_validation import multi_bracket_validation
def test_mbv_true_case_simple():
"""test function on balanced str"""
assert multi_bracket_validation('[{()}]') == True
def test_mbv_true_case_empty_str():
"""test function with empty string"""
assert multi_bracket_validation('... | StarcoderdataPython |
54466 | #!/usr/bin/env python3
import getpass
import json
import pprint
import requests
import sys
# The credentials to be used
try:
user = input('Login name: ')
# If it's a tty, use the version that doesn't echo the password.
if sys.stdin.isatty():
password = getpass.getpass('Password: ')
else:
... | StarcoderdataPython |
4870274 | <reponame>aerostone/vdebug
import unittest
import vdebug.connection
class SocketMockError():
pass
class SocketMock():
def __init__(self):
self.response = []
self.last_msg = []
def recv(self,length):
ret = self.response[0]
if len(ret) >= length:
chars = ret[0:le... | StarcoderdataPython |
3592899 | <gh_stars>1-10
# The MIT License (MIT)
# Copyright (c) 2015 <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 u... | StarcoderdataPython |
5049121 | <filename>238. Product of Array Except Self.py
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
p = 1
res = []
for n in nums:
res.append(p)
p *= n
p = 1
print(res)
for i in range(len(nums)-1,-1,-1):
... | StarcoderdataPython |
1943381 | import os
import datetime
import argparse
import numpy as np
import tensorflow as tf
from fpointnet_tiny_functional import get_compiled_model
FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0])
def read_raw_data(data_path, allowed_class, sample_limit=None):
data_filenames = sorted(os.listdir(data_path))
data_fi... | StarcoderdataPython |
5083640 | from __future__ import print_function
# Copyright (C) 2015-2016 Regents of the University of California
#
# 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/... | StarcoderdataPython |
3213826 | from django.core.management.base import BaseCommand
from RecommenderModule import recommendations_provider
class Command(BaseCommand):
"""Train and save popularity lists for popularity recommender."""
def add_arguments(self, parser):
parser.add_argument('min_ratings_threshold', type=int, n... | StarcoderdataPython |
9684038 | #
import warnings
from typing import Any, Dict, Optional
BALANCE_WARNING = ("Backend {} uses a haproxy balance method {}, " "forcing to `roundrobin`.")
MAP_HOST_WARNING = ("Frontend {} map contains multiple host matches, " "only `hostReg` will be used. ({})")
MAP_PATH_WARNING = ("Frontend {} map contains multiple p... | StarcoderdataPython |
9759577 | from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import pytest
@pytest.fixture(autouse=True)
def browser(request):
user_language = request.config.getoption("--language")
options = Options()
options.add_experimental_option('prefs', {'intl.accept_languages': user_language}... | StarcoderdataPython |
11225488 | """Convert SPRESI RD file to UDM."""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
import datetime
import re
import sys
from collections import namedtuple
from ctutils import clean_molecule
from rdfutils import FileFormatException, rdfile_reader
import udm
# We represent citations a... | StarcoderdataPython |
6617359 | <gh_stars>1-10
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
from gensim import corpora
def build_lsi_model(data_path="sentences.txt",stopwords_path="stopwords_english.txt",save_dict_path="model_dict.dict",save_corpus_path="model_corpus.mm"):
documents =... | StarcoderdataPython |
1673455 | <reponame>N0mansky/countbeat<filename>vendor/github.com/elastic/beats/filebeat/tests/system/filebeat.py<gh_stars>10-100
import json
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../libbeat/tests/system'))
from beat.beat import TestCase
class BaseTest(TestCase):
@classmetho... | StarcoderdataPython |
5105215 | <filename>cassie/env/play.py
import gym
import time
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import SubprocVecEnv
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.results_plotter import load_results, ts2xy, plot_results
from cassie import CassieRef... | StarcoderdataPython |
6463159 |
# Write a function that selects a random number and then asks the user to guess what that number is.
# They should be told if they are higher or lower than the result, track the number of guesses they take to get the correct value.
# If they do not guess correctly, ask them again until they do.
from ... | StarcoderdataPython |
6548735 | <gh_stars>0
# Is Unique
# Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
def isUnique(text_string):
if(len(set(text_string)) == len(text_string)):
return True
return False
# Sort string approach
def isUniqueNoDS(text_stri... | StarcoderdataPython |
3326388 | """
L2 integration tool methods
"""
from cobra_apic_base import cobra_apic_base
from cobra.model.fv import Tenant, BD, Subnet, AEPg, Ap, RsProv, RsCons, RsDomAtt, RsPathAtt, RsCtx, RsPathAtt
from cobra.mit.request import ClassQuery
from cobra.modelimpl.fabric.protpol import ProtPol
from cobra.modelimpl.fvns.encapblk ... | StarcoderdataPython |
1871183 | <reponame>allenyummy/GoodInfo<filename>src/entry_goodinfo.py
# encoding=utf-8
# Author: <NAME>
# Description: Example code
import argparse
import logging
import os
import sys
from tqdm import tqdm
from src.utils.struct import GoodInfoStruct
from src.utils.utility import readJson, writeJson
from src.crawler.goodinfo.g... | StarcoderdataPython |
12802863 | import boto3
GLUE = boto3.client('glue')
def lambda_handler(event, context):
crawler_name = event["crawler_name"]
crawler_info = GLUE.get_crawler(Name=crawler_name)
current_state = crawler_info['Crawler']['State']
if current_state == 'READY':
GLUE.start_crawler(Name=crawler_name)
pr... | StarcoderdataPython |
8135070 | import unittest
from core.workflow_manager import WorkflowManager
from uuid import uuid4
class TestDialog:
def __init__(self, id):
self.id = id
class TestService:
def __init__(self, name):
self.name = name
class TestWorkflowManagerDialog(unittest.TestCase):
def setUp(self):
sel... | StarcoderdataPython |
3303628 | from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(('priceapi.urls', 'priceapi'), namespace='priceapi')),
]
| StarcoderdataPython |
321702 | from flask import Flask, jsonify
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine, func
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
Base = automap_base()
Base.prepare(engine, reflect=True)
Measurement = Base.classes.measurement
Stat... | StarcoderdataPython |
6459192 | import logging
from cryptoadvance.specter.cli import server
from click.testing import CliRunner
import sys
import traceback
import mock
from mock import patch, MagicMock, call
mock_config_dict = {
"PORT": "123",
"DEBUG": "WURSTBROT",
"SPECTER_SSL_CERT_SUBJECT_C": "AT",
"SPECTER_SSL_CERT_SUBJECT_ST": ... | StarcoderdataPython |
6492788 | <gh_stars>0
'''Basic simulation unittest'''
import tests
import model.user
from unittest import TestCase
class TestSubmit(TestCase):
@tests.async_test
async def test_submit(self):
await model.user.create('admin', '<PASSWORD>', 'Admin',
level=model.user.UserLevel.kernel)
respons... | StarcoderdataPython |
5068718 | <gh_stars>1-10
# Based on https://github.com/google-coral/project-bodypix/blob/master/gstreamer.py
from functools import partial
import sys
import time
import numpy as np
import gi
gi.require_version("Gst", "1.0")
gi.require_version("GstBase", "1.0")
from gi.repository import GLib, GObject, Gst, GstBase
GObject.thr... | StarcoderdataPython |
3538630 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | StarcoderdataPython |
6415147 | import os
os.system("sudo service redis-server start")
from telethon import TelegramClient, events, Button, extensions, functions, types
from os.path import dirname, realpath, join
import re
import asyncio
import datetime
from utilities import utilities
import json
loop = asyncio.get_event_loop()
utilitie... | StarcoderdataPython |
11242061 | import pytest
from django.test import Client
class AccountObjects:
def __init__(self, handle):
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from fullctl.django.auth import permissions
from fullctl.django.models import Organization, Organ... | StarcoderdataPython |
3405543 | <reponame>aapalo/aoc2020<filename>1/code.py
#!/usr/bin/python3
#from collections import Counter
#import re
#import os
import time
#from collections import defaultdict
#from collections import deque
''' ####### '''
date = 1
dev = 0 # extra prints
part = 3 # 1,2, or 3 for both
samp = 0 # 0 or 1
''' #######... | StarcoderdataPython |
6559236 | from conans import ConanFile, CMake, tools
class FoobarConan(ConanFile):
name = "foobar"
version = "0.1.0"
license = "MIT"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False], "installer": ["deb", "rpm", "tgz", "zip"]}
default_options = "shared=False", "install... | StarcoderdataPython |
277084 | #!/usr/bin/python3
import argparse
import os
import sys
from src.util import Util
from src.step2.program import Program, ProgramRegex
from src.LR0Parser import LR0Parser
from src.grammar import Grammar
from src.log import Log
import re
if __name__ == '__main__':
grammar = Grammar.from_lines(Util.get_lines_filena... | StarcoderdataPython |
3571879 | #!/home/nickolai/python/taint-2.6/python
import os
import sys
class Taint:
def __init__(self, *l):
self.l = []
self.l.extend(l)
def merge(self, other):
n = Taint()
n.l.extend(self.l)
n.l.extend(other.l)
return n
def export_check(self, f):
pass
def pt(s):
print s
print s.__taint__.l
x = "... | StarcoderdataPython |
3339780 | <gh_stars>1-10
from setuptools import setup, find_packages
with open("README.md") as f:
readme = f.read()
with open("gym/__init__.py") as f:
for line in f:
if line.startswith("__version__"):
version = line.split('"')[1]
setup(
name="gym",
version="0.3.0",
description="Gym - VN... | StarcoderdataPython |
11334787 | print("Hello User")
name = input("What is your name?")
print("Hello " + name + "!")
age1 = input("What is your age?")
if int(age1) > 50:
print("Ah... A well traveled soul are ye.")
else:
print("Awwww you're just a baby")
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.