text
string
size
int64
token_count
int64
from algo_mini_max import get_available_moves, clone_and_apply_actions, from_numpy_to_tuple import numpy as np from time import time, sleep from const import RACE_ID, HUM, WOLV, VAMP from board import Action, Board from threading import RLock from game import TRANSPOSITION, INF PRINT_SUMMARY = False VICTORY_IS_INF = T...
4,928
1,427
# Source Code print("\t\t\t***** BankWithUs *****") bank_data = {} while True: print("\n\n\t\t\t----- Main Menu -----") ch = int(input("\n\n1.New Customer\n2.Existing Customer\n3.Exit\n\nEnter choice:")) if ch == 1: name = input("\nEnter name:") city = input("Enter city:") age = ...
2,197
675
import trafaret as T """ trafaret for server config """ TRAFARET = T.Dict({ T.Key('session_secret'): T.String(), T.Key('users'): T.Any(), T.Key('mysql'): T.Dict({ 'db': T.String(), 'host': T.String(), 'user': T.String(), 'password': T.String(allow_bla...
1,034
353
class Item: # Lower mult = Less clumped and less spawns. NOISE_MULT = 0.5 # Bigger diff = less spawns. SPAWN_DIFF = 0.01 def __init__(self, name, points): self.name = name self.short_name = self.name[0] self.points = points # TODO: Tinker with NOISE_MULT and SPAWN_DIFF fo...
784
330
import argparse import os import random import time import warnings import sys import numpy as np from sklearn.metrics import pairwise_distances import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.multiprocessing as mp import torch.utils.data ...
16,833
5,568
import logging from ..common.utils import charCodeAt, isSpace, normalizeReference from .state_block import StateBlock LOGGER = logging.getLogger(__name__) def reference(state: StateBlock, startLine, _endLine, silent): LOGGER.debug( "entering reference: %s, %s, %s, %s", state, startLine, _endLine, silen...
6,324
1,877
opcode_table = {'CLA': '0000', 'LAC': '0001', 'SAC': '0010', 'ADD': '0011', 'SUB': '0100', 'BRZ': '0101', 'BRN': '0110', 'BRP': '0111', 'INP': '1000', 'DSP': '1001', 'MUL': '1010', 'DIV': '1011', 'STP': '1100'} words = {'CLA': 1, 'LAC': 2, 'SAC': 2, 'ADD': 2, 'SUB': 2, 'BRZ': 2, 'BRN': 2, 'BRP'...
7,928
2,462
""" Methods for creating an input database """ import os import time import glob import pandas as pd from .. import constants from .database import Database def build_input_database(): """ Builds an input database from source Excel spreadsheets and stores it in the data directory. """ # Load input d...
4,319
1,703
import sys import os from django.conf import settings BASE_DIR = os.path.dirname(os.path.abspath(__file__)) settings.configure( DEBUG=True, SECRET_KEY='ac!5bu68^vf3_12)m1e&2ls#1uidd_33f)c!j=&&^b_91m7g#+', ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware',...
1,833
662
#!/usr/bin/env python import IPython import numpy as np #import ROOT DTYPE_BASE = np.dtype([("pT", np.float64), ("eta", np.float64), ("phi", np.float64), ("m", np.float64)]) print(f"DTYPE_BASE: {DTYPE_BASE}") #status_dtype = DTYPE_EP.descr + [("status_code", np.int32)] DTYPE_JETS = [(f"{label}_{name}", dtype) for l...
774
343
from nano_magic.entities.match import Match from nano_magic.repositories.match import MatchRepository async def select_match(client, matches: MatchRepository, channel_factory): while True: match_id = await client.request_match_id() match_password = await client.request_match_password() mat...
700
177
#!/usr/bin/env python3 import requests import sys import csv import re import numpy as np def gini_index(array): """ Calculate the Gini coefficient of a numpy array """ array = array.flatten() if np.amin(array) < 0: array -= np.amin(array) # values cannot be negative array += 0.00000...
3,398
1,084
""" Migration script to (a) create tables for annotating objects and (b) create tags for workflow steps. """ import logging from sqlalchemy import ( Column, ForeignKey, Index, Integer, MetaData, Table, TEXT, Unicode, ) from galaxy.model.migrate.versions.util import ( create_table,...
3,260
1,007
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. import cohesity_management_sdk.models.protection_source class AAGAndDatabases(object): """Implementation of the 'AAG And Databases.' model. Specifies an AAG and the database members of the AAG. Attributes: aag (ProtectionSource): Specifies ...
2,119
540
import logging from django.core.management.base import BaseCommand from coursedashboards.models import ( Course, CourseOffering, User) logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Changes ESS 102 to have an enrollment of 3" def handle(self, *args, **options): es...
738
218
def build (): return class place: #__name__ = None def __init__ (self,*to,**here): self.links = to self.actions = here self.run('__name__') def __repr__ (self): return self.__str__() def __str__ (self): s = ')' for a in self.actions: s = ',%s=%s' %(a,self.actions[a].__repr__()) + s return sel...
1,511
686
# %% [762. Prime Number of Set Bits in Binary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/) # 問題:[L, R]の範囲で条件を満たす数字の個数を返せ。条件は2進数で1になる数が素数であること # 解法:Rは1000_000以下であり、2進数で22ビット以下となり、素数は2, 3, 5, 7, 11, 13, 17, 19しかない class Solution: def countPrimeSetBits(self, L: int,...
448
266
import tkinter as tk # Tkinter Frame that handles the Buttons class ButtonFrame(tk.Frame): def __init__(self, master, VideoWidget=None, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) """ master: master widget upon which this works VideoWidget: Video Capt...
1,938
527
import blackjack.cmake.cmd as cmd from .BaseTarget import BaseTarget class LibTarget_Interface(BaseTarget): """ Represents a CMake Interface Library target An Interface library target does not directly create build output though it may have properties set on it and it may be installed, exported and i...
1,108
310
from django.shortcuts import get_object_or_404, redirect, render from django.views import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.contrib import messages from django.urls import reverse_lazy from main.models import List from main.form i...
2,451
751
# http://stackoverflow.com/questions/6290162/how-to-automatically-reflect-database-to-sqlalchemy-declarative from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import orm from contextlib import contextmanager from collections import OrderedDict import ...
4,555
1,370
""" Class description goes here. """ from dataclay.util.MgrObject import ManagementObject class DataClayInstance(ManagementObject): _fields = ["dcID", "hosts", "ports", ] _internal_fields = []
255
71
import json import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def main(): key = demisto.args()['key'] obj_str = json.dumps(demisto.get(demisto.context(), key)) demisto.setContext('JsonStr', obj_str) return_results(obj_str) if __name__ in ('__main__', '__buil...
352
132
cumulative_reward_cache = {} def cumulative_reward(reward_function, t, cache=True): if cache and (reward_function, t) in cumulative_reward_cache: return cumulative_reward_cache[(reward_function, t)] else: res = 0 for i in range(1, t + 1): res += reward_function(i) if...
591
198
# Copyright 2018 The glTF-Blender-IO authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
6,973
2,215
import argparse import logging from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional import more_itertools import numpy import pandas import requests from annofabapi.models import ProjectMemberRole, ProjectMemberStatus from dataclasses_json import DataClassJsonMixin i...
8,402
3,011
from .element import Element class Strong(Element): """ Represents content that has strong importance. """ def __str__(self): return "strong"
169
48
# HiPyQt version 3.1 # use QLabel # use QPushButton import sys from PyQt5.QtWidgets import * class MyWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Hi PyQt") self.setGeometry(50, 50, 400, 300) # QLabel self.label = QLabel("QLabel", self) ...
825
297
import os from typing import Iterable, Tuple, List class NameFix(object): def __init__( self, root_directory: str, exclude: Iterable[str], max_directory_length: int, max_filename_length: int ) -> None: self.root_directory = root_directory ...
3,340
980
import unittest from nonogram import Row, Cell, Infeasible class TestRow(unittest.TestCase): def test_create(self): row = Row(1) self.assertTrue(row) self.assertEqual(row.length, 10) self.assertEqual(len(row), 10) self.assertEqual(row.possible, []) self.assertEqual(...
3,514
1,310
""" A weighted version of categorical_crossentropy for keras (2.0.6). This lets you apply a weight to unbalanced classes. @url: https://gist.github.com/wassname/ce364fddfc8a025bfab4348cf5de852d @author: wassname """ from keras import backend as K def region_dice_overlap(weights): """ A weighted version of keras...
2,474
907
import random from typing import List from dex.task import Task from dex.util import AttrDict def rank_tasks(task_collection: AttrDict, limit: int = 0, include_inactive: bool = False) -> List[Task]: """ Order a task collection 1. remove abandoned and done tasks 2. deprioritize held tasks 3. ...
1,350
391
from pathlib import Path # Zaehle die Anzahl Ordner in einem Ordner (inkl. allen Unterordnern) def count_dirs(path): subdirs = [subdir for subdir in path.iterdir() if subdir.is_dir()] #Bestimme die direkten Unterordner des Ordners path count = 1 # Spielwiese selbst for subdir in subdirs: ...
476
175
''' This is a set of utility funcitons useful for analysing POD data. Plotting and data reorganization functions ''' #Plot 2D POD modes def plotPODmodes2D(X,Y,Umodes,Vmodes,plotModes,saveFolder = None): ''' Plot 2D POD modes Inputs: X - 2D array with columns constant Y - 2D array with rows ...
15,849
5,946
import os import docker import logging from ... import constants from ...log import log_to_client from ...memoize import memoized from ...subprocess import check_output_demoted from ...compiler.spec_assembler import get_specs def exec_in_container(container, command, *args): client = get_docker_client() exec...
3,898
1,172
""" This module is about generating, validating, and operating on (parametrized) fields (i.e. stings, e.g. paths). """ import re import os from functools import partial, wraps from types import MethodType from py2store.signatures import set_signature_of_func from py2store.errors import KeyValidationError, _assert_con...
22,242
7,072
from enum import Enum class ChatTag(Enum): NONE = 0x00 AFK = 0x01 DND = 0x02 GM = 0x04
154
62
from corehq.apps.app_manager import id_strings from corehq.apps.app_manager.suite_xml import xml_models as sx from corehq.apps.app_manager.suite_xml import const from corehq.apps.app_manager.util import is_sort_only_column from corehq.apps.app_manager.xpath import ( CaseXPath, CommCareSession, IndicatorXpat...
17,291
4,888
# -*- coding: utf-8 -*- #!/usr/bin/env python """ MplCanvas This is a QWidget that can be used for fast-ish plotting within a Qt GUI interface. Originally I was going to subclass for different types of plots, but this seems a little hard with the amount of initialization required to setup the plot properly...
17,070
5,629
import json import pytz import pandas as pd from cy_components.helpers.formatter import * def convert_df_to_json_list(df: pd.DataFrame, primary_column_name=None): """DF -> JSON""" if primary_column_name is not None: df.rename({primary_column_name: '_id'}, axis=1, inplace=True) json_list = json.loa...
640
226
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ...
3,622
1,289
from .collectors import * from .definitions import * from .types import *
74
21
# Copyright 2019-2021 AstroLab Software # Authors: Julien Peloton, Juliette Vlieghe # # 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 # # Unle...
12,741
4,350
import pandas as pd from copy import deepcopy from typing import Optional, Set, List, Dict from numpy import mean, median from sklearn import clone from sklearn.base import BaseEstimator from sklearn.model_selection import cross_val_score, RepeatedKFold from Pythagoras.util import * from Pythagoras.logging import * f...
53,426
16,731
from http import HTTPStatus from flask_restful import Api, Resource, request from lefci import app, model from lefci.deploy import deploy api = Api(app) state = model.State() def create_report(message, status=model.Status.OK): report = model.Report(message, status) report_with_source = model.ReportBySource(...
3,932
1,157
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.modeling.meta_arch.rcnn import GeneralizedRCNN @META_ARCH_REGISTRY.register() class TwoStagePseudoLabGeneralizedRCNN(GeneralizedRCNN): def forward( sel...
4,334
1,236
import xlrd import csv from geopy.geocoders import Nominatim from django.core.management.base import BaseCommand class Command(BaseCommand): loc = ("Places-Europe-TC.xls") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) nom = Nominatim(user_agent="CSVToLatLong")...
1,673
596
from manga_py.provider import Provider from .helpers.std import Std class ReadComicBooksOnlineOrg(Provider, Std): _name_re = r'\.(?:org|net)/(?:reader/)?([^/]+)' def get_chapter_index(self) -> str: idx = self.re.search(r'/reader/[^/]+/[^/]+_(\d+(?:[\./]\d+)?)', self.chapter) if not idx: ...
1,781
617
# Copyright 2021 Petuum, 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...
3,332
1,022
#!/usr/bin/python import praw import pdb import re import os # Create the Reddit instance reddit = praw.Reddit('tutorial_bot') # and login #reddit.login(REDDIT_USERNAME, REDDIT_PASS) # Have we run this code before? If not, create an empty list if not os.path.isfile("posts_replied_to.txt"): posts_replied_to = []...
1,456
474
#!/usr/bin/env python3.6 # Python from collections import OrderedDict import os import random import math import numpy as np import argparse import time import matplotlib.pyplot as plt import cv2 import shlex, subprocess import yaml # Pytorch import PIL.Image as Image #from scipy import ndimage import torch import to...
26,053
8,948
class MyCalendarTwo: def __init__(self): self.calendar = [] self.overlaps = [] def book(self, start: int, end: int) -> bool: for event in self.overlaps: if event[0] < end and start < event[1]: return False for event in self.calendar: ...
653
192
# encoding: utf-8 from __future__ import division, print_function, unicode_literals #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # - Run with Option Key to include the MacroPanel. # - Run with Shift Ke...
6,640
2,478
import pytest from unittest.mock import patch, Mock from _test_commons import _load_pytorch_transformer_model from onnxruntime.training import amp, checkpoint, optim, orttrainer, _checkpoint_storage import numpy as np import onnx import torch # Helper functions def _create_trainer(zero_enabled=False): """Cerates ...
31,624
11,042
from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String from .base_model import Base from .header_model import header_association_table class Endpoint(Base): """ Database model that describes a URL/endpoint. Represents gobuster data. Relationships: ``t...
850
248
import re, time class Statistics(object): def __init__(self, ixNetObj): self.ixNetObj = ixNetObj def getStatView(self, caption): """ Get a statistics view. :param caption: <str>: The statistics view caption name. Example: Protocols Summary, Flow Stat...
15,810
4,023
from flask import Flask app = Flask(__name__) from moduleapp.apps.admin import admin from moduleapp.apps.frontend import frontend app.register_module(admin) app.register_module(frontend)
188
58
from enum import Enum from typing import Dict, Iterable, Optional try: from dataclasses import dataclass except ImportError: print( "Dataclasses required. Install Python >= 3.7 or the dataclasses package from" " PyPi" ) class BetterEnum(Enum): """a better enum type that also allows ch...
2,392
895
#!/usr/bin/env python salir = False operandos = False while not salir: operacion = input("Introduzca una operación válida: +, -, *, /, ^ (-1 para salir)") if (operacion != '+' and operacion != '-' and operacion != '*' and operacion != '/' and operacion != '^' and operacion != '-1'): print("Error, la op...
1,646
523
import matplotlib matplotlib.use('Agg') import argparse import pickle import matplotlib.pyplot as plt import numpy as np import os import seaborn as sns import shutil from brainpedia.brainpedia import Brainpedia from brainpedia.fmri_processing import invert_preprocessor_scaling from utils.multiple_comparison import b...
16,841
6,794
import sys from swift.codegen.generators import cppgen from swift.codegen.lib import cpp from swift.codegen.test.utils import * output_dir = pathlib.Path("path", "to", "output") @pytest.fixture def generate(opts, renderer, input): opts.cpp_output = output_dir opts.cpp_namespace = "test_namespace" opts.t...
5,096
1,577
import os import socket import subprocess import time import sys class Streamer: command = 'ffmpeg ' \ '-y ' \ '-f avfoundation ' \ '-r 30 ' \ '-pixel_format bgr0 ' \ '-s 640x480 ' \ '-video_device_index 0 ' \ ...
2,890
899
#!/usr/bin/env python OCURS_FR = { 'E': 12.10, 'A': 7.11, 'I': 6.59, 'S': 6.51, 'N': 6.39, 'R': 6.07, 'T': 5.92, 'O': 5.02, 'L': 4.96, 'U': 4.49, 'D': 3.67, 'C': 3.18, 'M': 2.62, 'P': 2.49, 'G': 1.23, 'B': 1.14, 'V': 1.11, 'H': 1.11, 'F': 1.11, 'Q': 0.65, 'Y': 0.46, 'X': 0.38, 'J': 0.34, 'K': 0...
531
421
#!/usr/bin/python3 """ File Copy --------- Write a simple program that reads content from one file an writes it to yet another file. All possible I/O and OS errors shall be handled gracefully (e.g. nonexisting input file, insufficient permissions etc) and an appropriate diagnostic information shall be printed to stand...
1,714
467
num1 = float(input('Digite o primeiro número: ')) num2 = float(input('Digite o segundo número: ')) if num1 > num2: print(f'O primeiro número {num1} é maior que o segundo numero {num2}!') elif num2 > num1: print(f'O segundo número {num2} é maior que o primeiro numero {num1}!') else: print(f'Os número {num1}...
343
125
''' Multiple Constructors A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few. In Python, as there is no me...
1,134
357
"""zfs.replicate.snapshot tests""" import string from typing import Any, Dict, List from hypothesis import given from hypothesis.searchstrategy import SearchStrategy from hypothesis.strategies import fixed_dictionaries, integers, lists, none, text from zfs.replicate.filesystem.type import filesystem from zfs.replica...
1,402
477
import warnings # Import all methods/classes for BC: from . import * # noqa: F401, F403 warnings.warn( "The 'torchvision.models.segmentation.segmentation' module is deprecated since 0.12 and will be removed in " "0.14. Please use the 'torchvision.models.segmentation' directly instead." )
301
100
""" Created on March 19, 2020 @author: "Alexey Mavrin" @email alexeymavrin@gmail.com That file is just a proxy for the duplicates package. """ from duplicates import duplicates if __name__ == '__main__': duplicates.main()
230
81
# coding=utf-8 """ Created by jayvee on 16/12/22. """ class NonDataException(IOError): """ 无法获取到数据时的异常 """ def __init__(self, msg): self.message = msg def __str__(self): return self.message
231
97
from __future__ import unicode_literals from django.apps import AppConfig class MarketBlogConfig(AppConfig): name = 'market_blog'
137
42
from mythril.analysis.report import Issue from mythril.analysis.swc_data import TX_ORIGIN_USAGE from mythril.analysis.modules.base import DetectionModule import logging """ MODULE DESCRIPTION: Check for constraints on tx.origin (i.e., access to some functionality is restricted to a specific origin). """ class Depr...
2,165
559
import tkinter as tk from random import choice, sample import tkinter.messagebox from PIL import Image, ImageTk import sys import os import global_value colors = ['red', 'blue', 'yellow', 'green', 'white', 'purple'] def resource_path(relative_path): if getattr(sys, 'frozen', False): # 是否Bundle Resource ...
8,156
3,044
# Generated by Django 3.0.8 on 2020-10-22 04:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('modulector', '0011_auto_20201022_0448'), ] operations = [ migrations.AlterField( model_name='mirnadrugs', name='cond...
383
140
import collections # Time: O(n); Space: O(n) def majority_element(nums): n = len(nums) freq = collections.Counter(nums) return [el for el, fr in freq.items() if fr > n / 3] # Boyer-Moore Voting Algorithm; Time: O(n); Space: O(1) def majority_element2(nums): count1 = count2 = 0 candidate1 = candi...
918
328
""" >>> pow3(2,3,5) == 3 True >>> pow3(3,3,5) == 2 True >>> pow3_const() == 3 True >>> pow2(2,3) == 8 True >>> pow2(3,3) == 27 True >>> pow2_const() == 8 True >>> c1, c2 = 1.2 + 4.1j, 0.6 + 0.5j >>> allclose(pow2(c1, c2), pow(c1, c2)) True >>> d1, d2 = 4.2, 5.1 >>> allclose(pow2(d1, d2), pow(d1, d2)) True """ fro...
743
375
# coding=utf-8 from __future__ import print_function import torch.utils.data as data import numpy as np import torch import os import argparse import csv import glob import cv2 from shutil import copyfile from tqdm import tqdm from copy import deepcopy from torchvision import transforms from torchvision.datasets.utils ...
10,238
3,503
import os import numpy as np import pytest import torch from imageio import imread from pythae.models import BaseAE, BaseAEConfig from pythae.samplers import BaseSampler, BaseSamplerConfig PATH = os.path.dirname(os.path.abspath(__file__)) @pytest.fixture def dummy_data(): ### 3 imgs from mnist that are used to...
7,359
2,631
# 78. 子集 # 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 # # 说明:解集不能包含重复的子集。 # # 示例: # # 输入: nums = [1,2,3] # 输出: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # 先看 全排列吧 class Solution1: def subsets(self, nums): ln = len(nums) if ln == 0: return [[]] ...
1,199
543
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, Ryanair!' @app.route('/mario') def hello_mario(): return 'Soy Mario' if __name__ == '__main__': app.run()
211
82
from json import loads from tenable_io.api.base import BaseApi, BaseRequest from tenable_io.api.models import AssetsExport, ExportsAssetsStatus, ExportsVulnsStatus, VulnsExport from tenable_io.util import payload_filter class ExportsApi(BaseApi): def vulns_request_export(self, exports_vulns): """Export ...
12,531
3,334
# -*- coding: UTF-8 -*- import os import pandas as pd import shutil import numpy as np from tqdm import tqdm import pyfastcopy import random def stat_count(dir): csv_list=os.listdir(dir) df_store=pd.DataFrame(columns=['Categories','Path','Frames']) modify_class=['misssing','wufashibei','gongzuorengyuan','q...
3,853
1,289
import os.path as osp import tarfile import zipfile def extractall(path, to=None): """Extract archive file. Parameters ---------- path: str Path of archive file to be extracted. to: str, optional Directory to which the archive file will be extracted. If None, it will be se...
1,322
428
from typing import Any try: from json_parser_cysimdjson import JSONArray, JSONObject, parse, parse_str, safe_get, to_native except ImportError: print('Using slow built-in json parsing, install cysimdjson') from json_parser_builtin import JSONArray, JSONObject, parse, parse_str, safe_get, to_native # type:...
334
104
# Generated by Django 3.0.3 on 2020-04-07 06:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('node', '0003_node_shareimage'), ] operations = [ migrations.AddField( model_name='node', name='enable', ...
378
127
# This file was auto generated; Do not modify, if you value your sanity! import ctypes from enum import IntEnum class flex_vnet_mode(IntEnum): """A ctypes-compatible IntEnum superclass.""" @classmethod def from_param(cls, obj): return int(obj) flexVnetModeDisabled = 0 flexVnetModeOneSingl...
491
168
from pachatary.exceptions import InvalidEntityException, EntityDoesNotExistException class SceneValidator: MIN_TITLE_LENGHT = 1 MAX_TITLE_LENGHT = 80 MIN_LATITUDE = -90 MAX_LATITUDE = +90 MIN_LONGITUDE = -180 MAX_LONGITUDE = +180 def __init__(self, experience_repo): self.experien...
3,553
977
#!/usr/bin/env python3 import sys import math def solve(): with open("inputs/day7.txt") as file: data = [line for line in file] solve_part_1(data) solve_part_2(data) def solve_part_1(data): crab_positions = list(map(int, filter(None, data[0].split(',')))) sorted_crab_positions = s...
2,064
726
from contextlib import contextmanager from m2cgen.interpreters.code_generator import CLikeCodeGenerator class JavascriptCodeGenerator(CLikeCodeGenerator): def add_function_def(self, name, args): function_def = f"function {name}({', '.join(args)}) {{" self.add_code_line(function_def) self...
646
200
from flask import Flask,render_template app = Flask(__name__) @app.route("/") def home(): return render_template("index.html") if __name__ == "__main__": app.run(debug=True,port="3000",host="0.0.0.0")
205
82
import errno import os import pkg_resources import sys import textwrap from dataclasses import dataclass, field from pathlib import Path from typing import FrozenSet, Optional import pyroute2 from . import c seccomp_bpf_bytes = pkg_resources.resource_stream( __name__, "sandbox-seccomp.bpf" ).read() @dataclass(...
15,235
4,573
from mythril.laser.smt import Solver, symbol_factory, bitvec import z3 import pytest import operator @pytest.mark.parametrize( "operation,expected", [ (operator.add, z3.unsat), (operator.sub, z3.unsat), (operator.and_, z3.sat), (operator.or_, z3.sat), (operator.xor, z3...
2,079
872
#!/usr/bin/env python3 from airsim import MultirotorClient, ImageType, ImageRequest, ImageResponse from airsim import CameraInfo as SimCameraInfo import os import json import numpy as np import rclpy from rclpy.node import Node from tf2_ros.transform_broadcaster import TransformBroadcaster from cv_bridge import CvBrid...
6,151
2,076
''' main.py Created by Jo Hyuk Jun on 2020 Copyright © 2020 Jo Hyuk Jun. All rights reserved. ''' import sys a, i = map(int, sys.stdin.readline().rstrip().split(' ')) print((a * i) - a + 1)
209
92
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Food', fields=[ ('id', models.AutoField(verbose...
1,471
402
#!/usr/bin/env python3 -u # This file uploads to the Romi using a USB cable import time import serial import os import sys import getopt import subprocess def main(argv): try: opts, args = getopt.getopt(argv,"hp:f:",["port=","file="]) except getopt.GetoptError as err: print(err) print...
1,758
645
''' Module for account related macros ''' import logging from process import kill_process from settings import LEAGUE_CLIENT_PROCESS, REGION, LOCALE from .exceptions import (AccountBannedException, AuthenticationFailureException, BadUsernameException, ConsentRequiredE...
2,776
838
from django.contrib import admin from .models import * @admin.register(BlogPost) class BlogPostAdmin(admin.ModelAdmin): list_display = [f.name for f in BlogPost._meta.fields]
180
58
from django.urls import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings from .views import open_new_window_view, quit_app_view app_name = 'filemenu' urlpatterns = [ path('new', open_new_window_view, name='open_new...
516
167
from abc import ABCMeta, abstractmethod class BackgroundJobInterface: __metaclass__ = ABCMeta @abstractmethod def enqueue(self, f, *args, **kwargs): pass @abstractmethod def scheduled_enqueue(self): pass @abstractmethod def get_enqueued_job_by_id(self): pass ...
379
119