text
string
size
int64
token_count
int64
import xml.etree.ElementTree as ET from cntr.service.base import TextMsg, ImageMsg, LocationMsg, VoiceMsg class ReceiveHandler(object): def __init__(self): self._type_class_map = { 'text' : TextMsg, 'image' : ImageMsg, 'location': LocationMsg, 'voice' : ...
669
207
class Allergies(object): ALLERGY_SCORES = { 'eggs': 1, 'peanuts': 2, 'shellfish': 4, 'strawberries': 8, 'tomatoes': 16, 'chocolate': 32, 'pollen': 64, 'cats': 128 } def __init__(self, score): if score is None or not isinstance(score, i...
1,081
347
import collections from numpy.core.defchararray import lower import streamlit as st import numpy as np import pandas as pd from pages import utils def app(): st.title("Data Storyteller Application") st.markdown("## Data Upload") # Upload the dataset and save as csv st.markdown("### Upload ...
2,309
677
# Generated by Django 2.2.13 on 2020-11-26 03:26 from django.db import migrations, models import djongo.models.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UsoRed', fields=[ ...
832
256
import logging from collections import defaultdict from typing import Iterable, Generator, Optional from pynamodb.exceptions import DoesNotExist from common.enums.entity import Entity from common.enums.jobtype import detect_job_type from config.application import PERMANENTLY_FAILING_JOB_THRESHOLD from config.jobs im...
5,438
1,690
#!/usr/bin/python import datetime import httplib import urllib import redis import json from datetime import timedelta #now = datetime.datetime.now(); #today = now.strftime('%Y-%m-%d') #print today rdb = redis.Redis('localhost') def rv(value): out = "" for num in value.strip().split(","): out+=num return out de...
1,782
770
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'InterfaceGUI.ui' # # Created: Mon Mar 11 15:56:47 2013 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtWidgets try: from PyQt5 import QtCore, QtGui excep...
5,453
1,954
from sports.nba.nba_team import NBA_Team class WashingtonWizards(NBA_Team): """ NBA's Washington Wizards Static Information """ full_name = "Washington Wizards" name = "Wizards" team_id = 1610612764 def __init__(self): """ """ super().__init__()
302
111
# -*- coding:utf-8 -*- import paddle.fluid as fluid def cnn_net(data, dict_dim, emb_dim=128, hid_dim=128, hid_dim2=96, class_dim=2, win_size=3): """ Conv net """ # embedding layer emb = fluid.layers.embedding( input=da...
1,305
505
#!/usr/bin/env python # -*- coding: utf-8 -*- import runpy import os import pytest import glob THIS_FILES_DIR_PATH = os.path.realpath(os.path.dirname(__file__)) def get_paths_of_scripts(): exclude_sub_strings = ["do_not_execute"] plot_script_paths = glob.glob( os.path.join( os.path.dirna...
944
330
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import sys # groups: # anatomist: projects needed for anatomist (aims, soma-io and dependencies) # opensource # brainvisa: public brainvisa distro # bvdev: same as brainvisa but excludes restricted access projects # (such as brainrat-priv...
31,316
9,993
# -*- coding: utf-8 -*- """ Inspired by: * https://gist.github.com/shirriff/c9fb5d98e6da79d9a772#file-merkle-py * https://github.com/richardkiss/pycoin """ from __future__ import absolute_import, division, unicode_literals from builtins import range import binascii import hashlib def merkleroot(hashes): ...
977
379
from model.contact import Contact from model.group import Group import random def test_add_contact_in_group(app, db): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname="ADDNewFirstName1", lastname="ADDNewLastName1")) if len(db.get_group_list()) == 0: app.group.create(Gro...
1,273
456
import dill as pickle import cherrypy homeLocation = '/home/alion/Projekti/cherrypyTest' rootConfig = {'/': {'log.screen': False, 'log.access_file': homeLocation+'/logs/access_file.log', 'log.error_file': homeLocation+'/logs/error_file.log', 'tools.sessions.on': True, ...
1,945
625
from django.contrib import admin from simple_history.admin import SimpleHistoryAdmin from .models import MainMetadata # Register your models here. admin.site.register(MainMetadata, SimpleHistoryAdmin)
202
48
from typing import Iterable as Iterable, List, Dict, Callable, Iterator, Set, Optional from ...models.core.Unit import Unit from ...models.core.Class import Class from ...models.core.Weapon import Weapon from ...models.core.Item import Item from ...models.core.Skill import Skill from ...models.play.ActiveArena import A...
17,839
5,101
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def libevent(): http_archive( name = "libevent", build_fi...
967
431
""" The CPTPState class and supporting functionality. """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Govern...
15,190
4,910
# -*- coding: utf-8 -*- """ Created on Fri Apr 30 11:58:20 2021 @author: Martin Johnson """ import sys sys.path.append("...") import macheval as me class IMSettingsHandler(me.SettingsHandler): def getSettings(x): return NotImplementedError #TODO Implement settings functionality
298
107
import datetime as dt import json import os import pandas as pd from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func from iotfunctions.preprocessor import BaseTransformer from iotfunctions.bif import IoTExpression from iotfunctions.metadata import EntityType, make_sample_entity from iotfunctio...
1,596
489
import pytest import os import numpy as np import minst.taxonomy as tax def __test(value, expected): assert value == expected def __test_df_has_data(df): assert not df.empty def __test_pd_output(pd_output, dataset): """Make sure all the files in the tree exist""" # Check for valid columns req...
1,022
309
#!/usr/bin/env python3 from typing import Dict import rich.markup from pwncat.db import Fact from pwncat.platform.linux import Linux from pwncat.modules.enumerate import Schedule, EnumerateModule class SELinuxState(Fact): def __init__(self, source, state, status): super().__init__(source=source, types=[...
2,161
631
# Copyright 2017 Red Hat, Inc. <http://www.redhat.com> # # 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 b...
2,975
875
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 21 08:20:55 2021 @author: silasjimmy """ def count_words(s, n): s = s.split(' ') counted_words = [(w, s.count((w))) for w in set(s)] counted_words.sort(key = lambda x: (-x[1], x[0])) top_n = counted_words[:n] return top_n def t...
515
214
# jumlah segitiga n = 123 # panjang alas sebuah segitiga alas = 30 # tinggi sebuah segitiga tinggi = 18 # hitung luas sebuah segitiga luas = alas * tinggi * 1/2 # hitung luas total luastotal = n * luas print('luas total : ', luastotal,'satuan luas')
250
115
import queue import textwrap import threading import time import urllib.parse import pychromecast def create_notify_url(text: str, lang: str, ttsspeed: float): payload = { "ie": "UTF-8", "q": text, "tl": lang, "total": 1, "idx": 0, "textlen": ...
4,210
1,292
from . import BasicType class UserProfilePhotos(BasicType): fields = { 'total_count': int, } def __init__(self, obj=None): super(UserProfilePhotos, self).__init__(obj) from . import photosize UserProfilePhotos.fields.update({ 'photos': { 'class': photosize.PhotoSize, ...
353
116
from taurex.log import Logger class LinesReader: def __init__(self, lines): self._lines = lines self._count = 0 def skip(self, num=1): self._count += num def read_int(self, skip=1): val = int(self._lines[self._count]) self.skip(skip) return val ...
8,171
2,627
import logging logger = logging.getLogger(__name__) class ParserBase: selector_key = None def __init__(self, string_data, url=None, extractor_manifest=None): self.string_data = string_data self.url = url self.extractor_manifest = extractor_manifest def parse_data(self, string_...
2,374
674
import glob import itertools from functools import partial from typing import Tuple, Optional from kolejka.judge.tasks.base import TaskBase class ListFiles(TaskBase): def __init__(self, *args, variable_name): self.files = list(args) self.variable_name = variable_name def execute(self, enviro...
562
162
import os import json from flask_sqlalchemy import SQLAlchemy from flask import Flask, request, jsonify from flask.views import MethodView from flask.ext.cors import CORS from database import ElasticStorage, RedisClient from article import Article as ESArticle app = Flask(__name__) CORS(app) #sql_config = json.loads(...
5,775
2,071
import os from qaviton.utils import filer from qaviton.utils import path from qaviton.utils.operating_system import s from qaviton.version import __version__ cwd = os.getcwd() examples = path.of(__file__)('examples') def initial_msg(f): def dec(*args, **kwargs): print(""" QAVITON VERSION {} ...
9,738
2,775
from migen import * import math from litex.soc.interconnect.csr import * from litex.soc.interconnect import stream class DemosaicBase(Module): def first_pix(self): return [If(self.first_pixel, NextValue(self.rgb_first,1), NextValue(self.first_pixel,0), ).Else( ...
1,178
380
""" Tests for the reference loader for Buyback Authorizations. """ from functools import partial from unittest import TestCase import blaze as bz from blaze.compute.core import swap_resources_into_scope from contextlib2 import ExitStack import pandas as pd from six import iteritems from zipline.pipeline.common import...
10,341
3,647
import pymongo from bson.objectid import ObjectId # mongo 增加 def main(): client = pymongo.MongoClient(host='47.114.171.118', port=27017) db = client.test collection = db.students # 插入一条数据 student = { 'id': '20170101', 'name': 'Kevin', 'age': 20, 'gender': 'male' ...
1,534
706
# # Copyright (C) 2014 Red Hat, 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 or agreed to in wr...
4,608
1,361
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime as dt import json from pathlib import Path import torch import torch.nn as nn from torch import optim from libs.data_loader import create_mnist_data_loader from libs.model import CNN from libs.trainer import train, test def main(config): # 使用リソースの設...
2,130
889
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");...
2,029
632
import rospy import numpy as np import cv2 class ScalarStable(object): """Represents a stabilized scalar""" def __init__(self, x=.0, vx=.0, p_cov=.03, m_cov=.01, time=None): """ScalarStabilized constructor""" self.x = x ...
2,917
937
"""dRest core API connection library.""" import re from . import interface, resource, request, serialization, meta, exc from . import response class API(meta.MetaMixin): """ The API class acts as a high level 'wrapper' around multiple lower level handlers. Most of the meta arguments are optionally passed...
14,399
3,823
from ExIt.Apprentice import BaseApprentice from Games.GameLogic import BaseGame class BaseExpert: """ Class for the tree search algorithm used for policy improvement """ def __init__(self): self.__name__ = type(self).__name__ def search(self, state: BaseGame, predictor: BaseApprentice, search_t...
519
148
# 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 writing, software # distributed under the Li...
1,235
318
""" Copyright 2020 Inmanta 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 ...
1,937
628
import unittest from pyfsm.elements import * class StateUnitSimpleFsmTests(unittest.TestCase): def setUp(self): self.fsm = StateUnit() self.state1 = StateUnit() self.state2 = StateUnit() self.link1 = LinkElement() self.fsm.starters = [self.state1] self.state1.paren...
7,798
2,625
#!/usr/bin/env python import os import sys import sqlite3 import pandas as pd import numpy as np from scraper import create_data_folder, read_config from collections import OrderedDict def main(): """ Mainly for debugging purposes. """ config_file = read_config() # Pick a file try: c...
8,117
2,485
from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TerminateOnNaN, CSVLogger from keras import backend as K from keras.models import load_model from math import ceil import numpy as np from matplotlib import pyplot as plt from models.keras_ssd7 import build...
7,799
2,395
"""Ansible playbooks init"""
29
10
#Artificial Neural Network #includes import configparser import math import matplotlib.pyplot as plt import numpy as np import random from decimal import * #global variables weights = []; topology = []; data_training = []; data_test = []; learning_rate = 0; weight_min = 0; weight_max = 0; error_terms = []; outputs =...
12,339
4,024
# http://codingbat.com/prob/p193507 def string_times(str, n): result = "" for i in range(0, n): result += str return result
143
60
from app.service.base_service import BaseService class PluginService(BaseService): def __init__(self, plugins): self.plugins = plugins self.log = self.add_service('plugin_svc', self) def get_plugins(self): return self.plugins
262
77
import nengo import pytest from nengo_spinnaker.builder import Model from nengo_spinnaker.builder.ports import OutputPort, InputPort from nengo_spinnaker.node_io import ethernet as ethernet_io from nengo_spinnaker.operators import SDPReceiver, SDPTransmitter @pytest.mark.parametrize("transmission_period", [0.001, 0....
3,709
1,266
#!/usr/bin/env python # encoding: utf-8 # Copyright (C) Alibaba Cloud Computing # All rights reserved. import sys import requests try: import json except ImportError: import simplejson as json try : import logservice_lz4 except ImportError: pass from datetime import datetime from...
59,138
17,444
def alternate_case(s): # Like a Giga Chad return "".join([char.lower() if char.isupper() else char.upper() for char in s]) # Like a Beta Male # return s.swapcase() # EXAMPLE AND TESTING # input = ["Hello World", "cODEwARS"] for item in input: print("\nInput: {0}\nAlternate Case: {1}".format(item,...
489
177
#!/usr/bin/env python import os import todoist import pickle from os import path from argparse import ArgumentParser from todoist_python_additions.lib.state import Todoist def build_parser(): parser = ArgumentParser() parser.add_argument('-p', '--project', required=True, help='Project to get descendant tasks...
729
220
from django import http from django.shortcuts import render from django.shortcuts import render_to_response from . import settings from .scripts import logic import os import urllib import json def recipe_html(request): print(os.path.join(settings.BASE_DIR, "recipe_server/static")) return render_to_response("r...
636
196
"""A json-like master list of workflows and steps.""" # NOTE: Create a json-like dictionary in the form of: # WF_STEPS = { # env1: { # 1st condition defined in next_steps: { # 2nd condition defined in next_steps: (Workflow Name, Step Name), # }, # }, # } WF_STEPS = {}
296
102
import sys fn = sys.argv[1] fp = open(fn) fo = open(fn+".flv","wb") data = fp.read() offset = int(sys.argv[2]) if len(sys.argv)==3: fo.write(data[offset:]) else: l = int(sys.argsv[3]) fo.write(data[offset:offset+l]) fo.close() fp.close()
250
115
#!/usr/bin/python3 list = ["Armitage", "Backdoor Factory", "BeEF","cisco-auditing-tool", "cisco-global-exploiter","cisco-ocs","cisco-torch","Commix","crackle", "exploitdb","jboss-autopwn","Linux Exploit Suggester","Maltego Teeth", "Metasploit Framework","MSFPC","RouterSploit","SET","ShellNoob","sqlmap", "THC-IPV6","Ye...
329
131
from rest_framework import serializers from api.model.foodComment import FoodComment from api.model.food import Food from django.contrib.auth.models import User from api.serializer.user import UserSerializer class FoodCommentSerializer(serializers.ModelSerializer): comment = serializers.CharField(max_length=255...
1,152
330
from pycccl.base import ExchangeBase class Binance(ExchangeBase): _public_endpoint = "https://api.binance.com/api/v1" _private_endpoint = _public_endpoint def get_ticker(self, ticker, against='USDT'): pair = "{}{}".format(ticker, against) endpoint = "{}/ticker/24hr".format(self._public_en...
616
193
'''Contains helper functions that can be used by any feature.''' from nltk_utils import tokenize def get_search_query( spoken_text, patterns, search_terms, false_search_term_indicators=['like', 'love', 'want', 'ready'] ): ''' General function that extracts a search query from spoken text g...
3,036
821
from common import auth_check def test_machine_fields(cclient): fields = { 'useInternalIpAddress': 'cr', 'nodeTaints': 'r', 'nodeLabels': 'r', 'nodeAnnotations': 'r', 'namespaceId': 'cr', 'conditions': 'r', 'allocatable': 'r', 'capacity': 'r', ...
1,042
356
# Copyright (c) 2019 Ericsson # # 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...
1,764
518
from Dialogflow_Api import rispondimi from collegamentoSito import inserisci_utente from Nutrition import get_food, traduzione import re tipo_cibo = ["frutta", "carne", "verdure", "ortaggi", "primi_piatti", "legumi"] """ controllo_intent(query_result, utente)--> text_respose prende il risultato della query e lo confr...
6,743
2,186
def get_max_coins_helper(matrix, crow, ccol, rows, cols): cval = matrix[crow][ccol] if crow == rows - 1 and ccol == cols - 1: return cval down, right = cval, cval if crow < rows - 1: down += get_max_coins_helper( matrix, crow + 1, ccol, rows, cols) if ccol < cols - 1: ...
780
334
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applicabl...
1,745
607
"""Defines procedures for training, and evaluation automatic camfi annotation models, and for using them for making automatic annotations (inference). Depends on camfi.util, camfi.datamodel.autoannotation, camfi.datamodel.geometry, camfi.datamode.via, as well as ._torchutils and ._models.""" from datetime import datet...
26,526
7,520
""" Wrapper for running amplicon_analysis_inputs report for LAAgc (with an extra input file). """ import logging import sys from pbcommand.models import FileTypes from pbcommand.cli import pbparser_runner from pbcommand.utils import setup_log from pbreports.report.amplicon_analysis_input import _get_parser, make_rep...
1,644
555
#!/usr/bin/env python # coding:utf-8 from toughlib import dispatch """触发邮件,短信发送公共方法""" def trigger_notify(obj, user_info, **kwargs): if int(obj.get_param_value("webhook_notify_enable", 0)) > 0 and kwargs.get('webhook_notify'): dispatch.pub(kwargs['webhook_notify'], user_info, async=False) if int(o...
1,014
374
# Copyright (c) 2013 Mirantis 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 or agreed to in writ...
2,017
626
""" Copyright 2019 EUROCONTROL ========================================== Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions an...
2,978
916
# Copyright 2013-2014, Simon Kennedy, sffjunkie+code@gmail.com # pylint: disable=unused-argument """Provides access to a registry of validation functions. Functions are returned via the :func:`get_validator` function and can be refined by passing a specification which alters what passes the validation. All validator...
22,063
6,129
import os import shutil import build_utils def get_supported_targets(platform): if platform == 'win32': return ['win32', 'win10'] elif platform == 'darwin': return ['macos', 'ios', 'android'] elif platform == 'linux': return ['android', 'linux'] else: return [] def ge...
11,396
4,044
import healpy as hp import numpy as np from schnell import MapCalculator, GroundDetector, LISADetector # Detectors det1 = GroundDetector('Hanford', 46.4, -119.4, 90-171.8, 'plots/data/aLIGO_design.txt') det2 = GroundDetector('Livingstone', 30.7, -90.8, 90-243.0, 'plots...
1,871
874
# The MIT License (MIT) # Copyright © 2021 Opentensor.ai # 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 limitation # the rights to use, copy, modify,...
7,281
2,110
''' Split the training data into subsets for cross validation, sample from the testing data, etc. ''' from feather import read_dataframe as read_feather import numpy as np import pdb from zpylib import data_path as dp from zpylib import datatools from zpylib import N_TEST from zpylib import N_TRAIN # Config NGROUPS=...
1,924
673
from predictionserver.clientmixins.attributereader import ( AttributeReader, AttributeType, AttributeGranularity ) from predictionserver.set_config import MICRO_TEST_CONFIG from predictionserver.servermixins.attributeserver import AttributeServer BABLOH_CATTLE = MICRO_TEST_CONFIG['BABLOH_CATTLE'] PUBLIC_PROFILE =...
1,732
582
import unittest from datetime import datetime, timezone from pandas import DatetimeTZDtype from parameterized import parameterized import pandas as pd from aiokraken.utils.timeindexeddataframe import TimeindexedDataframe """ Test module. This is intended for extensive testing, using parameterized, hypothesis or simi...
20,187
6,085
# _*_ coding: utf-8 _*_ """ Created by Allen7D on 2018/6/16. """ import os.path as op from flask_admin import Admin, BaseView, expose from flask import render_template, redirect, url_for from flask_admin.contrib.sqla import ModelView from flask_admin.contrib.fileadmin import FileAdmin from flask_admin import form fro...
2,041
779
# Classes implementing the different commands that can be sent to MK # The implemented classes do not cover the complete functional set of MK # but are what is required to implement a basic UI. import enum import machinetalk.protobuf.message_pb2 as MESSAGE import machinetalk.protobuf.status_pb2 as STATUS import machi...
9,334
2,887
class NEC: def __init__( self ): self.prompt = '(.*)' self.timeout = 60 def show(self, *options, **def_args ): '''Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-s...
24,199
6,795
import cv2 threshold = 0.5 # Threshold to detect objects cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) classNames = [] classFile = "coco.names" with open(classFile, "rt") as f: classNames = f.read().rstrip("\n").split("\n") configPath = "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt" weightsPath = "f...
1,094
490
#!/usr/bin/env python # coding: utf-8 # In[1]: from bs4 import BeautifulSoup import re import json import numpy as np import sys sys.setrecursionlimit(10000) # Write a function that parses HTML pages into BeautifulSoup objects # In[2]: def soupify(html): soup = BeautifulSoup(html, 'lxml') return soup ...
4,302
1,519
from bson.objectid import ObjectId from girder.models.model_base import AccessControlledModel from girder.constants import AccessType from molecules.models.molecule import Molecule as MoleculeModel from molecules.utilities.get_cjson_energy import get_cjson_energy from molecules.utilities.pagination import parse_pagin...
2,651
787
## LIBRARY OF MATERIALS ####################################################### def matp(mat, Tbulk, NL): import numpy as np E, v, cpg, kg, rohg, sigmaHlim, sigmaFlim = [np.zeros(2) for _ in range(7)] for i in range(len(E)): if mat[i] == 'POM': E[i] = 3.2e9 # 2900 MPa (min) ...
2,185
1,149
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = 'CwT' # document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"> # <input type="hidden" name="q" value="a"></form>'; # document.getElementById("dynForm").submit(); POST_JS = '<form id=\\"dynamicform\\" action=\\"%s\\" met...
802
288
# coding: utf-8 """ Engine api Engine APIs # noqa: E501 The version of the OpenAPI document: 1.0.4 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six class EngineTask(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref:...
13,297
4,108
""" Analyses skewness for continuous features Options: A. Log B. Yeo-Johnson C. QuantileTransformer """ import json import pandas as pd import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import power_transform, quantile_transform from pathlib import Path p = Path(__f...
1,876
635
from __future__ import absolute_import, division, print_function from trakt.mapper.core.base import Mapper import logging log = logging.getLogger(__name__) class SyncMapper(Mapper): @classmethod def process(cls, client, store, items, media=None, flat=False, **kwargs): if flat: # Return ...
7,486
2,184
import pygame pygame.init() FPS = 60 WIDTH, HEIGHT = 800, 700 ROWS, COLS = 7, 8 SQUARE_SIZE = HEIGHT//ROWS # GRAPHICAL USER INTERFACE ICON_PATH = './src/murus_gallicus/assets/noun_checkers_1684698.png' WINDOW = pygame.display.set_mode((WIDTH, HEIGHT)) PADDING = 20 OUTLINE = 2 # RGB COLORS RED = (255, 0, 0) WHITE = ...
669
418
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
5,855
1,866
# -*- coding: utf-8 -*- """ Useful functions for the Next Generation Heat Pump library @author: Sylvain Quoilin """ import sys,os class NoStdStreams(object): ''' This class hides the std output of the executed function usage: with NoStdStreams() pass ''' def __init__(se...
939
304
# B_R_R # M_S_A_W """ Coding Problem on Regular expressions: In order to work with regular expressions or we can say regex too, we have to import its module which is called re Specifically we use search method of regex library search method returns match object if it finds any """ import re price='Price: $1...
829
270
import deepchem as dc import numpy as np import os def test_numpy_dataset_get_shape(): """Test that get_shape works for numpy datasets.""" num_datapoints = 100 num_features = 10 num_tasks = 10 # Generate data X = np.random.rand(num_datapoints, num_features) y = np.random.randint(2, size=(num_datapoints,...
4,465
1,649
import pandas as pd df = pd.read_sql( ''' SELECT a.name, h.name, s.name, sd.t, sd.y FROM assets a JOIN hardpoints h ON a.id = h.asset_id JOIN signals s ON h.id = s.hardpoint_id JOIN LATERAL ( SELECT x.t, x.y FROM signal_data x WHERE x.signal_id = s.id ORDER BY x...
1,104
422
# data hiding - encapsulation # this can be achieve by making the attribute or method private # python doesn't have private keyword so precede # the attribute/method identifier with an underscore or a double # this is more effective if object in import or used as a module # it isn't that effective # no underscore = pu...
557
168
# -*- coding: utf-8 -*- # # Copyright 2015 Google LLC. 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 requir...
2,311
802
import time a = 3215.35127 b = 3. start = time.time() for i in range(100000000): c = a / b end = time.time() time_elapsed = end - start print('Time elapsed (div ver) = %.5f' % time_elapsed) a = 3215.35127 b = 1./3. start = time.time() for i in range(100000000): c = a * b end = time.time() time_elapsed = end...
383
184
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
5,373
1,479
import math lines = 30 radius_x = 550 radius_y = 550 axes = 20 def frange(start, stop, step): while start < stop: yield start start += step def setup(): size(1080, 2160) background(51) ellipseMode(RADIUS) stroke(255) noFill() strokeWeight(1) # center the coordinate sys...
1,107
483