text
string
size
int64
token_count
int64
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2022 HalfMarble LLC # Copyright 2019 Hiroshi Murayama <opiopan@gmail.com> from hm_gerber_tool.cam import FileSettings import hm_gerber_tool.rs274x from hm_gerber_tool.gerber_statements import * from hm_gerber_ex.gerber_statements import AMParamStmt, AMParamStm...
14,247
4,623
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, \ USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, \ USLaborDay, USThanksgivingDay from pandas.tseries.offsets import CustomBusinessDay class USTradingCalendar(AbstractHolidayCalendar): rules = [ ...
691
242
""" Sample view for group aware projects """ from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from dja...
3,063
845
#!/usr/bin/python # -*- coding: utf-8 -*- ''' The MIT License (MIT) Copyright (c) 2016 Wei-Hung Weng Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limita...
2,595
950
# Copyright (C) 2020 THL A29 Limited, a Tencent company. # All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); you may # not use this file except in compliance with the License. You may # obtain a copy of the License at # https://opensource.org/licenses/BSD-3-Clause # Unless required by appl...
2,540
886
from .imdb import IMDB from .sst5 import SST5 from .sst2 import SST2 from .trec import TREC from .yelp2 import YELP2 from .yelp5 import YELP5 __all__ = ('IMDB', 'SST2', 'SST5', 'TREC', 'YELP2', 'YELP5') def get_dataset(dataset_name, examples, tokenizer, text_transform=None): dataset_name = dataset_name.lower() ...
571
232
import base64 import pathlib from collections import UserDict from pypleasant.api import PleasantAPI class Attachment: def __init__(self, attachment_as_json: dict, api: PleasantAPI): self.api = api self._entry_id = attachment_as_json["CredentialObjectId"] self._attachment_id = attachment_...
2,396
758
# Helpers common to the gui from contextlib import contextmanager from PyQt5 import QtWidgets @contextmanager def safe_command(command): """ Helper to suppress AttributeErrors from commands Args: command (callable): The command to run. Any AttributeError raised by the command will be ...
857
223
import simplejson as json from .telegram_field import TelegramField class WTelegramHeader(object): def __init__(self): # self._startField = TelegramField() self._lField = TelegramField() self._cField = TelegramField() # self._crcField = TelegramField() # self._stopField = T...
2,040
643
import tweepy from .interface import show_message, show_tweet, show_user def dm(api: tweepy.API, target: str, content: str): """ Sends a direct message to target user Keyword arguments: api -- API instance for handling the request target -- Target user's screename (e.g. @jake/jak...
2,966
831
# Based on spec_tests.py from # https://github.com/commonmark/commonmark-spec/blob/master/test/spec_tests.py # and # https://github.com/github/cmark-gfm/blob/master/test/spec_tests.py import sys import os import os.path import re import md4c import md4c.domparser import pytest from normalize import normalize_html ex...
5,711
1,823
# -*- coding: utf-8 -*- # # Usage: Download all stock code info from TWSE # # TWSE equities = 上市證券 # TPEx equities = 上櫃證券 # import csv from collections import namedtuple import requests from lxml import etree TWSE_EQUITIES_URL = 'http://isin.twse.com.tw/isin/C_public.jsp?strMode=2' TPEX_EQUITIES_URL = 'http://isin.tw...
1,737
697
#----------------------------------------------------------------------- # # __init__.py (FitnessCalc) # # FitnessCalc package init module # # Copyright and Distribution # # Part of SimplePyGA: Simple Genetic Algorithms in Python # Copyright (c) 2016 Terry McKiernan (terry@mckiernan.com) # Released under The MI...
453
123
''' billing invoice section ''' from .... pyaz_utils import _call_az def list(account_name, profile_name): ''' List the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. Required Parameters: - account_name...
3,757
997
# abba # foo bar bar foo text1 = list(input()) text2 = input().split() # text1 = set(text1) print(text1) print(text2) for i in range(len(text1)): if text1[i] == "a": text1[i] = 1 else: text1[i] = 0 for i in range(len(text2)): if text2[i] == "foo": text2[i] = 1 else: te...
418
183
""" Methods for user login """ from cgi import escape from google.appengine.ext import ndb def login_fields_complete(post_data): """ validates that both login fields were filled in :param post_data: :return: """ try: user_id = escape(post_data['user_id'], quote=True) except KeyErr...
864
278
# -*- coding: utf-8 -*- """ Created on Fri Nov 16 13:20:51 2018 lstm encoder decoder for hands @author: Γιώργος """ import torch import torch.nn as nn from utils.file_utils import print_and_save class LSTM_Hands_encdec(nn.Module): # source: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-in...
1,988
739
import socket import sys import os ip_port = ('127.0.0.1',6666) sk = socket.socket() sk.bind(ip_port) sk.listen(5) def FTP_send(conn): path = input('Path:') file_name = os.path.basename(path) file_size=os.stat(path).st_size Informf=(file_name+'|'+str(file_size)) conn.send(Informf.encode()) re...
2,201
767
import re with open("day14.txt", "r") as f: data = f.read().splitlines() def apply_mask(mask, value): binary_value = f"{value:>036b}" masked_value = "".join( value if mask_value == "X" else mask_value for value, mask_value in zip(binary_value, mask) ) return int(masked_value, 2) ...
557
204
from ..Module import Module from ..TagData import TagData class host(Module): opmap = { 'infData': 'descend', 'chkData': 'descend', 'creData': 'descend', 'roid': 'set', 'name': 'set', 'clID': 'set', 'crID': 'set...
2,429
754
from setuptools import setup, find_packages setup( name='patois-stop-words', version='0.0.1', description='A list of patois stop words.', long_description=open('README.md').read(), license='MIT', author='Alexander Nicholson', author_email='alexj.nich@hotmail.com', url='https://github.co...
594
197
# ------------------------------------------------------------------------------ # Test Many Things Utilities # ------------------------------------------------------------------------------ import sys import datetime as dt import pytz from django.test import TestCase from django.utils import translation from ls.joyous...
6,924
2,272
__version__ = '10.0'
21
12
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-03-07 18:42 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('brew', '0006_auto_20180109...
5,919
1,764
from box.parser import Parser from box.generator import Generator import os class Importer: def __init__(self, path): # Path to directory containing function graphs to import self.path = os.path.abspath(path) # { "FunctionName": <Generator>, ... } self.function_declarations = {} ...
1,050
281
import json def parse_search_resp(resp): return [i['_source'] for i in json.loads(resp)['hits']['hits']] def generate_keyword_search(keyword, field='post_content'): query = { "query": { "match": { field: keyword } } } return json.dumps(query)
319
101
# https://www.hackerrank.com/challenges/the-minion-game from collections import Counter def minion_game(string): # your code goes here string = string.lower() consonants = set("bcdfghjklmnpqrstvwxyz") vowels = set("aeiou") # Stuart will get 1 point for every non-distinct substring that starts # ...
957
304
import os from docx import Document from docx.shared import Inches from docx import Document from docx.text.paragraph import Paragraph def Iceriyomu(dosyayol): document = Document('{}'.format(dosyayol)) headings = [] texts = [] para = [] giris = "" for paragraph in document.paragraphs...
1,785
687
"""Assimp-based analyzer.""" from __future__ import absolute_import import os import logging import subprocess import pyassimp from damn_at import ( mimetypes, MetaDataType, MetaDataValue, FileId, FileDescription, AssetDescription, AssetId ) from damn_at.pluginmanager import IAnalyzer from...
7,008
1,949
""" Remove Batches ============== """ from .selector import Selector class RemoveBatches(Selector): """ Prevents a :class:`.Selector` from selecting some batches. Examples -------- *Removing Batches From Selection* You want to use :class:`.Roulette` selection on all but the 5 :class:`....
2,423
661
# Generated by Django 2.2.1 on 2019-06-30 00:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('students', '0009_auto_20190629_0125'), ] operations = [ migrations.AddField( model_name='institutionalemail', name='...
446
158
""" Author: Miguel Alex Cantu Email: miguel.can2@gmail.com Date: 12/21/2019 Description: Loads Azure Utility Tool configuration file. The configuration file is a blend of what the Microsoft Authentication Library requires and some extra directives that the Auzre Utility Tool requires. It is a JSON file ...
920
255
# This file was auto generated; Do not modify, if you value your sanity! import ctypes import enum from ics.structures.can_settings import * from ics.structures.canfd_settings import * from ics.structures.s_text_api_settings import * class flags(ctypes.Structure): _pack_ = 2 _fields_ = [ ('disableUsb...
1,197
467
## https://leetcode.com/problems/substring-with-concatenation-of-all-words/submissions/ ## this method fails on test case 171 of 173 because it's too slow. ## i'm not sure I see a way to avoid checking every starting position ## in s, and I'm also not sure I see a way to avoid having a loop over ## the words too. ## ...
1,531
454
#!/usr/bin/env python3 ''' The MIT License (MIT) Copyright (c) 2014 Mark Haines Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without...
1,848
597
from random import randint from retrying import retry import apysc as ap from apysc._geom.path_control_x_interface import PathControlXInterface class TestPathControlXInterface: @retry(stop_max_attempt_number=15, wait_fixed=randint(10, 3000)) def test_control_x(self) -> None: interface: ...
2,373
801
import json from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, FileType from pathlib import Path def main(): parser = ArgumentParser(description='Collect markdown files, and write JSON.', formatter_class=ArgumentDefaultsHelpFormatter) project_path = Path(__file__)....
1,060
282
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # My name is William Clifford Mckee and this is my autobiography. Written in November 2014. # # Structure: # # <markdowncell> # Hello and goodNIĢ # testing one two there. # <markdowncell> # Hello. Testing one two three. # Screw you guys. I'm g...
1,569
487
# -*- coding: utf-8 -*- from __future__ import with_statement import base64 import time import simplejson as json from flask.ext.security.utils import capture_registrations, \ capture_reset_password_requests, capture_passwordless_login_requests from flask.ext.security.forms import LoginForm, ConfirmRegisterForm,...
26,125
8,335
from . import program from . import turtle_test from . import antoine_test from . import dance
94
28
# -*- coding: utf-8 -*- from copy import deepcopy from difflib import SequenceMatcher from IPython.core.display import Image from IPython.core.display import JSON from json import JSONDecodeError from lunr.builder import Builder from lunr.stemmer import stemmer from lunr.stop_word_filter import stop_word_filter from lu...
8,283
2,635
# Function Credits: https://github.com/lekum/pyduino/blob/master/pyduino/pyduino.py (lekum (as of 2014)) # Written By: ItzTheDodo from Pyduino.Boards.Uno import UnoInfo from Pyduino.Boards.Mega import MegaInfo from Pyduino.Boards.Diecimila import DiecimilaInfo from Pyduino.Boards.Due import DueInfo from Pyduino...
5,022
1,734
from allauth.socialaccount.helpers import complete_social_login from allauth.socialaccount.models import SocialApp, SocialToken, SocialLogin, SocialAccount from allauth.socialaccount.providers.facebook.views import fb_complete_login from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from djang...
2,218
599
class Solution: def isIdealPermutation(self, A: List[int]) -> bool: n = len(A) g = local = 0 for i in range(1, n): if A[i] < A[i-1]: local += 1 if A[i] < i: diff = i - A[i] ...
390
120
# encoding: utf-8 import operator import six from django.db.models import BooleanField, Field, Q from ..utils.internal import MISSING_OBJECT, ModelAttributeGetter, QueryPath from .base import QueryableProperty from .mixins import AnnotationGetterMixin, AnnotationMixin, boolean_filter, LookupFilterMixin class Boole...
13,076
3,157
""" training a super-network and periodically evaluating its performance on bench architectures a work in this direction exists: https://arxiv.org/abs/2001.01431 """ from uninas.main import Main # default configurations, for the search process and the network design # config_files = "{path_conf_bench_tasks}/s1_fairna...
2,558
943
import numpy as np import sqlalchemy as sa from sqlalchemy.dialects import postgresql as psql from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.schema import UniqueConstraint from astropy import units as u from .core import Base from .constants import APER_KEY, A...
9,650
3,379
import tensorflow as tf from models.Libraries.BidirectionalGraphEncoder import BidirectionalGraphEncoder from tensorflow.python.ops import array_ops if __name__ == "__main__": # units=2, input_dim=2, edge_types=10, recurrent_size=4 bi_graph_encoder = BidirectionalGraphEncoder(2, 2, 10, 4) # inputs: batch_...
5,521
3,232
from django.apps import AppConfig class AnimazyaConfig(AppConfig): name = 'animazya'
96
35
xval = 0 xvalue1 = 1 xvalue2 = 2 print(xvalue1 + xvalue2)
59
33
from kivy.animation import Animation from kivy.app import App from kivy.core.window import Window from kivy.graphics import Color from kivy.graphics import Ellipse from kivy.graphics import Line from kivy.uix.widget import Widget class ProjCenter(Widget): def __init__(self, **kwargs): super(ProjCenter, se...
3,000
969
""" Sookie, is a waiter, waits for a socket to be listening then it moves on Usage: sookie <socket> [--timeout=<to>] [--retry=<rt>] [--logsocket=<ls>] [--logfacility=<lf>] [--loglevel=<ll>] sookie -h | --help sookie --version Options: -h --help Show this screen --version ...
3,960
1,243
import pytest from pytest import raises from vyper import compiler from vyper.exceptions import VariableDeclarationException, TypeMismatchException fail_list = [ """ @public def test(): a = 1 """, """ @public def test(): a = 33.33 """, """ @public def test(): a = "test string" """...
912
326
#!/usr/bin/env python import unittest from mongoengine import Document, Q, StringField, connect from mongoengine_dsl import Query from mongoengine_dsl.errors import InvalidSyntaxError, TransformHookError from tests.utils import ts2dt class DSLTest(unittest.TestCase): def test_whitespace(self): self.asser...
7,568
2,725
import subprocess from collections import UserDict from functools import lru_cache def _parse_handle_section(lines): """ Parse a section of dmidecode output * 1st line contains address, type and size * 2nd line is title * line started with one tab is one option and its value * line started with...
2,891
845
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: from .base import MIDDLEWARE_CLASSES except ImportError as e: raise e # MIDDLEWARE_CLASSES += ( # 'django.middleware.cache.CacheMiddleware', # 'django.middleware.cache.UpdateCacheMiddleware', # 'django.middleware.cache.FetchFrom...
1,580
640
from typing import List, Dict import json import numpy as np from pandas import DataFrame import logging from argparse import ArgumentParser, ArgumentError from sklearn.metrics import classification_report from xpotato.graph_extractor.extract import FeatureEvaluator from xpotato.dataset.explainable_dataset import Expla...
5,144
1,488
from .episodic import EpisodicMemory, EpisodicBuffer
53
18
import numpy as np from joblib import Parallel, delayed from sklearn.ensemble import ExtraTreesRegressor from mushroom.algorithms.value import FQI from mushroom.core import Core from mushroom.environments import * from mushroom.policy import EpsGreedy from mushroom.utils.dataset import compute_J from mushroom.utils.pa...
1,876
641
import os from datetime import datetime from flask_sqlalchemy import SQLAlchemy # heroku postgresql setting app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', None) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) class usermessage(db.Model): ''' user message and reply d...
1,854
592
import torch import torch.nn as nn class voxel_match_loss(nn.Module): def __init__(self): super().__init__() self.criterion=nn.MSELoss() def forward(self,output,label): positive_mask=torch.zeros(label.shape).cuda() positive_mask=torch.where(label>0.2,torch.ones_like(positive_mas...
728
247
# Generated by Django 3.2.7 on 2021-09-19 03:41 from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] operations =...
1,134
333
# Copyright 2019 The Johns Hopkins University Applied Physics Laboratory # # 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 ...
8,305
2,329
#!/usr/bin/env python3 """This is a module for X-Road Central Server API. This module allows: * adding new member to the X-Road Central Server. * adding new subsystem to the X-Road Central Server. """ import json import logging import re import psycopg2 from flask import request, jsonify from flask_restful i...
17,579
5,239
# Generated by Django 2.2.3 on 2019-12-27 18:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dotacni_matice', '0001_initial'), ] operations = [ migrations.AlterField( model_name='dotacnititul', name='history',...
397
136
from collections import OrderedDict from dataclasses import ( fields, ) from prettyprinter.prettyprinter import pretty_call, register_pretty def is_instance_of_dataclass(value): try: fields(value) except TypeError: return False else: return True def pretty_dataclass_instance...
898
268
""" GEFS Chart Bot Polls https://www.tropicaltidbits.com/storminfo/11L_gefs_latest.png, but it can really be used to monitor/notify about changes to any file on the web. (c) Charlton Trezevant 2017 MIT License Enjoy! """ import time, sys sys.dont_write_bytecode = True sys.path.insert(0, 'lib'...
1,055
421
'''test_periodbase.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Feb 2018 License: MIT - see the LICENSE file for details. This tests the following: - downloads a light curve from the github repository notebooks/nb-data dir - reads the light curve using astrobase.hatlc - runs the GLS, WIN, PDM, AoV, BLS, AoVMH, a...
6,442
2,432
from _pytest.python_api import raises from baby_steps import given, then, when from district42 import schema from revolt import substitute from revolt.errors import SubstitutionError from district42_exp_types.sdict import schema_sdict def test_sdict_substitution(): with given: sch = schema_sdict wit...
2,877
810
""" Pascal's Triangle 1 11 121 1331 14641 Question: Find the value in given row and column First solution: brute force Second solution: Dynamic programming alternative def pascal(r, c): print(f"row: {r}, col: {c}") if r == 0 or r == 1 or c == 0: return 1 return pascal(r-1, c-1) + pascal(r-1, c...
1,735
642
from __future__ import unicode_literals import codecs from django.conf import settings from rest_framework.compat import six from rest_framework.parsers import BaseParser, ParseError from rest_framework import renderers from rest_framework.settings import api_settings import ujson class UJSONParser(BaseParser): ...
1,117
305
from math import ceil walls_hight = int(input()) walls_witdh = int(input()) percentage_walls_tottal_area_not_painted = int(input()) total_walls_area = walls_hight * walls_witdh * 4 quadratic_meters_left = total_walls_area - ceil(total_walls_area * percentage_walls_tottal_area_not_painted / 100) while True: paint...
778
283
class Order(): def __init__(self, exchCode, sym_, _sym, orderType, price, side, qty, stopPrice=''): self.odid = None self.status = None self.tempOdid = None self.sym_ = sym_ self._sym = _sym self.symbol = sym_ + _sym self.exchCode = exchCode.upper() se...
1,078
373
import datetime import re import os import requests import json import uuid import random import calendar import time import libs.SerializableDict as SerializableDict import libs.StorageObjects as StorageObjects import libs.Models as Models import libs.Loggiz as Loggiz from pytz import timezone import pytz import teleg...
19,069
5,755
# Alias to SDK PyTorch utils from aim.sdk.adapters.pytorch import track_params_dists, track_gradients_dists # noqa
115
43
# coding: utf-8 # Your code here! import csv def encode_cardd_by_url(url: str) -> dict: """ 入力:デッキURL 出力:{ card_id, num } 処理: URLから、カードidごとの枚数の辞書を作成する """ site_url, card_url = url.split("c=") card_url, key_card_url = card_url.split("&") arr_card_id = card_url.split(".") ...
890
386
from .regular_grammar import RegularGrammar from .finite_automaton import FiniteAutomaton, State, Symbol, Sentence from .regular_expression import RegularExpression, StitchedBinaryTree, Lambda
193
52
from django.apps import AppConfig class PluginsConfig(AppConfig): name = 'recipes'
89
28
""" A repository for constants and symbols used in the mass weighing program Modify default folder paths as necessary """ import os MU_STR = 'µ' # ALT+0181 or 'µ'. use 'u' if running into issues SIGMA_STR = 'σ' # \u03C3 for sigma sign DELTA_STR = 'Δ' # \u0394 for capi...
1,337
560
import PyCmdMessenger from VestDeviceBase import VestDevice class UsbVestDevice(VestDevice): """ Basic interface for sending commands to the vest using a serial port connection. """ commands = [["PinSet","gg"], ["PinMute","g"], ["GloveSet","gg*"], ["...
3,032
874
from django.core.exceptions import ValidationError import pytest from api.models import Product @pytest.mark.django_db @pytest.mark.parametrize( ('name', 'price'), ( ('aa', 1000), ('a' * 21, 1000), ('house', 1000000001), ('minus', -1), ('A 01 %', 100), ), ) def tes...
923
353
import mock import pytest import copy import six from lxml import html from ...helpers import LoggedInApplicationTest from dmapiclient import HTTPError @mock.patch('app.main.views.users._user_info') @mock.patch('app.main.views.users.data_api_client') class TestUsersView(LoggedInApplicationTest): def test_shoul...
12,099
3,799
import numpy as np import sys, os from scipy.optimize import minimize import json import matplotlib.pyplot as plt # sys.path.append('./utils') import tools # bs, ncf, stepf = 400, 512, 40 path = '../data/z00/' ftype = 'L%04d_N%04d_S%04d_%02dstep/' ftypefpm = 'L%04d_N%04d_S%04d_%02dstep_fpm/' mm = np.load('../data/Il...
3,460
1,585
from django import forms from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from .models import UserProfile # Create your forms here class LoginForm(AuthenticationForm): def __init__(self, request, *args, **kwargs): super().__init__(self, request, *args, **kwargs) self.fiel...
1,729
478
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _AlibabaCloud class _Analytics(_AlibabaCloud): _type = "analytics" _icon_dir = "resources/alibabacloud/analytics" class AnalyticDb(_Analytics): _icon = "analytic-db.png" class ClickHouse(_Analytics): _icon = "click...
556
205
""" Purpose of this file is to give examples of structured arrays This script is partially dirived from the LinkedIn learning course https://www.linkedin.com/learning/numpy-data-science-essential-training/create-arrays-from-python-structures """ import numpy as np person_data_def = [('name', 'S6'), ('height', 'f8'),...
1,487
541
''' File: ebook_fix.py Created: 2021-03-06 15:46:09 Modified: 2021-03-06 15:46:14 Author: mcxiaoke (github@mcxiaoke.com) License: Apache License 2.0 ''' import sys import os from pprint import pprint from types import new_class from mobi import Mobi from ebooklib import epub import argparse from multiprocessing.dummy i...
5,716
1,850
from __future__ import absolute_import, division, print_function import attr @attr.s class Stack(object): __items = attr.ib(type=list, factory=list) def push(self, item): self.__items.append(item) def pop(self): return self.__items.pop() def peek(self): return self.__items[...
387
128
print('hi') raise Exception('fibble-fah')
41
15
""" Utility functions for working with DataFrame """ import pandas TEST_DF = pandas.DataFrame([1,2,3])
105
35
#!/usr/bin/env python3 # #Peter J. Mangelsdorf # # Kurt Schmidt # 7/06 # # # parsePhoneNrs.py - an example of 'grouping' - extracting parts of a match # # Python 3.5.2 # on Linux 4.4.0-36-generic x86_64 # # Demonstrates: regexp, re, search, groups # # Usage: By default, reads telNrs.txt . You may supply a different ...
2,160
892
import RPi.GPIO as gpio from pusher import Pusher import time pusher = Pusher(app_id=u'394325', key=u'cc900daae41222ea463e', secret=u'02ae96830fe03a094573', cluster=u'eu') gpio.setmode(gpio.BCM) gpio.setup(2, gpio.OUT) # TODO: Map each gpio pin to a room eg 2: HNG Main while True: gpio.output(2, gpio.OUT) passcode ...
567
278
import functools from flask import Blueprint from flask import render_template from flask import g from flask import redirect from flask import url_for from flask import flash from mflac.vuln_app.db import get_db bp = Blueprint("admin", __name__, url_prefix="/admin") def admin_required(view): @functools.wraps(...
1,036
319
import os import pandas as pd import torch from torch import nn import common.utils as util import scipy.misc as spmi def save_img(img_np, file_name, out_dir='./'): if not os.path.exists(out_dir): os.makedirs(out_dir) image = img_np.copy().transpose(1, 2, 0) # for gray image if img_np.shape[...
3,708
1,436
import numpy as np import matplotlib.pyplot as plt import networkx as nx from nxviz import CircosPlot from neurolib.utils import atlases # https://doi.org/10.1016/j.neuroimage.2015.07.075 Table 2 # number corresponds to AAL2 labels indices CORTICAL_REGIONS = { 'central_region': [1, 2, 61, 62, 13, 14], 'fron...
10,218
3,903
'''6. Escreva um programa que, dados dois números inteiros, mostre na tela o maior deles, assim como a diferença existente entre ambos.'''
140
44
''' This is the config file for the code in src/. Essentially it holds things like file and variable names. ''' # The folder locations of the below files are specified by the # cookie cutter data science format and are hardcoded into the code. # I'm not entirely sure that that was the best way to go about it, # but t...
1,694
608
#!/Usr/bin/env python """ You are given an array of numbers Ai which contains positive as well as negative numbers . The cost of the array can be defined as C(X) C(x) = |A1 + T1| + |A2 + T2| + ... + |An + Tn|, where T is the transfer array which contains N zeros initially. You need to minimize this cost. You ca...
1,486
528
def add_native_methods(clazz): def initProto____(): raise NotImplementedError() def socketCreate__boolean__(a0, a1): raise NotImplementedError() def socketConnect__java_net_InetAddress__int__int__(a0, a1, a2, a3): raise NotImplementedError() def socketBind__java_net_InetAddres...
2,002
652
import sys import time import digitalocean import subprocess def test_ssh(drop): droplet_ip_address = drop.ip_address result = subprocess.call(f"ssh -o StrictHostKeyChecking=no root@{droplet_ip_address} ls", shell=True) if result == 0: return True return False TOKEN_FILE = "/srv/secrets-newsbl...
973
353