text
string
size
int64
token_count
int64
import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from datetime import datetime import json from base import Session, engine, Base from enum import...
3,379
1,114
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class MybankCreditSceneprodCommonQueryModel(object): def __init__(self): self._app_seq_no = None self._ext_param = None self._operation_type = None self._org_code = None...
3,411
1,109
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 13 18:23:08 2019 This scrip is for training the experiement end2end @author: li """ import tensorflow as tf import models.AE as AE import optimization.loss_tf as loss_tf from data import read_frame_temporal as rft import numpy as np import os import ...
32,570
10,757
import napari from pathlib import Path from magicgui import magicgui from typing import List from cellfinder_napari.utils import brainglobe_logo # TODO: # how to store & fetch pre-trained models? # TODO: params to add NETWORK_VOXEL_SIZES = [5, 1, 1] CUBE_WIDTH = 50 CUBE_HEIGHT = 20 CUBE_DEPTH = 20 # If using ROI, h...
10,781
3,310
from setuptools import setup, find_packages version = {} with open("nltools/version.py") as f: exec(f.read(), version) with open("requirements.txt") as f: requirements = f.read().splitlines() extra_setuptools_args = dict(tests_require=["pytest"]) setup( name="nltools", version=version["__version__"]...
1,414
448
import os import warnings from dotenv import find_dotenv, load_dotenv from yacs.config import CfgNode as ConfigurationNode from pathlib import Path # Please configure your own settings here # # YACS overwrite these settings using YAML __C = ConfigurationNode() ### EXAMPLE ### """ # data augmentation parameters with...
4,028
1,435
list1 = [] list2 = [] list3 = [] cont = 0 while cont < 10: valor = int(input('Digite um numero na lista 1: ')) list1.append(valor) valor2 = int(input('Digite um numero na lista 2: ')) list2.append(valor2) cont = cont + 1 if cont == 10: for i in list1: if i in list2: ...
475
180
import os from shutil import rmtree import cv2 import docker import numpy as np import open3d as o3d from pypcd import pypcd from src.metrics import metrics from src.metrics.metrics import multi_value, mean from src.parser import loaders, create_parser UNSEGMENTED_COLOR = np.asarray([0, 0, 0], dtype=int) algos = { ...
7,693
2,715
from responsum.utils.fits_file import FITSFile, FITSExtension as FE import pkg_resources class FITSExtension(FE): # I use __new__ instead of __init__ because I need to use the classmethod .from_columns instead of the # constructor of fits.BinTableHDU def __init__(self, data_tuple, header_tuple): ...
491
166
""" @package mi.instrument.seabird.sbe26plus.ooicore.driver @file /Users/unwin/OOI/Workspace/code/marine-integrations/mi/instrument/seabird/sbe26plus/ooicore/driver.py @author Roger Unwin @brief Driver for the ooicore Release notes: None. """ __author__ = 'Roger Unwin' __license__ = 'Apache 2.0' import re import tim...
121,557
37,384
# 1) count = To count how many time a particular word & char. is appearing x = "Keep grinding keep hustling" print(x.count("t")) # 2) index = To get index of letter(gives the lowest index) x="Keep grinding keep hustling" print(x.index("t")) # will give the lowest index value of (t) # 3) find = To get index of lett...
514
182
#! -*- coding:utf-8 from typing import Callable, List, Optional import numpy as np import torch import torchvision __all__ = ["CIFAR10", "FashionMNIST"] class CIFAR10(torch.utils.data.Dataset): def __init__(self, root: str, train: bool = True, tra...
4,526
1,281
from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog import torch import numpy as np import cv2 class Model: def __init__(self,confidence_thresh=0.6): ...
1,819
653
from setuptools import setup setup( name="example-advanced-package", version="0.0.0", packages=[], )
106
36
from distutils.core import setup setup( name='pyASA', packages=['pyASA'], version='0.1.0', description='Wrapper for the Cisco ASA REST API', author='xpac', author_email='bjoern@areafunky.net', url='https://github.com/xpac1985/pyASA', download_url='https://github.com/xpac1985/pyASA/tarba...
416
162
from Qpid import QpidConnection from mxt1xx_pb2 import * from commands_pb2 import * from QpidTypes import * from qpid.messaging import * #doc http://qpid.apache.org/releases/qpid-0.14/apis/python/html/ #examples https://developers.google.com/protocol-buffers/docs/pythontutorial qpidCon = QpidConnection('192.168.0.78...
2,441
846
import numpy as np from example_functions import target_function_dict from line_search_methods import line_search_dict from main_methods import main_method_dict from config import best_params from helpers import generate_x0 def run_one(_theta, _main_method, _ls_method, params, ls_params): theta = _theta() x0...
1,574
482
# Load Packages import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.model_selection import GridSearchCV, cross_val_score from sklearn.metrics import classification_report from plots import draw_corr_heatmap import seaborn as sns ...
5,299
2,052
#!/usr/bin/python # -*- coding: utf-8 -*- """ nuxt-chalice-api のテンプレート実装です。 主に、全体で利用するグローバルスコープのリソースを初期化します。 """ import os from chalice import ( Chalice, CognitoUserPoolAuthorizer, CORSConfig ) from chalicelib import aws from chalicelib.env import store stage = store.mutation( 'chalilce.stage', os.env...
1,346
568
import matplotlib.pyplot as plt import numpy as np from acconeer.exptool import configs, utils from acconeer.exptool.clients import SocketClient, SPIClient, UARTClient def main(): args = utils.ExampleArgumentParser(num_sens=1).parse_args() utils.config_logging(args) if args.socket_addr: client =...
2,186
780
from .bot import Bot class MultiBot(Bot): strategies = [] def __init__(self, strategies, config=None): super().__init__(strategy=None, config=config) self.strategies = strategies # override this to inherit def __start(self): for st in self.strategies: st.add_sessi...
437
134
#!/usr/bin/env python """Setup file for the ``mixt`` module. Configuration is in ``setup.cfg``.""" from setuptools import setup setup()
140
46
def _recipes_pil_prescript(plugins): try: import Image have_PIL = False except ImportError: from PIL import Image have_PIL = True import sys def init(): if Image._initialized >= 2: return if have_PIL: try: impor...
1,235
316
from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class GetTypeView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = request.user if hasattr(user, 'vendor'): t...
691
185
# Thinking probabilistically-- Discrete variables!! # Statistical inference rests upon probability. Because we can very rarely say anything meaningful with absolute certainty from data, we use probabilistic language to make quantitative statements about data. In this chapter, you will learn how to think probabilistical...
9,390
2,694
''' This is an abstract example of Extracting in an ETL pipeline. Inspired from the "Introduction to Data Engineering" course on Datacamp.com Author: Alex Nakagawa ''' import requests # Fetch the Hackernews post resp = requests.get("https://hacker-news.firebaseio.com/v0/item/16222426.json") # Print the response par...
1,008
314
""" * 보석과 돌 J는 보석이며, S는 갖고 있는 돌이다. S에는 보석이 몇 개나 있을까? 대소문자는 구분한다. - Example 1 Input : J = "aA", S = "aAAbbbb" Output : 3 - Example 2 Input : J = "z", S = "ZZ" Output : 0 """ import collections class Solution: # Counter로 계산 생략 def numJewelsInStones(self, J: str, S: str) -> int: freqs = collections.Count...
531
273
"""empty message Revision ID: e1c435b9e9dc Revises: 2527092d6a89 Create Date: 2020-06-11 14:22:00.453626 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e1c435b9e9dc' down_revision = '2527092d6a89' branch_labels = None depends_on = None def upgrade(): # ...
774
296
import unittest from pyquilted.quilted.contact import * from pyquilted.quilted.contacts_list import ContactsList class TestContactsList(unittest.TestCase): def test_contact_list(self): contacts = ContactsList() email = EmailContact('jon.snow@winterfell.got') phone = PhoneContact('555-123-4...
1,345
403
from __future__ import print_function import time import uuid import Adafruit_BluefruitLE CHARACTERISTIC_SERVICE_UUID = uuid.UUID('0000fee0-0000-1000-8000-00805f9b34fb') CHARACTERISTIC_DATA_UUID = uuid.UUID('0000fee1-0000-1000-8000-00805f9b34fb') provider = Adafruit_BluefruitLE.get_provider() def main(): provi...
3,110
1,560
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
4,902
1,474
#!/usr/bin/env python3 from .main import rplint if __name__ == "__main__": rplint.main(prog_name=__package__)
115
46
#!/usr/bin/env python from __future__ import division from numpy import sqrt, cos, sin, arctan, exp, abs, pi, conj from scipy import array, dot, sum class JonesVector: """ A Jones vector class to represent polarized EM waves """ def __init__(self,Jarray=array([1,0])): self.Jx = Jarray[0] self.J...
3,368
1,209
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
2,560
658
#!/usr/bin/env python import json import pathlib import sys input_dir = pathlib.Path(sys.argv[2]) output_dir = pathlib.Path(sys.argv[1]) output_file = output_dir / "data.parsed.ndjson" results = [] for input_file in input_dir.glob("data.raw.*.json"): with input_file.open() as fin: results.extend(json.loa...
460
165
# example of redefinition __repr__ and __str__ of exception class MyBad(Exception): def __str__(self): return 'My mistake!' class MyBad2(Exception): def __repr__(self): return 'Not calable' # because buid-in method has __str__ try: raise MyBad('spam') except MyBad as X: print(X) #...
563
210
import skimage.color import matplotlib.pyplot as plt import numpy as np import cv2 import os import imghdr import time """ Duplicate Image Finder (DIF): function that searches a given directory for images and finds duplicate/similar images among them. Outputs the number of found duplicate/similar image pairs with a l...
7,998
2,254
# A função min_max deverá rodar em O(n) e o código não pode usar nenhuma # lib do Python (sort, min, max e etc) # Não pode usar qualquer laço (while, for), a função deve ser recursiva # Ou delegar a solução para uma função puramente recursiva import unittest def bora(cont, seq, min, max): if cont < len(seq): ...
1,572
596
import argparse import pickle from tokenization import Vocab, Tokenizer TOKENIZER = ('treebank', 'mecab') def argparser(): p = argparse.ArgumentParser() # Required parameters p.add_argument('--corpus', default=None, type=str, required=True) p.add_argument('--vocab', default=None, type=str, required=T...
3,927
1,237
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import json import boto3 import os from aws_lambda_powertools import Logger logger = Logger() client = boto3.client('stepfunctions') sfnArn = os.environ['SFN_ARN'] def lambda_handler(event, context): # TODO impl...
650
216
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the AES decrypter object.""" import unittest from dfvfs.encryption import aes_decrypter from dfvfs.lib import definitions from tests.encryption import test_lib class AESDecrypterTestCase(test_lib.DecrypterTestCase): """Tests for the AES decrypter object....
3,068
1,167
#Q2 # “If you have an apple and I have an apple and we exchange these apples then # you and I will still each have one apple. But if you have an idea and I have # an idea and we exchange these ideas, then each of us will have two ideas.” # George Bernard Shaw class Person: apples = 0 ideas = 0 johanna = Perso...
4,460
1,513
# verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_1_C from python.lib.is_prime import isprime print(sum(isprime(int(input())) for _ in range(int(input()))))
205
82
import torch import numpy as np PAD_TOKEN_INDEX = 0 def pad_masking(x, target_len): # x: (batch_size, seq_len) batch_size, seq_len = x.size() padded_positions = x == PAD_TOKEN_INDEX # (batch_size, seq_len) pad_mask = padded_positions.unsqueeze(1).expand(batch_size, target_len, seq_len) return pa...
691
270
from jesse.store import store from jesse import helpers from jesse.services import logger def save_daily_portfolio_balance(): balances = [] # add exchange balances for key, e in store.exchanges.storage.items(): balances.append(e.assets[helpers.app_currency()]) # add open position values ...
576
183
################################################################################ # # cmd_copyToExternal.py # # Author: Oliver Hotz | Chris Sprance # # Description: Copies Geo/Weights/Morphs/UV's to External File # # Last Update: # ###############################################################################...
1,020
342
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/. import ast import os import re import shlex from itertools import zip_longest from string import Template from typing import * from .pithy.fs import * from .pithy.io import * from .pithy.types import * # type: ignore fro...
17,828
5,940
"""Asynchronous Python client for the Photoprism REST API.""" from .photoprism import API, Photoprism # noqa
111
37
#!/usr/bin/python vm_cfg = { 'name_label': 'APIVM', 'user_version': 1, 'is_a_template': False, 'auto_power_on': False, # TODO 'memory_static_min': 64, 'memory_static_max': 128, #'memory_dynamic_min': 64, #'memory_dynamic_max': 128, 'VCPUs_policy': 'credit', 'VCPUs...
5,558
1,979
from portfolyo import testing, dev from portfolyo.core.pfline import single_helper from portfolyo.tools.nits import Q_ from portfolyo.tools.stamps import FREQUENCIES import pandas as pd import pytest def assert_w_q_compatible(freq, w, q): if freq == "15T": testing.assert_series_equal(q, w * Q_(0.25, "h"),...
6,171
2,353
"""Competitions for parameter tuning using Monte-carlo tree search.""" from __future__ import division import operator import random from heapq import nlargest from math import exp, log, sqrt from gomill import compact_tracebacks from gomill import game_jobs from gomill import competitions from gomill import competi...
31,044
8,688
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: ''' T: O(n log n) and S: O(1) ''' n = len(nums) sorted_nums = sorted(nums) start, end = n + 1, -1 for i in range(n): if nums[i] != sorted_nums[i]: ...
460
156
import pandas as pd import numpy as np import matplotlib.pyplot as plt #%matplotlib inline import codecs import lightgbm as lgb from sklearn.model_selection import StratifiedShuffleSplit from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score # Read data image_file_path = './simulated_dpc_d...
9,705
3,613
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py # oauth constants HOSTNAME = "http://hackathon.chinacloudapp.cn" # host name of the UI site QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA HACkATHON_API_ENDPOINT = ...
3,488
1,452
#%% import sys import numpy as np from typing import Any, List import pandas as pd from sklearn.preprocessing import MinMaxScaler sys.path.append('C:/Users/panos/Documents/Διπλωματική/code/fz') from arfftocsv import function_labelize import csv colnames =['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thal...
1,036
413
""" The follwing constructor classes exists here: +------------------------------------------+---------------------------------------+ | Class | Description | +==========================================+=======================================+ | :py:class:`~...
10,323
3,208
# Generated by Django 2.2.7 on 2020-05-14 03:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('newsletter', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='Newsletter', new_name='Subscriber', ...
330
116
from django.views.generic import TemplateView from main.permissions import ResidentLoginRequiredMixin class DashboardView(ResidentLoginRequiredMixin, TemplateView): template_name = "index_dashboard.html"
210
59
#!/usr/bin/env python3 """awspfx Usage: awspfx.py <profile> awspfx.py [(-c | --current) | (-l | --list) | (-s | --swap)] awspfx.py token [(-p | --profile) <profile>] awspfx.py sso [(login | token)] [(-p | --profile) <profile>] awspfx.py -h | --help awspfx.py --version Examples: awspfx.py ...
9,179
3,103
import re from model.contact import Contact def test_contact_info_from_home_page(app, db): app.navigation.open_home_page() contact_from_home_page = sorted(app.contact.get_contact_list(), key=Contact.id_or_max) def clean(contact): return Contact(id=contact.id, firstname=contact.firstname.strip(), ...
3,694
1,238
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: if not target or not original or not...
628
179
#!/usr/bin/env python # -*- coding: utf-8 -*- # Writing Our First Classifier - Machine Learning Recipes #5 #https://www.youtube.com/watch?v=AoeEHqVSNOw&list=PLOU2XLYxmsIIuiBfYad6rFYQU_jL2ryal&index=1 from scipy.spatial import distance from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accu...
1,790
730
""" Re-tooled version of the script found on VideoToTextDNN: https://github.com/OSUPCVLab/VideoToTextDNN/blob/master/data/process_frames.py """ import sys import os import argparse import time from multiprocessing import Pool def main(args): src_dir = args.src_dir dst_dir = args.dst_dir start = int(args.s...
2,323
820
from django.contrib.auth.hashers import get_hashers_by_algorithm from django.core import checks @checks.register(checks.Tags.security, deploy=True) def check_for_plaintext_passwords(app_configs, **kwargs): if "plaintext" in get_hashers_by_algorithm(): yield checks.Critical( "Plaintext module s...
383
115
class City: name = "city" size = "default" draw = -1 danger = -1 population = []
105
38
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 24 17:19:39 2021 @author: rayin """ import os, sys import numpy as np import pandas as pd import torch import warnings import random import torchvision.models as models from sdv.tabular import CTGAN from sdv.evaluation import evaluate from sdv.met...
9,340
3,329
from app.extensions import db from flask import current_app class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) access_token = db.Column(db.String()) jit_feature = db.Column(db.Boolean()) recurrence_resch_feature = db.Column(db.Boolean()) streaks_feature ...
1,265
402
from dataclasses import dataclass, field from enum import Enum from typing import Optional from output.models.boeing_data.ipo4.ipo_xsd.ipo import AddressType __NAMESPACE__ = "http://www.example.com/IPO" class Usstate(Enum): AK = "AK" AL = "AL" AR = "AR" CA = "CA" PA = "PA" @dataclass class Ukad...
1,240
385
# Jared Dyreson # CPSC 386-01 # 2021-11-29 # jareddyreson@csu.fullerton.edu # @JaredDyreson # # Lab 00-04 # # Some filler text # """ This module contains the Intro display class """ import pygame import functools import sys import pathlib import typing import os import dataclasses import random from pprint import ppr...
5,060
1,538
from oscar.apps.checkout.models import * # noqa
49
18
from rest_framework import serializers from apps.calendarioPago.models import CalendarioPago from apps.cliente.models import Cliente from apps.cuenta.models import Cuenta from apps.grupo.models import Grupo from apps.miembro.models import Miembro from apps.transaccion.models import Transaccion # Serializers define t...
1,642
485
import re from .walk import walk, WalkState from .utils import caret, is_inline_element, is_snippet, push_tokens, should_output_attribute from .comment import comment_node_before, comment_node_after, CommentWalkState from ...abbreviation import Abbreviation, AbbreviationNode, AbbreviationAttribute from ...abbreviation....
8,194
2,365
"""Secant Method module""" from numeric_method import NumericMethod class SecantMethod(NumericMethod): """Secant method class""" def secant_method(self, previous_value, value): """The secant method itself @param previous_value: first value of interval @param previous_value: second va...
2,584
809
import os import re MODEL_FILE_FORMAT = 'weights.{epoch:02d}-{val_loss:.2f}.h5' MODEL_REGEX_PATTERN = re.compile(r'^.*weights\.(\d+)\-\d+\.\d+\.h5$') LAST_MODEL_FILE_FORMAT = 'last.h5' TEAMS_WEBHOOK_URL = os.environ.get('TEAMS_WEBHOOK_URL', '')
245
127
import numpy as np import pandas as pd from sklearn import svm from mlxtend.plotting import plot_decision_regions import matplotlib.pyplot as plt # Create arbitrary dataset for example df = pd.DataFrame({'Planned_End': np.random.uniform(low=-5, high=5, size=50), 'Actual_End': np.random.uniform(low...
977
347
from transposonmapper.importing import ( load_default_files,read_genes ) def test_output_format(): a,b,c=load_default_files(gff_file=None,essentials_file=None,gene_names_file=None) a_0,b_0,c_0=read_genes(gff_file=a,essentials_file=b,gene_names_file=c) assert type(a_0)==dict, "the gene coordinates...
2,544
1,008
""" Using http://thejit.org/static/v20/Docs/files/Options/Options-Canvas-js.html#Options.Canvas """ from django.http import HttpResponse, Http404, HttpResponseRedirect from django.urls import reverse from django.shortcuts import render, redirect, get_object_or_404 import json import os import json from libs.myuti...
4,477
1,808
# -*- test-case-name: vumi.blinkenlights.tests.test_metrics_workers -*- import time import random import hashlib from datetime import datetime from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from twisted.internet import reactor from twisted.internet.task import LoopingCall ...
14,772
4,315
from __future__ import absolute_import from django import forms from django.db import transaction from sentry.models import ( OrganizationMember, OrganizationMemberTeam, Team, ) class BaseOrganizationMemberForm(forms.ModelForm): """ Base form used by AddOrganizationMemberForm, InviteOrganization...
1,401
393
# -*- coding: utf-8 -*- # Copyright 2021 Google 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 law ...
1,589
493
from django.urls import include, path from django.conf.urls import url from endpoint.views import ( enroll_user, validate_recording, check_redis_health, redirect_flower_dashboard, ) urlpatterns = [ path("enroll", enroll_user), path("validate", validate_recording), path("redis-healthcheck", ...
401
132
from datetime import datetime from typing import List, Optional import bcrypt from sqlalchemy.orm import Session from . import models, schemas def get_user(db: Session, id: int) -> models.User: """Return a single user by id. Args: db (Session): database connection id (int): id of the user ...
3,096
946
async def run(ctx): await ctx.send(''' `bot invite link:` <https://discord.com/api/oauth2/authorize?client_id=732933945057869867&permissions=538569921&scope=bot>''')
170
82
from django.test import TransactionTestCase from polymorphic.models import PolymorphicModel, PolymorphicTypeUndefined from polymorphic.tests.models import ( Enhance_Base, Enhance_Inherit, Model2A, Model2B, Model2C, Model2D, ) from polymorphic.utils import ( get_base_polymorphic_model, r...
2,693
922
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 <pavle.portic@tilda.center> # # Distributed under terms of the BSD 3-Clause license. import hashlib import itertools import json from decimal import Decimal from multiprocessing import ( cpu_count, Pool, Process, Queue ) class D...
2,098
838
import peewee as pw from flask import g from flask import redirect from flask import render_template from flask import request from flask import url_for from myfunds.core.models import Account from myfunds.core.models import Category from myfunds.core.models import JointLimitParticipant from myfunds.web import auth fr...
5,317
1,569
# # Copyright 2018-2021 Elyra 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 agreed to in writ...
6,854
1,594
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from common import MayanAppConfig from .licenses import * # NOQA class MIMETypesApp(MayanAppConfig): name = 'mimetype' verbose_name = _('MIME types') def ready(self, *args, **kwargs): super(MIMETyp...
356
119
from packages.levels.Level import Level import packages.levels.levels as Levels import packages.resources.functions as function import packages.resources.variables as var from packages.filesystem.Directory import Directory from packages.filesystem.File import File var.bash_history = ("Check") test = Level("Instruct",...
388
105
# noinspection PyUnresolvedReferences import unittest from cython_vst_loader.vst_loader_wrapper import allocate_float_buffer, get_float_buffer_as_list, \ free_buffer, \ allocate_double_buffer, get_double_buffer_as_list class TestBuffers(unittest.TestCase): def test_float_buffer(self): pointer = ...
1,235
416
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import uuid import requests class MicrosoftTranslator: def __init__(self, subscription_key: str, subscription_region: str): self.subscription_key = subscription_key self.subscription_region = subscriptio...
1,520
418
from .common import * from .json_store import *
48
15
# -*- coding: utf-8 -*- import os import logging from sqlalchemy import create_engine, Column, Integer, String, ForeignKey from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from scraper import settings Base = declarative_base() def...
2,760
849
def to_weird_case(string): arr=string.split() count=0 for i in arr: tmp=list(i) for j in range(len(tmp)): if j%2==0: tmp[j]=tmp[j].upper() arr[count] = ''.join(tmp) count+=1 return ' '.join(arr) ''' 一个比较不错的版本 def to_weird_case(string): r...
487
190
# 经典面向对象的GUI写法 from tkinter import * from tkinter import messagebox class Application(Frame): """一个经典的GUI程序""" def __init__(self,master=None): super().__init__(master) self.master = master self.pack() self.createWidget() def createWidget(self): """创建组件""" ...
1,573
617
# Grupo da Maioridade '''Crie um programa que leia o ANO DE NASCIMENTO de SETE PESSOAS. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores''' from datetime import date anoatual = date.today().year # Pegará o ano atual configurado na máquina totalmaior = 0 totalmenor = 0 for pess...
839
292
from typing import Tuple import numpy as np import png from skimage.transform import resize def load_world(filename: str, size: Tuple[int, int], resolution: int) -> np.array: """Load a preconstructred track to initialize world. Args: filename: Full path to the track file (png). ...
2,160
671
from rest_framework import serializers from user.models import User from main.exceptions.user_exceptions import UserException user_exception = UserException class UserRegisterSerializer(serializers.ModelSerializer): password_confirmation = serializers.CharField(max_length=128) class Meta: model = U...
885
244
#!/usr/bin/env python3 import argparse import ctypes import os import sys from llvmlite import ir, binding as llvm INDEX_BIT_SIZE = 16 def parse(bf): bf = iter(bf) result = [] for c in bf: if c == "[": result.append(parse(bf)) elif c == "]": break else: ...
7,332
2,246
#!/usr/bin/env python # BSD Licence # Copyright (c) 2011, Science & Technology Facilities Council (STFC) # All rights reserved. # # See the LICENSE file in the source distribution of this software for # the full license text. """ Execute a programme that makes NetCDF-API OPeNDAP calls, capturing request events and timi...
4,715
1,464