id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
9625503
# Checking for each interval the next intervals if has start # lower then actual end def rooms(intervals): min_rooms = 0 for key, value in enumerate(intervals): lesson = intervals[key] required = 1 for vm in intervals: if vm[0] > lesson[1]: required += 1 ...
StarcoderdataPython
1805749
import json import random from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union, cast import pytorch_lightning as pl import torch import torch.utils.data from nuplan.planning.training.callbacks.utils.scene_converter import SceneConverter from nuplan.planning.training.data_loader.scenario...
StarcoderdataPython
12842241
<gh_stars>1-10 # Generated by Django 2.0 on 2018-01-29 07:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('datatrans', '0004_alias_registration_fields_optional'), ] operations = [ migrations.AlterField( model_name='aliasre...
StarcoderdataPython
3226616
<filename>recomendation system/content.py __author__ = 'lily' import numpy as np from sklearn.decomposition import ProjectedGradientNMF import recsys import evaluate import similarity from sklearn import decomposition from numpy.linalg import inv from sklearn.metrics.pairwise import pairwise_distances #feature helper ...
StarcoderdataPython
3480255
from __future__ import print_function import numpy from amuse.lab import * from amuse.couple import bridge from matplotlib import pyplot class MilkyWay_galaxy(object): def get_gravity_at_point(self, eps, x,y,z): phi_0 = self.get_potential_at_point(eps, x,y,z) grav = AdaptingVectorQuantity() ...
StarcoderdataPython
64871
# # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # 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
4832898
import base64 import urllib.parse from django.test import Client, TestCase from django.urls import reverse from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site from secrets.models import Secret, SecretRole, SessionKey, UserKey from utilities.testing import create_test_user from .constants import...
StarcoderdataPython
6487778
<reponame>andreped/annotationweb # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2019-05-15 09:48 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('annotat...
StarcoderdataPython
4997168
# Generated by Django 2.1.7 on 2020-02-10 10:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0022_auto_20200210_1005'), ] operations = [ migrations.RenameField( model_name='user', old_name='image', ...
StarcoderdataPython
8191376
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
StarcoderdataPython
9661957
from Classes.Logic.LogicCommandManager import LogicCommandManager from Classes.Packets.PiranhaMessage import PiranhaMessage class AvailableServerCommandMessage(PiranhaMessage): def __init__(self, messageData): super().__init__(messageData) self.messageVersion = 0 def encode(self, fields): ...
StarcoderdataPython
1850045
import unittest from blahtex import Blahtex, BlahtexException class TestAll(unittest.TestCase): def test_convert(self): bt = Blahtex() self.assertEqual( bt.convert("\sqrt{3}"), '<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><msqrt><mn>3</mn></msqrt></mat...
StarcoderdataPython
177584
<reponame>Animenosekai/yuno<filename>yuno/utils/annotations.py """ annotations.py Manages annotations utilities. """ import typing class Default(): """A default value for a function call""" def __init__(self, value: typing.Any = None) -> None: """ A class representing the default value for ...
StarcoderdataPython
1685831
<filename>latte/monkey_patches/frappe/model/naming.py # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import now_datetime, cint, cstr import re from six import string_types f...
StarcoderdataPython
11353288
# -*- coding:utf-8; python-indent:2; indent-tabs-mode:nil -*- # Copyright 2013 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/...
StarcoderdataPython
6626008
<filename>genmotion/render/c4d/params.py # Get skeleton information from https://meshcapade.wiki/SMPL#smpl-x SMPL_SKELETON = { 0: 'Pelvis', 3: 'Spine1', 6: 'Spine2', 9: 'Spine3', 12: 'Neck', 15: 'Head', 1: 'L_Hip', 4: 'L_Knee', 7: 'L_Ankle', 10: 'L_Foot', 2: 'R_Hip', 5...
StarcoderdataPython
4815989
<reponame>RussianNLP/WikiOmnia<filename>filtering_rus/data/language_checker.py from langid.langid import LanguageIdentifier from langid.langid import model as lang_ident class CheckRussian: """ Check if a text is in Russian. (Only for first 100 characters of text: 1) in order to make it faster 2) not Russ...
StarcoderdataPython
3441294
import pytz import unittest from airflow.models import DAG, TaskInstance, XCom, DagRun, DagTag, DagModel from airflow.models.xcom import XCOM_RETURN_KEY from airflow.operators.dummy import DummyOperator from airflow.utils.session import create_session, provide_session from airflow.utils.state import State from datetime...
StarcoderdataPython
4808147
<filename>bugbuster/cmd/__init__.py import sys from oslo.config import cfg from bugbuster.utils import gerrit CONF = cfg.CONF opts = [ cfg.StrOpt('exceptions', default='./exceptions.txt', help='Exceptions file'), ] CONF.register_opts(opts) EXCEPTIONS = ["128497"] def main(): ...
StarcoderdataPython
4993218
<reponame>PacktPublishing/PySpark-and-AWS-Master-Big-Data-with-PySpark-and-AWS # Databricks notebook source from pyspark.streaming import StreamingContext from pyspark import SparkConf, SparkContext conf = SparkConf().setAppName("Streaming") sc = SparkContext.getOrCreate(conf=conf) ssc = StreamingContext(sc, 1) # CO...
StarcoderdataPython
5045304
# Generated by Django 3.2.11 on 2022-01-12 08:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracking', '0002_auto_20190516_1146'), ] operations = [ migrations.AlterField( model_name='applicationtracking', na...
StarcoderdataPython
4910415
<filename>SERVER/src/client.py import socket from random import randint from threading import Thread from json import dumps, loads clients = {} class Client: def __init__(self, id:int, conn, addr) -> None: clients[str(id)] = self self.id = str(id) ...
StarcoderdataPython
1675498
<reponame>shubh2ds/DSA_Python def partition_for_quick_sort(arr,sidx,eidx): pivot=arr[sidx] c=0 for i in range(sidx,eidx+1): if arr[i]<pivot: c=c+1 arr[sidx+c],arr[sidx] = arr[sidx],arr[sidx+c] pivot_idx=sidx+c i=sidx j=eidx while i<j: if arr[i]<pivot: i=i+1 elif arr[j]>=pivot: ...
StarcoderdataPython
4966403
<reponame>FengYen-Chang/ImageCaptioning<filename>pytorch/sample.py import torch import matplotlib.pyplot as plt import numpy as np import argparse import pickle import os from torchvision import transforms from build_vocab import Vocabulary from model import EncoderCNN, DecoderRNN, Embed, DecoderRNN2 from PIL import...
StarcoderdataPython
9625602
import os import time from collections import defaultdict class DeterministicDie: def __init__(self): self.curr = 0 self.rolls = 0 def roll(self): if self.curr == 100: self.curr = 1 else: self.curr += 1 self.rolls += 1 return self.curr ...
StarcoderdataPython
254776
<reponame>pablogo1/wallet # Generated by Django 4.0.1 on 2022-01-10 07:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wallet', '0001_initial'), ] operations = [ migrations.AlterField( model_name='account', na...
StarcoderdataPython
12829371
from .science import *
StarcoderdataPython
5186614
<gh_stars>10-100 import re import sys import mapnik # mapnik_utils from mapnik_utils.projection import EasyProjection if not hasattr(mapnik,'ProjTransform'): from compatibility import ProjTransform BoostPythonMetaclass = mapnik.Coord.__class__ class _injector(object): class __metaclass__(Bo...
StarcoderdataPython
1675709
<filename>landlibrary/importers/AGRIS/agris/LandVoc/landvoc.py #!/usr/bin/python # -*- coding: UTF-8 -*- import os import csv class LandVoc(object): def __init__(self): basepath = os.path.dirname(__file__) self.concepts_and_fixed_relations, self.uris_to_concepts = self.process_landvoc_file(self._...
StarcoderdataPython
324839
<filename>test/core_tests/test_parameters.py import warnings from amuse.test import amusetest from amuse.support.exceptions import AmuseException, AmuseWarning from amuse.units import nbody_system, generic_unit_system, generic_unit_converter from amuse.units import units from amuse.datamodel import parameters from amu...
StarcoderdataPython
4994474
# coding=utf-8 from torch import nn from torch.nn import functional as F class CNN(nn.Module): def __init__(self, configuration): super(CNN, self).__init__() self.conv1 = nn.Conv2d(configuration['input_channels'], 32, kernel_size=8, stride=4) self.conv2 = nn.Conv2d(32, 64, ker...
StarcoderdataPython
126664
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
StarcoderdataPython
6415609
<filename>visualization/questions.py class VisualizeQuestions(object): def __init__(self): from preprocessor.database import Database database = Database( 'host', 'db', 'user', 'pass', 'utf8mb4' ) self.connection = databas...
StarcoderdataPython
138718
<gh_stars>0 import json import unittest from botocore.exceptions import WaiterError, ClientError from mock import patch, MagicMock, mock_open from Hummingbird.errors import SchedulerException from Hummingbird.hummingbird_utils import PLATFORM from Hummingbird.scheduler import AWSBatchScheduler from Hummingbird.instan...
StarcoderdataPython
12840369
<gh_stars>0 # -*- coding: utf-8 -*- """ --- Day 10: The Stars Align --- It's no use; your navigation system simply isn't capable of providing walking directions in the arctic circle, and certainly not in 1018. The Elves suggest an alternative. In times like these, North Pole rescue operations will arrange points of li...
StarcoderdataPython
9789030
import numpy as np import innvestigate import innvestigate.utils as iutils def isi(model, indicator, x, y=None, max_iter=30, norm=0, batch_size=100, **kwargs): """ Input Significance Indicator based Attack, two indicators: sensitivity and relevance are included. Relevance-based attack supports l0,l2 or l...
StarcoderdataPython
1802108
<gh_stars>0 import os import json import time import smtplib import threading import firebase_admin from firebase_admin import credentials from firebase_admin import firestore from firebase_admin import auth from email.message import EmailMessage # Use the application default credentials jsonKey = json.load(open('Serv...
StarcoderdataPython
8004920
<gh_stars>100-1000 import sublime from subprocess import call class LinuxBrowserRefresh: def __init__(self, activate_browser): # activate_browser is always true on Windows since you can't # send keys to an inactive window programmatically. We ignore it. self.activate_browser = activate_bro...
StarcoderdataPython
11327318
from datetime import datetime from bs4 import BeautifulSoup import requests from fake_useragent import UserAgent from celery.utils.log import get_task_logger from fuck_papers.models import Paper, Category, Message, User from fuck_papers.extensions import db from fuck_papers import celery, flask_app logger = get_tas...
StarcoderdataPython
12853039
<gh_stars>0 # -*- coding: utf-8 -*- import click from github import Github from github.GithubException import RateLimitExceededException def main(): cli(obj={}) def get_repos(key, org, repo, url): if url: g = Github(key, base_url=url) else: g = Github(key) if org: g_org = g.g...
StarcoderdataPython
9747398
<filename>src/mtl_trainer.py import os import logging from dataclasses import dataclass, field from typing import Dict, Optional, Callable, Tuple import torch import numpy as np from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torch.utils.data.distributed import Dist...
StarcoderdataPython
3344703
<reponame>rhyswhitley/savanna_iav<filename>src/figures/modchecks/water_limits.py<gh_stars>0 #!/usr/bin/env python2 import os import seaborn as sns import numpy as np import pandas as pd import cPickle as pickle import matplotlib.pyplot as plt #from matplotlib import style def main(): """ Does a quick re-sampl...
StarcoderdataPython
3483831
from __future__ import absolute_import import os from celery import Celery, signals # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # django.setup() app = Celery('celery_uncovered') # Using a string here means...
StarcoderdataPython
110820
from .Workbook import Workbook from .Style import Style from .Fill import Fill from .Font import Font from .Format import Format from .Alignment import Alignment try: import pkg_resources __version__ = pkg_resources.require('PyExcelerate')[0].version except: __version__ = 'unknown'
StarcoderdataPython
3223702
#!/usr/bin/env python # # Copyright (c) 2019, Arista Networks EOS+ # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # ...
StarcoderdataPython
1626842
from setuptools import setup package_name = 'turtlesim_robotics' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], ...
StarcoderdataPython
6693784
import pytest import networkx as nx from floweaver.ordering import (flatten_bands, unflatten_bands, band_index, new_node_indices, median_value, neighbour_positions, fill_unknown, Ordering) def test_ordering_normalisation(): o1 = Ordering([['a', 'b...
StarcoderdataPython
5176179
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import numpy as np import popart import json import pytest # `import test_util` requires adding to sys.path import sys from pathlib import Path sys.path.append(str(Path(__file__).resolve().parent.parent)) import test_util as tu def reshape(builder, x, outshape...
StarcoderdataPython
11220836
class StockSpanner: # 1st: 460ms, 18.4MB def __init__(self): self.stack = [] def next(self, price: int) -> int: span = 0 while self.stack and self.stack[-1][0] <= price: span += self.stack.pop()[1] span += 1 self.stack.append((price, span)) return...
StarcoderdataPython
1688062
import os from os import listdir from tqdm import tqdm import json from collections import Counter import itertools import random import pandas as pd import numpy as np from sklearn.decomposition import PCA import tensorflow as tf import tensorflow_hub as hub import networkx as nx def get_papers_dict(areas:list, yea...
StarcoderdataPython
8087373
<filename>auditlog/admin.py from __future__ import absolute_import from __future__ import unicode_literals import json from django.contrib import admin from django.contrib.admin.util import flatten_fieldsets from django import forms from django.contrib.auth import get_user_model from django.utils.html import escape fr...
StarcoderdataPython
3308067
<filename>Server/covid.py from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException import time from bs4 import Beautifu...
StarcoderdataPython
3588196
<reponame>Lindronics/honours_project_dissertation import json import cv2 import numpy as np import matplotlib.pyplot as plt from yolov3 import get_anchors, bbox_iou class Dataset(): def __init__(self, config, training=False): self.input_size = config["TRAINING"]["INPUT_SIZE"] self.channels = con...
StarcoderdataPython
6471682
import os import argparse import numpy as np import matplotlib.pyplot as plt from robolearn.utils.plots import plot_multiple_process_iu_returns from robolearn.utils.plots import plot_process_iu_policies from robolearn.utils.plots import plot_process_iu_values_errors from robolearn.utils.plots import plot_process_genera...
StarcoderdataPython
1767755
<reponame>iuyoy/TaggedSearch<filename>Global/config.py #!/usr/bin/python # -*- coding:utf-8 -*- #author:iuyyoy #重要的全局变量 #输出等级 print_level = 0 #数据库信息 dbinfo={\ 'host' : 'localhost'\ ,'user' : 'root'\ ,'passwd' : '<PASSWORD>'\ ,'db' : 'wiki'\ ,'port' : 3306\ ,'charset' : 'utf8'\ } #dbinfo={\ #'host' : '192.168.99....
StarcoderdataPython
22100
#!/usr/bin/env python3 import fire import json import os import numpy as np import tensorflow as tf import model, sample, encoder def interact_model( model_name='117M', seed=None, nsamples=1000, batch_size=1, length=None, temperature=1, top_k=0, top_p=0.0 ): """ Interactively ...
StarcoderdataPython
1806223
<filename>FileManagementApp.py #cd C:\Python27\Lib\site-packages\PyQt4 #pyuic4 -x C:\Users\Gregoire\Documents\PythonCode\JCAP\JCAPCreateExperimentAndFOM\QtDesign\CreateExpForm.ui -o C:\Users\Gregoire\Documents\PythonCode\JCAP\JCAPCreateExperimentAndFOM\CreateExpForm.py import time, shutil import os, os.path import sys ...
StarcoderdataPython
1772695
<reponame>KathmanduLivingLabs/tasking-manager from backend.models.postgis.user import User, UserRole, MappingLevel from tests.backend.base import BaseTestCase class TestUser(BaseTestCase): def setUp(self): super().setUp() self.test_user = User() self.test_user.role = UserRole.MAPPER.value ...
StarcoderdataPython
5054417
# -*- coding: utf-8 -*- # # Copyright (c) 2019, <NAME>. All rights reserved. # ----------------------------------------------------------------------------- import unittest import os import json import vfxtest mock = vfxtest.mock # ----------------------------------------------------------------------------- class ...
StarcoderdataPython
5065873
<filename>keras_extra/utils/common.py #!/usr/bin/env python # -*- coding: utf-8 -*- #================================================================ # God Bless You. # # file name: common.py # author: klaus # email: <EMAIL> # created date: 2018/01/08 # description: # #======================================...
StarcoderdataPython
9619439
<reponame>AKSHANSH47/crowdsource-platform2<filename>crowdsourcing/serializers/template.py from crowdsourcing import models from rest_framework import serializers from crowdsourcing.serializers.dynamic import DynamicFieldsModelSerializer from rest_framework.exceptions import ValidationError class TemplateItemSerialize...
StarcoderdataPython
9691793
#!/usr/bin/env python3 import sys from tweet_dumper import * from analyzer import Analyzer from stats import Stats from tqdm import tqdm frequencies = [0, 0, 0] def main(): if len(sys.argv) != 3: sys.exit("Usage: ./tweet-sentiment <twitter username> <number of tweets to analyse>(without the <>)") username = sy...
StarcoderdataPython
3394225
import DirNav; import threading; import time; import os; results = list(); results2 = dict();#results dictionary of {result:path} no_d_threads = 0; #no. of completed d_threads no_f_threads = 0; #no. of completed f_threads class SearchThread(threading.Thread): def __init__(self,d_or_f,path,search_string): ...
StarcoderdataPython
1718008
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: <NAME> Created: 10/03/2017 Updated: 10/03/2017 # Description Unit tests for the functions in the ands.algorithms.dac.select module. """ import unittest from random import randint, sample, randrange from ands.algorithms.dac.select import sel...
StarcoderdataPython
8071915
from __future__ import division import os from labelit.command_line.imagefiles import ImageFiles class spotfinder_proxy: def __init__(self,old_spotfinder,phil,frames): self.frames = frames self.phil = phil self.old_pd = old_spotfinder.pd self.old_S = old_spotfinder def get_aitbx_inputs(self): p...
StarcoderdataPython
1771282
<filename>evaluation/scripts/performance/compare.py import os import json import argparse from sklearn import metrics def align(*args): keys = None for a in args: if keys is not None: keys &= set(a.keys()) else: keys = set(a.keys()) return [[a[k] for k in keys] f...
StarcoderdataPython
188127
from bs4 import BeautifulSoup from requests import get import math def search(term: str, num_results:int=10, lang: str="en", proxy: str="None", filter_results: bool=True): verbose=False usr_agent = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' ...
StarcoderdataPython
9630262
#1.只负责写视图 import os import datetime from flask import render_template from main import app from models import Curriculum#导入这个表 from flask import redirect#跳转 即Django中的重定向功能 import functools from flask import session from models import * class Calendar: """ 当前类实现日历功能 1、返回列表嵌套列表的日历 2、安装日历格式打印日历 # 如果一...
StarcoderdataPython
5088868
<filename>Dice Roller/dice.py import random def roll_dice(): numbers = '' for i in range(1, 7): numbers += str(i) selected_num = (random.choice(numbers)) print(f'Your dice is rolling! You got: {selected_num}') roll_dice()
StarcoderdataPython
9700183
<reponame>hase1128/dragonfly """ Tensorflow Code. """
StarcoderdataPython
1792834
"""Data Embedding algorithms for bitcoin addresses""" import hashlib from b58 import encode as base58_encode, decode as base58_decode TESTNET = True version = 0 if not TESTNET else 111 def embed_in_address(x): assert isinstance(x, bytes) assert len(x) == 20 return base58_check_encode(x, version) def ...
StarcoderdataPython
116805
"""Functions for using Gaussian Processes.""" import logging from typing import Callable, Tuple import numpy as np def zero_mean_initialise(x: np.ndarray, kernel_fun: Callable, noise=0.0) -> Tuple[np.ndarray, np.ndarray]: """Initialise a zero mean GP using the provided kernel function. Parameters -----...
StarcoderdataPython
9789131
<filename>src/core/mocfunctions.py from django.conf import settings from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from core.models import * import logging logger = logging.getLogger(__name__) # This array defines all the IDs in the database of the articles that are...
StarcoderdataPython
6446252
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #82. Remove Duplicates from Sorted List II #Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from t...
StarcoderdataPython
9744079
<reponame>paultag/billy from django.core import urlresolvers from django.template.defaultfilters import slugify from billy.core import mdb as db from billy.core import settings from .base import Document, RelatedDocument, RelatedDocuments, ListManager from .metadata import Metadata class CommitteeMember(dict): l...
StarcoderdataPython
9691019
<gh_stars>0 from quran.factory.audio_factory import AudioFactory from quran.factory.edition_factory import EditionFactory from quran.factory.image_factory import ImageFactory from quran.factory.surah_factory import SurahFactory from quran.factory.translation_factory import TranslationFactory from quran.repository.ayah_...
StarcoderdataPython
6505481
#! /usr/bin/python3 ''' Given one audio clip, output what the network thinks ''' from __future__ import print_function import numpy as np import librosa import os from os.path import isfile from panotti.models import * from panotti.datautils import * os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # less TF messages, thanks...
StarcoderdataPython
6520200
<reponame>Cobliteam/cassandra-s3-incremental-backup-watcher<gh_stars>1-10 from __future__ import absolute_import, unicode_literals import argparse import json import logging import os import re import shlex import subprocess import boto3 from .util import clean_s3_path from .sstable import traverse_data_dir from .tr...
StarcoderdataPython
9613136
<filename>python_programs/breadth_first_search_test.py from .node import Node from .breadth_first_search import breadth_first_search def test_main(): # Case 1: Strongly connected graph # Output: Path found! station1 = Node("Westminster") station2 = Node("Waterloo", None, [station1]) station3 = Nod...
StarcoderdataPython
304466
<filename>solutions/treachery_of_whales.py """ Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? """ from dataclasses import dataclass from typing import Callable, List, Optional def constant_burn(units: int) -> int: ...
StarcoderdataPython
3258773
<gh_stars>0 height = int(input()) x = 1 for i in range(1,height): for j in range(1,i+1): print(x,end="# ") x += 1 print() # Sample Input :- 5 # Output :- # 1# # 2# 3# # 4# 5# 6# # 7# 8# 9# 10#
StarcoderdataPython
86981
# -*- coding: utf-8 -*- # pylint: disable=missing-docstring import io import json from pathlib import Path import shutil import tempfile import uuid from app.modules.users.models import User from app.modules.fileuploads.models import FileUpload from PIL import Image from tests.utils import TemporaryDirectoryGraceful ...
StarcoderdataPython
355772
<filename>pytglib/api/types/text_entity_type_bot_command.py from ..utils import Object class TextEntityTypeBotCommand(Object): """ A bot command, beginning with "/". This shouldn't be highlighted if there are no bots in the chat Attributes: ID (:obj:`str`): ``TextEntityTypeBotCommand`` No ...
StarcoderdataPython
1643337
# Given a binary tree, determine if it is height-balanced. # For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # ...
StarcoderdataPython
5097624
<filename>tock/organizations/migrations/0004_unit_org.py # Generated by Django 2.2.10 on 2020-03-04 22:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('organizations', '0003_unit'), ] operations = [ mi...
StarcoderdataPython
1785881
<reponame>myhoger/ditto # Copyright 2013 MemSQL, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
StarcoderdataPython
3476449
from __future__ import absolute_import, unicode_literals from django.core.urlresolvers import reverse, reverse_lazy from django.http import Http404 from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.decorato...
StarcoderdataPython
3564182
<filename>qap/test_script_utils.py import pytest import unittest class TestGatherFilepathList(unittest.TestCase): def setUp(self): # setup import os import pkg_resources as p from qap.script_utils import gather_filepath_list self.gather_filepath_list = gather_filepath_lis...
StarcoderdataPython
6607878
<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('characters', '0003_auto_20150410_1125'), ('wod_rules', '0002_auto_20150410_1125'), ('mage_rules', '0001_initial')...
StarcoderdataPython
11224388
<filename>exemplo_de_test/test_basico.py def test_one_plus_one_is_two(): assert 1 + 1 == 2 def test_negative_1_plus_is_3(): assert 1 + 1 == 3
StarcoderdataPython
79223
# encoding: utf-8 """ @author: yp @software: PyCharm @file: GoodsManageDemo.py @time: 2019/8/1 0001 16:43 """ from AutoTestPlatform.web.WebDriver import Driver driver = Driver() #登录Dbshop driver.get("http://192.168.1.16/DBshop/admin") driver.find_element_by_id_data("user_name", 'admin') driver.find_element_by_id_d...
StarcoderdataPython
103735
import h5py import os import re class H5Explorer(object): def __init__(self, h5_obj): self.__filename = h5_obj.file.filename self.__file = h5_obj self.__working_dir = h5_obj.name self.__dir_queue = list() @staticmethod def from_file(filename, mode="r"): filename = ...
StarcoderdataPython
8177221
<filename>String/696. Count Binary Substrings.py """ 696. Count Binary Substrings Example 1: Input: "00110011" Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Notice that some of these substrings repeat and are coun...
StarcoderdataPython
4821908
<reponame>alexgaskell10/encoded_kge<gh_stars>100-1000 from kge.job import EvaluationJob, Job class EntityPairRankingJob(EvaluationJob): """ Entity-pair ranking evaluation protocol """ def __init__(self, config, dataset, parent_job, model): super().__init__(config, dataset, parent_job, model) ...
StarcoderdataPython
6580791
<filename>pyapprox/l1_minimization.py import numpy as np import scipy.sparse as sp from functools import partial from scipy.optimize import minimize, LinearConstraint, NonlinearConstraint, BFGS, \ linprog, OptimizeResult, Bounds try: from ipopt import minimize_ipopt has_ipopt = True except: has_ipopt =...
StarcoderdataPython
5109521
"""Example of use of the CodonOptimize specification.""" from dnachisel import (DnaOptimizationProblem, random_protein_sequence, CodonOptimize, reverse_translate, EnforceTranslation) protein = random_protein_sequence(3000, seed=123) sequence = reverse_translate(protein) problem = DnaOptimizatio...
StarcoderdataPython
8173099
# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # from PySide2 import QtCore import maya.standalone maya.standalone.initialize(name='python') import maya.cmds as...
StarcoderdataPython
6410135
from tool.runners.python import SubmissionPy from collections import defaultdict from functools import lru_cache from textwrap import wrap class BadouralixSubmission(SubmissionPy): def run(self, s): """ :param s: input in string format :return: solution flag """ # Before e...
StarcoderdataPython
1768214
from KnapsackProblem.KnapsackProblem import KnapsackProblem if __name__ == '__main__': print("------------- Knapsack Informations -------------") max_weight = int(input("Select max weight of knapsack: ")) length_items = int(input("Select max amount of items in the knapsack: ")) max_weight_items = int(input("Se...
StarcoderdataPython
5069740
<gh_stars>1-10 import os import pwd import grp from collections import OrderedDict from envy.lib.docker_manager import ContainerManager from envy.lib.io import StepPrinter from envy.lib.config import ENVY_CONFIG import envy.lib.triggers as triggers from .script_setup_step import ScriptSetupStep from .remote_setup_s...
StarcoderdataPython