text
string
size
int64
token_count
int64
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from enum import Enum class Type(Enum): STRING = 'string' NUMBER = 'number' BOOLEAN = 'boolean' DATE = 'date' DATETIME = 'datetime' TIMEOFDAY = ...
332
109
import os from pathlib import Path from shutil import copyfile def stu_activities(rootDir): # set the rootDir where the search will start # that is in home dorectory #rootDir = "Downloads" # build rootDir from rootDir with the base as home "~" rootDir = os.path.join(Path.home(),rootDir) ...
1,525
461
import matplotlib.pyplot as plt import numpy as np def plot(ac): ac=np.array(ac) ac=ac.reshape((28,28)) ac=[[int(ac2+0.48) for ac2 in ac1] for ac1 in ac] plt.imshow(ac) f=np.load("model.npz",allow_pickle=True) f2=np.load("model2.npz",allow_pickle=True) f3=np.load("model3.npz",allow_pickle=True) f4=np.load...
1,122
550
import logging import threading import time from datetime import datetime, timedelta from sqlalchemy import column, func, select from sqlalchemy.orm import SessionTransaction from actions.discord import Discord from actions.telegram import Telegram from common.database import session from common.models import Event, ...
2,021
571
import attr import binascii import zigpy.types as t import zigpy_deconz.types as dt import zigpy_deconz_parser.types as pt @attr.s class Version(pt.Command): SCHEMA = (t.uint32_t, ) version = attr.ib(factory=SCHEMA[0]) def pretty_print(self, *args): self.print("Version: 0x{:08x}".format(self.ver...
9,148
3,540
#!/usr/bin/python3 import math import os import random import sys import time from operator import itemgetter import pygame from screeninfo import get_monitors from Xlib import display from level import Level DEBUG = "XSCREENSAVER_WINDOW" not in os.environ BLACK = (0, 0, 0) WHITE = (255, 255, 255) pygame.init()...
2,240
825
# Quotes from: https://www.notion.so/Quotes-by-Naval-Ravikant-3edaf88cfc914b06a98b58b62b6dc222 dic = [\ "Read what you love until you love to read.",\ "True Wisdom Comes From Understanding, Not Memorization.",\ "Meditation is the art of doing nothing. You cannot do meditation. By definition, if you’re doing some...
29,789
7,784
import json from database_utils import DatabaseUtils from mobileapp import MobileApp from registrar import RegistrarAPI import logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s: %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) logger = logging.getLogger(__name__) ...
9,520
2,962
from agents.custom_agent import CustomAgent from agents.torchbeast_agent import TorchBeastAgent from envs.wrappers import addtimelimitwrapper_fn ################################################ # Import your own agent code # # Set Submision_Agent to your agent # # Set NUM_PARALLEL_ENVI...
1,294
378
from typing import Union try: import winreg except ImportError: pass from ..template import BaseTemplate from ..exceptions import NotFoundError class RegistryTemplate(BaseTemplate): root = winreg.HKEY_CURRENT_USER def __init__(self, name='xmem'): """ :param name: name of your applic...
1,452
423
from math import sqrt, ceil def isPrime(x): """Primality test. Param x: int. Returns True if x is prime, False otherwise. """ if x <= 0: return False elif x == 2 or x == 3: return True else: for i in range(2, ceil(sqrt(x)) + 1): if x % i == 0: ...
610
201
"""Script to analyze the Dataframes """ import pandas as pd import matplotlib.pyplot as plt german_df = pd.read_parquet('/home/felix/Desktop/Document_Scanner/text_classifier/data/german.parquet') english_df = pd.read_parquet('/home/felix/Desktop/Document_Scanner/text_classifier/data/english.parquet') german_df.to_csv(...
1,279
469
import serial import time import numpy as np import pandas as pd from timeflux.core.exceptions import WorkerInterrupt from timeflux.helpers import clock from timeflux.core.node import Node class SerialDevice(Node): """A generic serial device driver. Attributes: o (Port): Stream from the serial devic...
4,742
1,404
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2021/3/15 10:40 上午 # @File : infer.py # @Author: johnson # @Contact : github: johnson7788 # @Desc : 推理模型 import opennre def infer_wiki80_cnn_softmax(): model = opennre.get_model('wiki80_cnn_softmax') result = model.infer({ ...
2,147
825
#!/usr/bin/env python """ A standalone script that prepares a set of input to e3sm_diags to be ran as a container, and then runs e3sm_diags as a container. """ import os import sys import importlib import argparse import subprocess # Change these commands if needed. SHIFTER_COMMAND = 'shifter --volume=$REFERENCE_DATA_...
6,938
2,254
import sys, os import shutil def SilentMkdir(theDir): try: os.mkdir(theDir) except: pass return 0 def Run_00_CameraInit(baseDir, binDir, srcImageDir): # SilentMkdir(baseDir + "/00_CameraInit") binName = binDir + "\\aliceVision_cameraInit" # .exe" dstDir = baseDir + "/" # ...
15,601
6,051
import csv import itertools import json import tempfile import re import pytest from browser_history.utils import get_browsers from browser_history.cli import cli, AVAILABLE_BROWSERS from .utils import ( # noqa: F401 become_linux, become_mac, become_windows, change_homedir, ) # pylint: disable=redef...
17,448
5,380
# -*- coding: utf-8 -*- def case_insensitive_string(string, available, default=None): if string is None: return default _available = [each.lower() for each in available] try: index = _available.index(f"{string}".lower()) except ValueError: raise ValueError(f"unrecognised in...
3,363
1,027
import HTMLParser import os import re import sys import time import urllib import urllib2 import xbmc import xbmcaddon import xbmcgui import xbmcplugin __addon__ = xbmcaddon.Addon() __cwd__ = xbmc.translatePath(__addon__.getAddonInfo('path')).decode("utf-8") __resource__ = xbmc.translatePath(os.path.join(__c...
12,527
4,868
from django import forms from . import widgets from .models import Ticket, TicketItem #Creating html forms. # Each class interacts with a model. Fields for a form are chosen in 'fields' class TicketForm(forms.ModelForm): #setting timeDue to have specific formatting timeDue = forms.DateTimeField( input_...
912
264
# # Copyright 2021 Budapest Quantum Computing Group # # 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 ...
1,089
346
from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_emamil_successful(self): """Test creating a new user with an email is successful""" email = 'test@test.com' password = 'testpass123' user = get_user_model().objects....
799
207
begin_unit comment|'# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory' nl|'\n' comment|'# All Rights Reserved' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with t...
6,736
3,059
from channels.staticfiles import StaticFilesConsumer from .consumers import ws_connect, ws_receive, ws_disconnect, new_contestant, start_quiz, submit_answer from channels import include, route # Although we could, there is no path matching on these routes; instead we rely # on the matching from the top-level routing. ...
1,308
387
#!/usr/bin/env python3 """ MySql Parser for graphical presentation """ import mysql.connector import datetime from mysql.connector import Error from datetime import datetime, timedelta import json def pull_flow_graphs(node, time, sql_creds, db): """ Pulls the RX and TX information from the database to di...
2,039
649
#!/usr/bin/env python # cardinal_pythonlib/sphinxtools.py """ =============================================================================== Original code copyright (C) 2009-2020 Rudolf Cardinal (rudolf@pobox.com). This file is part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0 ...
35,203
9,751
# Generated by Django 2.1.3 on 2018-11-08 21:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('monsterapi', '0004_name'), ] operations = [ migrations.AddField( model_name='monster', ...
481
169
import pandas as pd from wikidataintegrator import wdi_login import utils from login import WDPASS, WDUSER import argparse import sys parser = argparse.ArgumentParser() df = utils.get_complex_portal_species_ids() print(df.to_markdown())
239
79
# -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-01-23 19:07 from __future__ import unicode_literals import logging from django.db import migrations from sentry import eventstore from sentry.utils.query import RangeQuerySetWrapper from sentry.utils.snuba import ( SnubaError, QueryOutsideRetentio...
2,398
687
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/5/5 12:39 AM @Author : sweetcs @Site : @File : config.py @Software: PyCharm """ DEBUG=True HOST="0.0.0.0" PORT=9292
190
100
import cv2 print(cv2.getBuildInformation())
45
16
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Bitcoin Core developers # Copyright (c) 2019 The Unit-e developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://opensource.org/licenses/MIT. import argparse import os import subprocess import sys import platform impo...
26,733
8,840
import discord from lib import utils async def _guild_list(page=1): try: page = int(page) - 1 except Exception: await _guild_list.message.channel.send( ":warning: use number to navigate between pages" ) return guilds = utils.get_guilds() pages = [[]] ...
1,239
452
# # Copyright (c) 2021, SteelHead Industry Cloud, Inc. <info@steelheadhq.com>. # All Rights Reserved. * # # # Import Core Modules # For consistency with other languages, `cdk` is the preferred import name for the CDK's core module. from aws_cdk import core as cdk from aws_cdk.core import App, Stack...
4,184
1,518
# ============================================================================= # System imports import logging import RPi.GPIO as RPiGPIO # ============================================================================= # Logger setup logger = logging.getLogger(__name__) # =============================================...
2,443
699
from django.contrib import admin from .models import Evento, EventoCategoria, InscricaoSolicitacao # Register your models here. admin.site.register(Evento) admin.site.register(EventoCategoria) admin.site.register(InscricaoSolicitacao)
235
78
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.statements import * from indra.preassembler.grounding_mapper import GroundingMapper, \ default_grounding_map def get_statements(): statements = [] ...
4,949
1,784
import sys # import osgeo.utils.gcps2wld as a convenience to use as a script from osgeo.utils.gcps2wld import * # noqa from osgeo.utils.gcps2wld import main from osgeo.gdal import deprecation_warn deprecation_warn('gcps2wld', 'utils') sys.exit(main(sys.argv))
263
98
class Solution: def frequencySort(self, s: str) -> str: return reduce(lambda a, b: a + b[1]*b[0], Counter(s).most_common(), '')
139
49
import unittest import base_test import json class PrincipalClaimTest(base_test.BaseTest): def setUp(self): super(PrincipalClaimTest, self).setUp() self._org = self.post('/api/orgs', {"name":"claim_org", "url":"https://myorg.com"}) self._principal = self.post('/api/orgs/%s/principals' % sel...
2,138
797
#!/usr/bin/env python ''' The most simple case how to use standalone mode with several `run` calls. ''' from brian2 import * set_device('cpp_standalone', build_on_run=False) tau = 10*ms I = 1 # input current eqs = ''' dv/dt = (I-v)/tau : 1 ''' G = NeuronGroup(10, eqs, method='exact') G.v = 'rand()' mon = StateMonitor...
510
224
# What should be printing the next snippet of code? intNum = 10 negativeNum = -5 testString = "Hello " testList = [1, 2, 3] print(intNum * 5) print(intNum - negativeNum) print(testString + 'World') print(testString * 2) print(testString[-1]) print(testString[1:]) print(testList + testList) # The sum of each three fir...
801
339
from django.urls import path from django.views.generic import TemplateView from .views import CdchangerListView, CdchangerWizard urlpatterns = [ path('', TemplateView.as_view(template_name='cdchanger/index.html'), name='index'), path('cdchangers', CdchangerListView.as_view(), name='cdchangers'), path('cdc...
801
275
import pandas as pd import yaml import gzip import re import urllib import shutil # for removing and creating folders from pathlib import Path from tqdm.autonotebook import tqdm import warnings from Bio import SeqIO from Bio.Seq import Seq from .cloud_caching import CLOUD_CACHE, download_from_cloud_cache CACHE_PATH...
9,255
2,862
from modules import menu, hosts, logMail, status, webpagina, zoekInLog def main(): """" Dit is de start file/functie van het programma, hierin worden alle modules geladen en zo nodig uitgevoerd. Het menu wordt gestart en de keuze wordt verwezen naar een van de modules. Geimporteerde modules: - menu...
851
303
import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import time from datetime import timedelta import os # Importing a helper module for the functions of the Inception model. import inception import cifar10 from cifar10 import num_classes from inception import transfer_values_cache #Importing...
15,329
4,708
from rest_framework.exceptions import NotFound, PermissionDenied from rest_framework.generics import ( CreateAPIView, DestroyAPIView, RetrieveUpdateAPIView, ) from .permissions import ( IsAdminOrModeratorOrReadOnly, IsOwnerOrAdminOrModeratorOrReadOnly, IsOwnerOrReadOnly, ) from .serializers impo...
2,276
667
from app.questionnaire_state.state_item import StateItem class StateSection(StateItem): def __init__(self, item_id, schema_item): super().__init__(item_id=item_id, schema_item=schema_item) self.questions = [] self.children = self.questions
270
81
#!/usr/bin/env python from __future__ import print_function import sys sys.path.insert(0, "/home/liangjiang/code/keras-jl-mean/") from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import model_from_json from keras.models import Sequential from keras.layers imp...
8,046
2,966
import numpy as np import pvlib.pvsystem as pvsyst import interconnection as connect import matplotlib.pyplot as plt def calculate_reverse_scaling_factor(voltages, breakdown_voltage, miller_exponent): """ :param voltages: numpy array of voltages :param breakdown_voltage: the minimum voltage before the ave...
14,221
4,273
# -*- coding: utf-8 -*- import os from os.path import dirname, join SECRET_KEY = os.urandom(16) # configure file based session SESSION_TYPE = "filesystem" SESSION_FILE_DIR = join(dirname(__file__), "cache") # configure flask app for local development ENV = "development"
284
98
import requests from bs4 import BeautifulSoup import re from selenium import webdriver import model URL = "https://sobooks.cc" VERIFY_KEY = '2019777' def convert_to_beautifulsoup(data): """ 用于将传过来的data数据包装成BeautifulSoup对象 :param data: 对应网页的html内容数据 :return: 对应data的BeautifulSoup对象 """ bs = Bea...
5,610
2,606
import unittest import subprocess import re from os import environ class MoveRatingTestBasic(unittest.TestCase): def setUp(self): if environ.get('OMDB_API_KEY') is None or len(environ.get('OMDB_API_KEY')) < 1: raise Exception("The OMDB_API_KEY environment variable is not set. Unable to run test...
2,545
826
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '1.9.0' version = '1.9.0' full_version = '1.9.0' git_revision = '07601a64cdfeb1c0247bde1294ad6380413cab66' release = True if not release: version = full_version
228
117
# Generated by Django 3.1.4 on 2021-01-05 03:33 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Posts', fields=[ ('id', models.AutoField(au...
620
185
import sys class Reporter(object): '''Collect and report errors.''' def __init__(self, args): '''Constructor.''' super(Reporter, self).__init__() self.messages = [] def check_field(self, filename, name, values, key, expected): '''Check that a dictionary has an expected v...
1,450
419
""" Graph i/o helpers """ import math from pathlib import Path import networkx as nx import numpy as np from src.utils import ColorPrint as CP, check_file_exists, print_float # TODO: add LFR benchmark graphs class GraphReader: """ Class for graph reader .g /.txt: graph edgelist .gml, .gexf for Geph...
10,722
3,588
import csv import re class Arquivo: def __init__(self, path): rp = re.compile("^ *(\d+) +(\d+)\n?$") self.alturas = [] self.duracoes = [] linecount = 1 with open(path) as f: for line in f: match = rp.match(line) if match: ...
1,241
406
'''OpenGL extension ARB.shader_clock This module customises the behaviour of the OpenGL.raw.GL.ARB.shader_clock to provide a more Python-friendly API Overview (from the spec) This extension exposes a 64-bit monotonically incrementing shader counter which may be used to derive local timing information within a ...
937
275
from __future__ import absolute_import, unicode_literals from django.test import TestCase from tuiuiu.tests.utils import TuiuiuTestUtils class AdminAPITestCase(TestCase, TuiuiuTestUtils): def setUp(self): self.login()
234
77
import argparse import requests import youtube_dl from bs4 import BeautifulSoup from jsonfinder import jsonfinder from nested_lookup import nested_lookup parser = argparse.ArgumentParser(description='Download YouTube videos from a channel using youtube-dl.') parser.add_argument('channelURL', metavar='url', type=str, h...
1,933
592
import cv2 import numpy as np # Create a VideoCapture object cap = cv2.VideoCapture(0) # Check if camera opened successfully if (cap.isOpened() == False): print("Unable to read camera feed") # Default resolutions of the frame are obtained.The default resolutions are system dependent. # We convert the resolutions ...
1,415
483
from models.torch.trainer import SupervisedNNModelTrainConfig, Trainer class KerasTrainer(Trainer): def __init__( self, train_config: SupervisedNNModelTrainConfig ): super(KerasTrainer, self).__init__(train_config) def fit(self, train_data, eval_data=None, callbacks=None,...
2,502
790
"""Given a string and a pattern, find all anagrams of the pattern in the given string. Write a function to return a list of starting indices of the anagrams of the pattern in the given string.""" """Example: String="ppqp", Pattern="pq", Output = [1, 2] """ def find_string_anagrams(str1, pattern): result...
1,168
357
from functools import partial from django.urls import path from .views import openapi_json, swagger, home def get_openapi_urls(api: "NinjaAPI"): result = [path("", partial(home, api=api), name=f"api-root")] if api.openapi_url: result.append( path( api.openapi_url.lstrip("/...
826
239
def table_pkey(table): query = f"""SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.table_n...
1,243
459
from django.apps import AppConfig class django_event_signupConfig(AppConfig): name = 'django_event_signup'
113
36
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-29 18:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('places', '0027_auto_20171229_1606'), ] operations = [ migrations.AddField( ...
515
184
import paho.mqtt.client as mqtt import uuid import time # Test code to trig the gateway to update with mqtt. # Requirements: # - pip install paho-mqtt stopMqttClient = False # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print('Conn...
1,798
577
from builtins import str import collections import contextlib import functools import itertools import io import os import re import six import subprocess import threading import tempfile import time import traceback import termcolor from . import command from . import parser COLORS = ['yellow', 'blue', 'red', 'gre...
11,863
3,285
from demo.components.server import server from chips.api.api import * def application(chip): eth = Component("application.c") eth( chip, inputs = { "eth_in" : chip.inputs["input_eth_rx"], "am_in" : chip.inputs["input_radio_am"], "fm_in" : chip.inputs["input...
746
253
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: __init__.py.py Author: Scott Yang(Scott) Email: yangyingfa@skybility.com Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved. Description: """
227
91
#this file contains models that I have tried out for different tasks, which are reusable #plus it has the training framework for those models given data - each model has its own data requirements import numpy as np import common_libs.utilities as ut import random import torch.nn as nn import torch.autograd as autograd...
10,926
3,398
""" Global configuration for the utility based on config files and environment variables.""" import os import re import math import yaml import multiprocessing from ddsc.core.util import verify_file_private from ddsc.exceptions import DDSUserException try: from urllib.parse import urlparse except ImportError: ...
9,669
2,891
""" Model construction utilities based on keras """ import warnings from distutils.version import LooseVersion import tensorflow.keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Flatten # from cleverhans.model import Model, NoSuchLayerError import tensorflow a...
12,781
3,559
from .db_handler import cursor from tornado import concurrent import tornado.web executor = concurrent.futures.ThreadPoolExecutor(8) def start_task(arg): print("The Task has started") # Async task return True def stop_task(arg): print("The Task has stopped") # Async task return True class Handler...
1,911
523
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ dp = [False for i in xrange(len(s)+1)] dp[0] = True for i in range(1, len(s)+1): for w in wordDict: if le...
666
225
from websaw.core import Fixture from yatl.helpers import INPUT, H1, A, DIV, SPAN, XML from .datatables_utils import DtGui mygui=DtGui() from pprint import pprint import json # ################################################################ # Grid object (replaced SQLFORM.grid) using Datatables # #####################...
9,523
2,944
import dbus from lib.cputemp.service import Descriptor import gatewayconfig.constants as constants class UTF8FormatDescriptor(Descriptor): def __init__(self, characteristic): Descriptor.__init__( self, constants.PRESENTATION_FORMAT_DESCRIPTOR_UUID, ["read"], ...
680
219
import gurobipy as gp from gurobipy import GRB from scheduler.utils import * import csv W = {} days = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"] departments = ["CMPE"] def create_W_matrix(): global W allAvailableSlots = get_all_available_slots() for availableSlot in allAvailabl...
4,340
1,646
from sqlalchemy import Column, Integer, String from sqlalchemy.orm import relationship from app.db.settings import Base from app.models.assignment import ModelAssignment class ModelTask(Base): __tablename__ = "tasks" id = Column(Integer, primary_key=True, index=True) title = Column(String, index=True) ...
616
182
from rest_framework import viewsets, status from rest_framework.response import Response from account.models import Account from wallet.coin_base import coin_base from wallet.models import Wallet from ico_gateway.models import IcoWallet, IcoProject from ico_gateway.serializers import ( IcoProjectSerializer, Ic...
1,777
532
#!/usr/bin/env python import rospy import numpy as np import math from discrete_tustin import ReferenceModel from vortex_msgs.msg import GuidanceData class LOSReferenceModelNode(): """ This is the ROS wrapper class for the reference model class. Nodes created: los_reference_model Subscribes to: /guidan...
2,733
1,157
import sys,os import time import datetime import random import re import json import requests from flask import Flask, jsonify from flasgger import Swagger # pip install flasgger from flasgger import swag_from from flask import request from api_helper import GretNet_API_Helper LOCAL_PATH = os.path.abspath(os....
2,225
676
""" paw_structure.ion ----------------- Ion complex detection using geometric :ref:`algorithm<Control_ION_algorithm>`. Main routine is :func:`.ion_find_parallel`. Dependencies: :py:mod:`functools` :py:mod:`miniutils` :py:mod:`numpy` :py:mod:`pandas` :mod:`.neighbor` :mod:`.utility` :class:...
13,051
3,828
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('facilities', '0001_auto_20160328_1426'), ] operations = [ migrations.AddField( model_name='facilityunit', ...
720
233
# Copyright (c) 2015-2016 Maciej Dems <maciej.dems@p.lodz.pl> # See LICENSE file for copyright information. import sys if 'PySide6' in sys.modules: from PySide6.QtWidgets import QMessageBox, QLabel, QTextEdit _exec_attr = 'exec' elif 'PyQt6' in sys.modules: from PyQt6.QtWidgets import QMessageBox, QLabel, ...
4,547
1,434
# pvtrace is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # pvtrace is distributed in the hope that it will be useful, # but WITHOUT...
11,475
3,858
# # Copyright 2017 Vitalii Kulanov # class ClientException(Exception): """Base Exception for Dropme client All child classes must be instantiated before raising. """ pass class ConfigNotFoundException(ClientException): """ Should be raised if configuration for dropme client is not specif...
621
157
from django.apps import AppConfig class SageConfig(AppConfig): name = 'sage'
83
28
import numpy as np import matplotlib.pyplot as plt import pandas as pd from matplotlib.colors import LinearSegmentedColormap ms_color = [0.12156863, 0.46666667, 0.70588235, 1] hc_color = [1., 0.49803922, 0.05490196, 1] SMALL_SIZE = 12 MEDIUM_SIZE = 14 BIGGER_SIZE = 16 plt.rc('font', size=SMALL_SIZE) # contr...
11,058
4,744
# coding=utf-8 import io import os import re from setuptools import setup, find_packages def get_path(*args): return os.path.join(os.path.dirname(__file__), *args) def read_from(filepath): with io.open(filepath, 'rt', encoding='utf8') as f: return f.read() def get_requirements(filename='requiremen...
1,670
547
"""Map phrases to preferred phrases.""" import logging from collections import namedtuple PhraseMapping = namedtuple("PhraseMapping", "preferred_phrase phrase_length") SortableMatch = namedtuple( "SortableMatch", "start descending_phrase_length end preferred_phrase") class PhraseMapper: """Rew...
3,110
888
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import update_wrapper, wraps def disable(func): """ Disable a decorator by re-assigning the decorator's name to this function. For example, to turn off memoization: >>> memo = disable """ return func def decorator(decorator_func...
3,092
1,103
#!/usr/bin/env python3 ''' kicad-footprint-generator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. kicad-footprint-generator is distribut...
13,670
5,155
# Generated by Django 3.1.3 on 2020-11-28 23:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
1,048
329
import numpy as np def flatten_array_list(a_list): return np.concatenate([l.ravel() for l in a_list]) def unflatten_array_list(array, shapes): c = 0 l = [] for s in shapes: tmp = np.array(array[c:c + np.prod(s)]) reshaped = np.reshape(tmp, s) c += np.prod(s) l.append...
1,158
515
# coding=utf-8 import os import jinja2 import jinja2.ext from .render import md_to_jinja MARKDOWN_EXTENSION = '.md' class MarkdownExtension(jinja2.ext.Extension): def preprocess(self, source, name, filename=None): if name is None or os.path.splitext(name)[1] != MARKDOWN_EXTENSION: return ...
804
266
# Configuration file for EmptySource import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.load("FWCore.Framework.test.cmsExceptionsFatal_cff") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(8*5) ) runToLumi = ((2,1),(10,3),(20,7) ) def findRunForLumi( lumi) : l...
1,553
608
# Copyright (c) 2018 Mengye Ren, Eleni Triantafillou, Sachin Ravi, Jake Snell, # Kevin Swersky, Joshua B. Tenenbaum, Hugo Larochelle, Richars S. Zemel. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
3,666
1,172