id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
6,931
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil...
Determine if a CSS selector matches a particular element.
6,932
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil...
Attempt to cast a string to a python type.
6,933
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil...
Calculate the specificity score of a CSS selector.
6,934
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil...
Collect all CSS styles from style tags.
6,935
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Retrieve the last character of formatted text.
6,936
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Apply a style to formatted text.
6,937
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Align formatted text vertically.
6,938
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Concatenate two blocks of formatted text, aligning at a given baseline. Args: ft_a: The first block of formatted text to combine ft_b: The second block of formatted text to combine baseline_a: The row to use to align the first block of formatted text with the second, counted in lines down from the top of the block base...
6,939
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Indent formatted text with a given margin. Args: ft: The formatted text to strip margin: The margin string to add style: The style to apply to the margin skip_first: If :py:const:`True`, the first line is skipped Returns: The indented formatted text
6,940
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Add a border around formatted text. Args: ft: The formatted text to enclose with a border width: The target width including the border and padding style: The style to apply to the content background border_grid: The grid style to use for the border border_visibility: Determines which edges should receive a border borde...
6,941
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Format formatted text using a named :py:mod:`pygments` lexer.
6,942
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_tool...
Write fragments tagged with "[ReverseOverwrite]" over text to their left.
6,943
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Return successiver overlapping pairs from an iterable.
6,944
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Compute a cell's border line.
6,945
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Calculate column widths given the available space. Reduce the widest column until we fit in available width, or expand cells to to fill the available width. Args: cols: A list of columns in the table width: The desired width of the table expand_to_width: Whether the column should expand to fill the available width min_...
6,946
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Calculate which character to use at the intersection of four cells.
6,947
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Calculate which character to use to divide horizontally adjacent cells.
6,948
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Calculate which character to use to divide vertically adjacent cells.
6,949
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Wrap the cell's text to a given width. Args: cell: The cell whose lines to compute width: The width at which to wrap the cell's text. render_count: The number of times the application has been rendered Returns: A list of lines of formatted text
6,950
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text fr...
Compute the cell's final style for each of a cell's borders.
6,951
from __future__ import annotations import logging from functools import lru_cache, partial from typing import TYPE_CHECKING from prompt_toolkit.application.current import get_app from prompt_toolkit.data_structures import Point from prompt_toolkit.layout import containers from prompt_toolkit.layout.containers import Wi...
null
6,952
from __future__ import annotations import asyncio import logging from threading import Thread from typing import TYPE_CHECKING, cast from prompt_toolkit.cache import FastDictCache from prompt_toolkit.data_structures import Point from prompt_toolkit.filters import Condition from prompt_toolkit.formatted_text.utils impor...
Determine if there is a currently focused webview.
6,953
from __future__ import annotations import logging from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app as ptk_get_app from prompt_toolkit.application.run_in_terminal import in_terminal from prompt_toolkit.filters.app import ( has_completions, is_done, is_searching, ...
Get the current application.
6,954
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `check_output` function. Write a Python function `def check_output(*args: "str") -> "str"` to solve the following problem: Check the output of a command. Args: args: List of works in...
Check the output of a command. Args: args: List of works in a command line string
6,955
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `item` function. Write a Python function `def item(text: "str") -> "None"` to solve the following problem: Print a task. Here is the function: def item(text: "str") -> "None": ...
Print a task.
6,956
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `error` function. Write a Python function `def error(text: "str") -> "None"` to solve the following problem: Print an error message. Here is the function: def error(text: "str") ->...
Print an error message.
6,957
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `status` function. Write a Python function `def status(value: "str") -> "None"` to solve the following problem: Print a status field at the end of a line. Here is the function: def...
Print a status field at the end of a line.
6,958
from __future__ import annotations import subprocess import sys from textwrap import dedent, indent from typing import TYPE_CHECKING, cast def format_action(action: argparse.Action) -> str: """Format an action as RST.""" s = "" type_ = "" if action.type and action.type != bool: action.type = cas...
Format a parser's arguments as RST.
6,959
import os from pathlib import Path from textwrap import dedent The provided code snippet includes necessary dependencies for implementing the `activate_virtualenv_in_precommit_hooks` function. Write a Python function `def activate_virtualenv_in_precommit_hooks() -> "None"` to solve the following problem: Activate virt...
Activate virtualenv in hooks installed by pre-commit. This function patches git hooks installed by pre-commit to activate the hatch virtual environment. This allows pre-commit to locate hooks in that environment when invoked from git.
6,960
from __future__ import annotations import sys from typing import TYPE_CHECKING from prompt_toolkit.input.vt100 import raw_mode from euporie.core.io import Vt100Parser from euporie.core.keys import Keys The provided code snippet includes necessary dependencies for implementing the `callback` function. Write a Python fu...
Run when a key press event is received.
6,961
from __future__ import annotations import subprocess import sys from textwrap import dedent, indent from euporie.core.commands import commands commands: dict[str, Command] = {} The provided code snippet includes necessary dependencies for implementing the `format_commands` function. Write a Python function `def forma...
Format commands as RST.
6,962
import click import sys from typing import List def mutate_header(line) -> str: cveXXXXX = ' Status CVE-2021-XXXXX ' _, vendor, product, version, cve4104, cve44228, cve45046, cve45105, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve45105, cveX...
null
6,963
import click import sys from typing import List VALID_STATUS = [''] def mutate_header(line) -> str: cve45105 = ' Status CVE-2021-45105 ' _, vendor, product, version, cve4104, cve44228, cve45046, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve4...
null
6,964
import click import sys from typing import List def mutate_header(line) -> str: cve4104 = ' Status CVE-2021-4104 ' cve45046 = ' Status CVE-2021-45046 ' cve44228 = ' Status CVE-2021-44228 ' _, vendor, product, version, status, comment, link, _ = line.split('|') return(table_line([vendor, product, ver...
null
6,965
import sys import csv as py_csv import json as py_json from pathlib import Path from typing import List, Iterator import click import mistune import unicodedata from bs4 import BeautifulSoup from bs4.element import Tag def parse_record(record: List[Tag] = None) -> dict: """ Parse single tr record in Software list ...
Parse a single software list file :param path: path of file to parse :yield: a single parse record from file
6,966
import sys import csv as py_csv import json as py_json from pathlib import Path from typing import List, Iterator import click import mistune import unicodedata from bs4 import BeautifulSoup from bs4.element import Tag def json(ctx, output): py_json.dump(ctx.obj['records'], output)
null
6,967
import sys import csv as py_csv import json as py_json from pathlib import Path from typing import List, Iterator import click import mistune import unicodedata from bs4 import BeautifulSoup from bs4.element import Tag HEADERS = [ 'Supplier', 'Product', 'Version', 'Status CVE-2021-4104', 'Status CVE...
null
6,968
import base64 import copy import json import logging import operator import re import uuid from decimal import Decimal from functools import reduce from itertools import chain from typing import Optional import posthog import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django....
null
6,969
from __future__ import unicode_literals import logging import django from django.core import signals from django.core.cache.backends.base import BaseCache import django.db.backends.utils from django.db import OperationalError django.db.backends.utils.CursorWrapper.execute = execute_wrapper def get_cache(backen...
null
6,970
import datetime import logging import os import re import uuid from datetime import timedelta, timezone from json import loads from pathlib import Path from urllib.parse import urlparse import dj_database_url import django_heroku import jwt import posthog import sentry_sdk from decouple import config from dotenv import...
null
6,971
import datetime import logging import os import re import uuid from datetime import timedelta, timezone from json import loads from pathlib import Path from urllib.parse import urlparse import dj_database_url import django_heroku import jwt import posthog import sentry_sdk from decouple import config from dotenv import...
null
6,972
import datetime import logging import os import re import uuid from datetime import timedelta, timezone from json import loads from pathlib import Path from urllib.parse import urlparse import dj_database_url import django_heroku import jwt import posthog import sentry_sdk from decouple import config from dotenv import...
null
6,973
import logging from dataclasses import dataclass import sentry_sdk from django.conf import settings from metering_billing.models import Event from metering_billing.utils import now_utc from .singleton import Singleton class Event(models.Model): organization = models.ForeignKey( Organization, on_delete=mode...
null
6,974
import json import pycountry import requests import sentry_sdk from django.conf import settings from drf_spectacular.utils import extend_schema, inline_serializer from metering_billing.exceptions import ( CRMIntegrationNotAllowed, CRMNotSupported, EnvironmentNotConnected, ) from metering_billing.models impo...
null
6,975
import json import pycountry import requests import sentry_sdk from django.conf import settings from drf_spectacular.utils import extend_schema, inline_serializer from metering_billing.exceptions import ( CRMIntegrationNotAllowed, CRMNotSupported, EnvironmentNotConnected, ) from metering_billing.models impo...
null
6,976
import logging from django.conf import settings from django.core.mail import BadHeaderError, EmailMultiAlternatives from drf_spectacular.utils import extend_schema, inline_serializer from metering_billing.exceptions import DuplicateCustomer from metering_billing.models import TeamInviteToken, User from metering_billing...
null
6,977
import stripe from django.conf import settings from django.views.decorators.csrf import csrf_exempt from rest_framework import status from rest_framework.decorators import ( api_view, authentication_classes, permission_classes, ) from rest_framework.response import Response from metering_billing.kafka.produ...
null
6,978
def remove_invalid_subscription_methods(endpoints): # your modifications to the list of operations that are exposed in the schema to_remove = [] for path, path_regex, method, callback in endpoints: if (path == r"/api/subscriptions/" and method == "POST") or ( path == r"/api/subscriptio...
null
6,979
def remove_required_parent_plan_and_target_customer(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) schemas["Plan"]["required"] = [ x for x in schemas["Plan"]["required"] if x not in ["parent_plan", "target_customer"] ] return result
null
6,980
def remove_required_address_from_lw_cust_invoice(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) schemas["LightweightCustomerSerializerForInvoice"]["required"] = [ x for x in schemas["LightweightCustomerSerializerForInvoice"]["required"] if x not in ["addre...
null
6,981
def remove_required_external_payment_obj_type(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) schemas["LightweightInvoice"]["required"] = [ x for x in schemas["LightweightInvoice"]["required"] if x not in ["external_payment_obj_type"] ] return resul...
null
6,982
def add_external_payment_obj_type_to_required(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) if "external_payment_obj_type" not in schemas["LightweightInvoice"]["required"]: schemas["LightweightInvoice"]["required"].append("external_payment_obj_type") return result
null
6,983
def add_plan_id_parent_plan_target_customer_to_required(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) if "plan_id" not in schemas["Plan"]["required"]: schemas["Plan"]["required"].append("plan_id") if "parent_plan" not in schemas["Plan"]["required"]: schemas["...
null
6,984
import abc import base64 import datetime import logging from decimal import Decimal from typing import Literal, Optional, Tuple from urllib.parse import urlencode import braintree import pytz import requests import sentry_sdk import stripe from django.conf import settings from django.core.cache import cache from django...
null
6,985
import logging from collections.abc import Iterable from decimal import Decimal import sentry_sdk from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q, Sum from django.db.models.query import QuerySet from metering_billing.kafka.producer import Producer from me...
Generate an invoice for a subscription.
6,986
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( ...
null
6,987
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( ...
null
6,988
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( ...
null
6,989
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( ...
null
6,990
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( ...
Generate `n` stacktrace lengths with a gaussian distribution
6,991
import uuid from django.db import migrations def gen_uuid(apps, schema_editor): Subscription = apps.get_model("metering_billing", "Subscription") for row in Subscription.objects.all(): row.uuid = uuid.uuid4() row.save(update_fields=["subscription_uid"])
null
6,992
from django.db import migrations def move_from_seconds_to_microseconds(apps, schema_editor): SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for row in SubscriptionRecord.objects.all(): row.unadjusted_duration_microseconds = row.unadjusted_duration_seconds * 10**6 ...
null
6,993
import uuid from django.db import migrations from django.db.models import Q def make_all_emails_nonnull(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") c_list = Customer.objects.filter(Q(email="") | Q(email__isnull=True)) for c in c_list: c.email = f"{str(uuid.uuid4(...
null
6,994
from django.db import migrations def transfer_invoice_status(apps, schema_editor): Invoice = apps.get_model("metering_billing", "Invoice") for inv in Invoice.objects.all(): if inv.payment_status_old == "draft": inv.payment_status = 1 elif inv.payment_status_old == "voided": ...
null
6,995
from django.db import migrations def transfer_component_granularity_to_metric(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): if metric.metric_type == "stateful": metric.metric_type = "gauge" metric.save()
null
6,996
from django.db import migrations def reverse_transfer_component_granularity_to_metric(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): if metric.metric_type == "gauge": metric.metric_type = "stateful" metric.save()
null
6,997
from django.db import migrations METRIC_HANDLER_MAP = { METRIC_TYPE.COUNTER: CounterHandler, METRIC_TYPE.GAUGE: GaugeHandler, METRIC_TYPE.RATE: RateHandler, METRIC_TYPE.CUSTOM: CustomHandler, } def refresh_mat_views(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") fr...
null
6,998
from django.db import migrations def transfer_data(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") Customer = apps.get_model("metering_billing", "Customer") StripeCustomerIntegration = apps.get_model( "metering_billing", "StripeCustomerIntegration" ) ...
null
6,999
import uuid from django.conf import settings from django.db import migrations, models def fill_uuid(apps, schema_editor): IdempotenceCheck = apps.get_model("metering_billing", "IdempotenceCheck") for check in IdempotenceCheck.objects.all(): check.uuidv5_idempotency_id = uuid.uuid5( settings...
null
7,000
from django.db import migrations from metering_billing.utils.enums import BATCH_ROUNDING_TYPE, PRICE_TIER_TYPE def migrate_plancomponetns_to_price_tiers(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") PriceTier = apps.get_model("metering_billing", "PriceTier") Plan...
null
7,001
from django.db import migrations, models def change_organization_setting_names(apps, schema_editor): OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for setting in OrganizationSetting.objects.all(): if setting.setting_name == "subscription_filters": setting.s...
null
7,002
import uuid from django.db import migrations def make_unique_uuids(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") RecurringCharge = apps.get_model("metering_billing", "RecurringCharge") for plan_component in PlanComponent.objects.all(): plan_component.usag...
null
7,003
import uuid from django.db import migrations def transfer_text_to_uuid(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") for org in Organization.objects.all(): org.organization_id = uuid.uuid4() org.save() Backtest = apps.get_model("metering_billing", ...
null
7,004
from django.db import migrations, models def delete_dups(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") for row in Customer.objects.all().order_by("pk"): org = row.organization email = row.email pk = row.pk others = Customer.objects.filter(organi...
null
7,005
from django.db import migrations def copy_events_to_idempotencecheck(apps, schema_editor): Event = apps.get_model("metering_billing", "Event") IdempotenceCheck = apps.get_model("metering_billing", "IdempotenceCheck") for event in Event.objects.order_by( "idempotency_id", "organization", "-time_cre...
null
7,006
from django.db import migrations def migrate_customer_and_organization_addresses(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") Organization = apps.get_model("metering_billing", "Organization") Address = apps.get_model("metering_billing", "Address") # Migrate customer ...
null
7,007
from django.db import migrations def prepopulate(apps, schema_editor): apps.get_model("metering_billing", "PlanComponent") apps.get_model("metering_billing", "PriceTier") apps.get_model("metering_billing", "PlanVersion") PricingUnit = apps.get_model("metering_billing", "PricingUnit") Invoice = apps...
null
7,008
from django.db import migrations def mark_as_demo(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") Organization.objects.filter(company_name__startswith="demo_").update(is_demo=True)
null
7,009
from django.db import migrations def set_not_before(apps, schema_editor): PlanVersion = apps.get_model("metering_billing", "PlanVersion") for version in PlanVersion.objects.all(): if version.created_on: version.active_from = version.created_on version.save() Plan = apps.get...
null
7,010
from django.db import migrations def set_not_after(apps, schema_editor): from metering_billing.utils import now_utc PlanVersion = apps.get_model("metering_billing", "PlanVersion") for version in PlanVersion.objects.all(): if version.status == "active": version.active_to = None ...
null
7,011
import uuid from django.conf import settings from django.db import migrations def set_uuidv5_customer_id(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") HistoricalCustomer = apps.get_model("metering_billing", "HistoricalCustomer") CUSTOMER_ID_NAMESPACE = settings.CUSTOMER_ID...
null
7,012
from django.db import migrations def transfer_events(apps, schema_editor): UsageEvent = apps.get_model("metering_billing", "UsageEvent") Event = apps.get_model("metering_billing", "Event") for event in Event.objects.all(): UsageEvent.objects.create( event_name=event.event_name, ...
null
7,013
import uuid from django.db import migrations def unique_team_id(apps, schema_editor): Team = apps.get_model("metering_billing", "Team") for team in Team.objects.all(): team.team_id = uuid.uuid4() team.save()
null
7,014
from django.db import migrations def copy_addon_spec(apps, schema_editor): Plan = apps.get_model("metering_billing", "Plan") AddOnSpecification = apps.get_model("metering_billing", "AddOnSpecification") for plan_template in Plan.objects.filter(addon_spec__isnull=False): plan_template.is_addon = Tru...
null
7,015
import time from django.db import migrations def transfer_subscription_keys(apps, schema_editor): OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for org_setting in OrganizationSetting.objects.filter( setting_name="subscription_filter_keys" ): organization = ...
null
7,016
from django.db import migrations def migrate_stateful_other_to_max(apps, schema_editor): BillableMetric = apps.get_model("metering_billing", "BillableMetric") BillableMetric.objects.filter( metric_type="rate", usage_aggregation_type="unique", ).update(usage_aggregation_type="count", propert...
null
7,017
from django.db import migrations def transfer_text_to_int(apps, schema_editor): PriceTier = apps.get_model("metering_billing", "PriceTier") for price_tier in PriceTier.objects.all(): if price_tier.type_old == "flat": price_tier.type = 1 elif price_tier.type_old == "per_unit": ...
null
7,018
from django.db import migrations def transfer_org_settings(apps, schema_editor): OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for org_setting in OrganizationSetting.objects.filter( setting_name="generate_customer_after_creating_in_lotus" ): organization = ...
null
7,019
import uuid from django.db import migrations def make_metric_ids_unique(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): metric.metric_id = str(uuid.uuid4()) metric.save()
null
7,020
from django.db import migrations def fill_null_pricing_unit_in(apps, schema_editor): RecurringCharge = apps.get_model("metering_billing", "RecurringCharge") for recurring_charge in RecurringCharge.objects.filter(pricing_unit__isnull=True): recurring_charge.pricing_unit = recurring_charge.plan_version....
null
7,021
from django.db import migrations from django.db.models import Count, Max def remove_duplicates(apps, schema_editor): Event = apps.get_model("metering_billing", "Event") unique_fields = ["organization_id", "idempotency_id"] duplicates = ( Event.objects.values(*unique_fields) .order_by() ...
null
7,022
from django.db import migrations def transfer_flat_fees_to_recurring(apps, schema_editor): PlanVersion = apps.get_model("metering_billing", "PlanVersion") RecurringCharge = apps.get_model("metering_billing", "RecurringCharge") for plan_version in PlanVersion.objects.all(): if plan_version.flat_rate...
null
7,023
import metering_billing.utils.utils from django.db import migrations, models def transfer_custom_plans(apps, schema_editor): Plan = apps.get_model("metering_billing", "Plan") for plan in Plan.objects.filter(target_customer__isnull=False): parent_plan = plan.parent_plan num_versions_in_parent =...
null
7,024
import uuid from uuid import UUID from django.db import migrations def transfer_text_to_uuid(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") for org in Organization.objects.all(): uuid_string = org.organization_id_old.replace("org_", "") uuid_instance = U...
null
7,025
from django.db import migrations def delete_dups(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") for row in Customer.objects.all().order_by("pk"): org = row.organization email = row.email pk = row.pk others = Customer.objects.filter(organization=o...
null
7,026
from django.db import migrations def transfer_component_granularity_to_metric(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") apps.get_model("metering_billing", "Metric") for component in PlanComponent.objects.all(): ass_metric = component.billable_metric ...
null
7,027
from django.db import migrations def fill_pricing_units(apps, schema_editor): PlanVersion = apps.get_model("metering_billing", "PlanVersion") for plan_version in PlanVersion.objects.filter(currency__isnull=True): plan_version.currency = plan_version.organization.currency plan_version.save()
null
7,028
from django.db import migrations def transfer_to_brs(apps, schema_editor): SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") BillingRecord = apps.get_model("metering_billing", "BillingRecord") InvoiceLineItem = apps.get_model("metering_billing", "InvoiceLineItem") for sr in ...
null
7,029
from django.db import migrations def transfer_filters_to_subscription_filters(apps, schema_editor): SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for subscription in SubscriptionRecord.objects.all(): new_filters = [] for sf in subscription.filters.all(): ...
null
7,030
from django.db import migrations from django.db.models import Q def migrate_metric_type(apps, schema_editor): BillableMetric = apps.get_model("metering_billing", "BillableMetric") BillableMetric.objects.filter(metric_type="aggregation").update( metric_type="counter" )
null