text string | size int64 | token_count int64 |
|---|---|---|
from threading import Thread
import requests
from lxml import etree
from fake_useragent import UserAgent
from queue import Queue
class Spider(Thread):
def __init__(self,url_queue):
Thread.__init__(self)
self.url_queue = url_queue
def run(self):
while not self.url_queue.empty():
... | 1,052 | 324 |
'''
A Python program to test whether a passed letter is a vowel ornot.
'''
def isVowel (inputStr):
vowelTuple = ('a', 'e', 'i', 'o', 'u')
for vowel in vowelTuple:
if inputStr == vowel:
return True
return False
def main ():
myStr = input ("Enter a letter")
... | 486 | 158 |
"""Scrape out the Soil Bulk Density and Texture data from Google Drive"""
from __future__ import print_function
import sys
import psycopg2
import pyiem.cscap_utils as util
YEAR = sys.argv[1]
config = util.get_config()
pgconn = psycopg2.connect(
database="sustainablecorn", host=config["database"]["host"]
)
pcurs... | 5,821 | 1,890 |
import pandas as pd
import numpy as np
import pickle
import sklearn.ensemble as ske
from sklearn import tree, linear_model
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.externals import joblib
from sklearn.naive_bayes import GaussianNB
from sklea... | 3,335 | 1,145 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 15:51:34 2017
@author: ktt
"""
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 14:28:01 2017
@author: ktt
"""
def numeral(arabic):
# Returns Roman equivalent of arabic numeral
# Assumes input is int
... | 2,495 | 792 |
import h1st as h1
import pandas as pd
import os
import sklearn
import sklearn.metrics
import subprocess
import pathlib
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import OneHotEncoder
from Forecas... | 5,466 | 1,740 |
from wrapper import rate_handler
import utils
import mappers.repos
import mappers.commits
import mappers.labels
import mappers.pull_requests
import mappers.milestones
import mappers.issues
import logging
import os
from github import Github
if __name__ == "__main__":
logging.config.fileConfig(
fname='loggin... | 1,231 | 429 |
#
# PySNMP MIB module RADLAN-BOOTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-BOOTP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:45:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | 5,267 | 1,970 |
import numpy as np
import autograd.numpy as npa
from copy import copy, deepcopy
from .constants import *
from .utils import reshape_to_ND, grid_center_to_xyz, grid_xyz_to_center
from .derivatives import curl_E, curl_H
class fdtd():
def __init__(self, eps_r, dL, npml):
""" Makes an FDTD object
... | 13,063 | 5,371 |
"""
DuplicatesPipeline
Uses a configurable unique key/item field to filter duplicates on.
HashedDuplicatesPipeline
Automatic (exact) duplicates finder, remembering items based on a hash,
optionally using a hashset for every seen itemtype.
"""
from scrapy.exceptions import DropItem
try:
import cPickle as pickle
ex... | 1,392 | 525 |
from paz.backend.image import draw_circle
from paz.backend.image.draw import GREEN
from paz.backend.image import resize_image
from paz import processors as pr
from paz.abstract import Processor
import numpy as np
from paz.backend.image import lincolor
import seaborn as sns
from matplotlib.backends.backend_agg import Fi... | 5,289 | 1,590 |
# encoding: utf-8
"""
registry.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""
from exabgp.configuration.experimental.engine.raised import Raised
from exabgp.configuration.experimental.engine.section import Section
from exabgp.configuration.experimental.engin... | 3,727 | 1,345 |
from django.contrib import admin
from nmmis.contrib.place.models import Place
admin.site.register(Place) | 105 | 30 |
# Copyright 2020-present, Apstra, Inc. All rights reserved.
#
# This source code is licensed under End User License Agreement found in the
# LICENSE file at http://www.apstra.com/eula
from aos.client import AosClient
from scripts.utils import deserialize_fixture
import urllib3
urllib3.disable_warnings(urllib3.exceptio... | 2,993 | 995 |
""" Base code for dataset conversion and management
This code contains:
- core functions
- asserting definitions to ensure dataset's integrity
TODO
----
#TODO: find the best way to define the global path
#TODO: check tests
#TODO: think if it should be a class in this manner 'dataset_name' etc..
... | 3,405 | 1,032 |
#grade
def grade(a):
total=0
for i in a:
total=total+i
print(total)
per=float(total/5)
print(per)
if per>80:
print("a")
elif per>70:
print("b")
elif per>60:
print("c")
elif per>50:
print("d")
elif per>40:
... | 490 | 215 |
import util
# 日志目录
global logfileDir
logfileDir = './log'
# 数据库配置
global db
db = {
'host': '127.0.0.1',
'port': 27017
}
global daliy
daliy = 'daliy'
global daliyxxx
daliyxxx = 'daliy'+util.yesterday().strftime('%Y%m%d') # daliy20210622
global history
history = 'histest'
global fund
fund = 'fund'
# 基金类型字典
glo... | 1,233 | 767 |
# -*- coding: utf-8 -*-
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 app... | 6,172 | 1,881 |
"""
Tax-Calculator federal tax policy Policy class.
"""
# CODING-STYLE CHECKS:
# pycodestyle policy.py
# pylint --disable=locally-disabled policy.py
import os
import json
import numpy as np
from taxcalc.parameters import Parameters
from taxcalc.growfactors import GrowFactors
class Policy(Parameters):
... | 6,506 | 2,111 |
# Copyright (c) OpenMMLab. All rights reserved.
"""
CommandLine:
pytest tests/test_merge_cells.py
"""
import torch
import torch.nn.functional as F
from mmcv.ops.merge_cells import (BaseMergeCell, ConcatCell, GlobalPoolingCell,
SumCell)
def test_sum_cell():
inputs_x = torch.r... | 2,550 | 1,048 |
# Generated by Django 3.0.8 on 2020-07-31 10:00
from django.db import migrations, models
import django_simple_coupons.helpers
class Migration(migrations.Migration):
dependencies = [
('django_simple_coupons', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name... | 459 | 154 |
"""
/r/3DPrinting Help Bot V2
Tries to help users by replying to them with helpful links
:author: Tim Estermann, @der-test
:original author: Connor Henley, @thatging3rkid
"""
import os
import sys
import time
import pickle
import praw
import praw.models
import datetime
import traceback
import subprocess
import config
... | 6,337 | 1,882 |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2021/7/24 21:45
# @author : Mo
# @function: Layer and Loss
from torch import nn
import torch
import numpy as np
__all__ = ["PriorMultiLabelSoftMarginLoss",
"LabelSmoothingCrossEntropyV1",
"LabelSmoothingCrossEntropy",
"MultiL... | 37,989 | 12,884 |
#_*_ coding:utf-8 _*_
import redis
class Cache(object):
def __init__(self):
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=1)
self.sr = redis.Redis(connection_pool=pool)
def Set(self, key, value):
'''设置 key 值'''
return self.sr.set(key, value)
def ... | 2,075 | 817 |
import numpy as np
# PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
# Original DeepSDF loss
def clamped_l1(pred_dist, gt_dist, trunc=0.1):
pred_dist_trunc = torch.clamp(pred_dist, -trunc, trunc)
gt_dist_trunc = torch.clamp(gt_dist, -trunc, trunc)
loss = torch.abs(pred_dist_trunc... | 1,528 | 627 |
from werkzeug.security import safe_str_cmp
from appcode.models.user import UserModel
# Function to authenticate the user
def authenticate(username, password):
user = UserModel.find_by_username(username)
if user and safe_str_cmp(UserModel.password, password):
return user
def identity(payload):
us... | 389 | 114 |
import numpy as np
import pylab as pl
from time import time
import logging
from motionstruct.functions import init_logging, asciiL, recursive_dict_update
from motionstruct.classes import PhiWorld
import scipy.io as sio
import os
# Help string and argument parsing
from argparse import ArgumentParser, RawTextHelpFormatt... | 5,184 | 1,814 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, string, socket
import smtplib
#导入smtplib和MIMEText
import smtplib
from email.mime.text import MIMEText
from config import mailto_list, mail_host, mail_user, mail_pass, mail_postfix
def send_mail(sub,content):
me=mail_user+"<"+mail_user+"@"+mail_postfix... | 812 | 299 |
# -*- coding: UTF-8 -*-
# description: 小Q有一叠纸牌,一共有n张,从上往下依次编号为1到n。现在小Q要对这叠纸牌反复做以下操作:
# 把当前位于顶端的牌扔掉,然后把新的顶端的牌放到新叠牌的底部。
# 小Q会一直操作到只剩下一张牌为止。小Q想知道每次丢掉的牌的编号。
# example: input:7 (输入为一行,只有一个数字n, 1<=n<=1e6)
#
# output:1 3 5 7 4 2 6 (输出n个用空格间隔的整数,表示每次丢掉的牌的编号)
"""
@para... | 598 | 397 |
"""
Connect|DISPATCH: Connecting Computer-Aided Dispatch (CAD) Systems to ArcGIS.
The gis_append script is activated when incident_push.p is modified in the watch directory.
"""
from connectdispatch import fire_ops
import logging
import os
import yaml
import pickle
import csv
import mgrs
from datetime import datetime... | 10,626 | 3,299 |
#!/usr/bin/env python
""" Running DOE experiments (in parallel)"""
from __future__ import print_function
import sys
import time
import traceback
import numpy as np
import unittest
from openmdao.api import IndepVarComp, Component, Group, Problem, \
FullFactorialDriver, AnalysisError
from open... | 13,723 | 4,274 |
{
"targets": [
{
"target_name": "roboticscape",
"sources": [ "rc-node-bindings.cc" ],
"cflags": [ "-Wall", "-g", "-std=c++1y" ],
"cflags_cc!": [ "-fno-rtti", "-std=c++14" ],
"libraries": [ "-lm", "-lrt", "-lpthread", "-lroboticscape" ],
... | 453 | 162 |
from django.contrib import admin
from .models import ReviewRequest
# Register your models here.
admin.site.register(ReviewRequest)
| 133 | 35 |
"""
Provides the top level flask application configuration.
"""
import sentry_sdk
from flask import Flask
from flask_dance.contrib.azure import make_azure_blueprint
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from werkzeug.middleware.p... | 1,959 | 623 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
__version__ = "0.0.1"
__title__ = "Traceability" | 113 | 46 |
# fora
# class UserModel
# Xu [xw901103@gmail.com] Copyright 2015
from fora.core.model import Model
from sqlalchemy import (
Column,
Integer,
Boolean,
String,
DateTime
)
class UserModel(Model):
__tablename__ = 'users'
id = Column(Integer, primary_key = True, autoincrement = True)
uuid ... | 612 | 201 |
""" Module containing the deserializer api function and supporting classes.
The deserializers are versioned and the ones in this module correspond to the
latest protocol. Old versions of deserializers that were updated are stored in
the legacy_deserializers dict.
"""
import logging
from six import string_types
from t... | 16,590 | 4,284 |
import res.server.server as server
import res.client as client
import threading
import os
import res.server.keyboardlistener
address = ("localhost", 8000)
dataPath = os.getcwd()+"/res/database/clients/db.json"
def startServer():
Server = server.RpcServer(dataPath)
Server.initialize(address)
KeyboardListe... | 1,162 | 352 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import datetime
import enum
import logging
import os
import re
import smtplib
from email.mime.text import MIMEText
from http.client import HTTPConnection
class VAULTIER_SECRET(enum.IntEnum):
secret = 20... | 3,235 | 1,169 |
x = np.linspace(1, 5, num=100)
y = 3*x**2 + 1
integrate.trapz(y, x) # Exact value is 128 | 88 | 52 |
class DeviceCapability(basestring):
"""
router|trans-bridge|source-route-bridge|switch|host|igmp|repeater|phone
Possible values:
<ul>
<li> "router" - Router,
<li> "trans_bridge" - Trans Bridge,
<li> "source_route_bridge" - Source Route Bridge,
<li> "switch... | 632 | 202 |
from .bsnlp import load_bsnlp # noqa
from .persons import load_persons # noqa
| 81 | 33 |
# pretty.py - Pretty formatting for db table rows. There are routines defined
# here for use in a terminal as well as on the web.
#
# Copyright (c) 2013, Christopher Patton, all rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the foll... | 19,776 | 7,059 |
#!/usr/bin/env python3
"""
UAVCAN to TUN network adapter.
"""
import argparse
import os
import struct
import sys
import fcntl
import uavcan
import subprocess
import time
import logging
from queue import Queue, Empty
import threading
DSDL_DIR = os.path.join(os.path.dirname(__file__), "../uavcan_data_types/cvra")
def... | 5,016 | 1,782 |
from xml.etree import ElementTree
def gpx_builder(data):
gpx = ElementTree.Element('gpx')
tree = ElementTree.ElementTree(gpx)
gpx.set('version', '1.0')
gpxname = ElementTree.SubElement(gpx, 'name')
gpxname.text = 'PLACEHOLDER'
rte = ElementTree.SubElement(gpx, 'rte')
for routepoint in ran... | 840 | 306 |
################################################################################
# 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... | 5,050 | 1,441 |
#! /usr/bin/env python3
from tinkoff.cloud.stt.v1 import stt_pb2_grpc
from auth import authorization_metadata
from audio import audio_open_read
from common import build_recognition_request, make_channel, print_recognition_response, BaseRecognitionParser
from google.protobuf.json_format import MessageToDict
from tinkof... | 1,428 | 425 |
import asyncio
import json
import os
from unittest.mock import patch
import pytest
from eth_utils import encode_hex, to_canonical_address, to_checksum_address
from tornado.httpclient import HTTPRequest
from tornado.websocket import websocket_connect
from raiden_installer import load_settings
from raiden_installer.acc... | 33,823 | 10,236 |
""" Regression library """
# =============================================================================
# Imports
# =============================================================================
import theano
import numpy as np
import pymc3 as pm
import random
from coral.statsfunc import get_empirical_cdf, empirica... | 3,872 | 1,299 |
import sys
import time
import copy
import numpy as np
import scipy.io as sio
__all__=['OptimizationBase']
__docformat__ = "restructuredtext en"
class OptimizationBase(object):
""" Base class for descent-like optimization routines.
These are stateful algorithms. The current step, as well as the step inde... | 26,367 | 7,149 |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import sys
import logging
import ccs811LIBRARY
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S')
picdir = os.path.join(os.path.join(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__fil... | 7,091 | 2,699 |
# Copyright 2020 University of Groningen
#
# 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 i... | 7,025 | 1,974 |
import numpy as np
from timeflux.core.exceptions import WorkerInterrupt
from timeflux.core.node import Node
class SelectRange(Node):
"""Select a subset of the given data along vertical (index) or horizontal (columns) axis.
Attributes:
i (Port): default data input, expects DataFrame with eventually ... | 8,138 | 3,007 |
# -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ---------------------------------------------------... | 2,205 | 624 |
nome = input('Digite o nome da pessoa: ')
salario = float(input('Digite o Salario da pessoa: '))
desconto = float(input('Digite a porcertagem de desconto do salario: '))
salario_final = salario - (salario / desconto)
print('{}, tem o Salário de R${:.2f}, mas houve desconto de {}%, o salario final do mes foi R${:.2f}'.... | 364 | 133 |
import requests
from bs4 import BeautifulSoup
import sqlite3
import re
from OperateDatabase import *
import socket
import random
import time
socket.setdefaulttimeout(1000)
base_url = 'http://www.freepatentsonline.com'
additional_url = ['/result.html?p=',
'&sort=relevance&srch=top&query_txt=AN%2F%22... | 5,040 | 2,023 |
import torch
import unittest
from mqbench.prepare_by_platform import prepare_by_platform, BackendType
from mqbench.convert_deploy import convert_deploy
from mqbench.utils.state import enable_calibration, enable_quantization
class TestObserver(unittest.TestCase):
def test_quantile_observer(self):
model_to... | 4,505 | 1,504 |
#!/usr/bin/env python
# Copyright 2019 QuantRocket 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 req... | 3,005 | 955 |
import numpy as np
import pandas as pd
def SOEP_to_df_old(dataf):
"""
This function takes the SOEP data as a dataframe and returns the the harmonized data such that the rest of the code can work with it. It also renames the columns etc
"""
dataf = dataf.copy()
# Checking whether some adjustments ... | 8,520 | 3,268 |
from network import LoRa
import socket
import time
modes=[LoRa.LORA]
coding=[LoRa.CODING_4_5,LoRa.CODING_4_6,LoRa.CODING_4_7,LoRa.CODING_4_8]
pub=[True,False]
for k in modes:
for i in range(0,16):
for j in range(0,6):
for l in coding:
for p in pub:
#LoRa
... | 1,404 | 477 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
from cryptography.fernet import Fernet
import hashlib
def _enc(data, key):
key_32 = base64.urlsafe_b64encode(hashlib.sha512(key).digest()[:32])
f = Fernet(key_32)
return f.encrypt(data)
def _dec(b, key):
key_32 = base64.urlsafe_b64encode(... | 731 | 297 |
#!/usr/bin/env python
from setuptools import setup, find_packages
from os.path import join, dirname
with open("README.md", "r") as fh:
long_description = fh.read()
version_ns = { }
exec(open('niimpy/_version.py').read(), version_ns)
version = version_ns['__version__']
del version_ns
requirementstxt = join(dirna... | 1,268 | 405 |
#coding=utf-8
from abc import ABCMeta, abstractmethod
class server_action(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def description(self):
pass
@abstractmethod
def parse_parameters(self):
pass
@abstractmethod
def run(self):
... | 329 | 98 |
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.optimizers import RMSprop
def get_model(maxlen, chars_num):
model = Sequential()
model.add(LSTM(128, input_shape=(maxlen, chars_num)))
model.add(Dense(chars_num, activation='softmax'))
optimize... | 430 | 151 |
"""File IO utilities using HDF5.
The data element saved in HDF5 should be a dictionary. The types of each value
should be in HDF5_DATA_TYPES.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import h5py
import numpy as np
import uuid
import traceback
d... | 4,374 | 1,276 |
import taichi as ti
@ti.program_test
def test_while():
x = ti.var(ti.f32)
s = ti.var(ti.i32)
n = 128
@ti.layout
def place():
ti.root.dense(ti.i, n).bitmasked().dense(ti.i, n).place(x)
ti.root.place(s)
@ti.kernel
def func():
for i in x:
ti.atomic_add(s[None], 1)
x[0] = 1
func()
... | 344 | 173 |
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
from sklearn.neighbors import NearestNeighbors
from keras.datasets import cifar10
import numpy as np
from keras import backend as K
################################################################
# input image dimension... | 2,752 | 1,188 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2020 E.U. Copernicus Marine Service Information
import sys
from pathlib import Path # noqa E402
from setuptools import find_packages, setup
assert sys.version_info >= (3, 6, 0), "cmtb requires Python 3.6+"
CURRENT_DIR = Path(__file__).parent
sys.path.in... | 2,291 | 797 |
from application.models.Tag import Tag
from application.app import db
from flask import jsonify
import traceback
class TagService:
def create_tag(self, params):
try:
tag_object = Tag(tag_name = params["tag_name"])
db.session.add(tag_object)
db.session.commit()
return {"Message": "Tag created successfull... | 1,520 | 558 |
from rest_framework import serializers
from .models import Weblink
class WeblinkSerializer(serializers.ModelSerializer):
class Meta:
model = Weblink
fields = ('id', 'content', 'url')
| 207 | 56 |
# Check number and return result
def num_test(num):
# Check number
if num > 10:
return 'Greater than 10.'
elif num < 10:
return 'Less than 10.'
else:
return 'Equal to 10.'
# Define main function
def main():
# Prompt user for a number
number = float(input('Ente... | 479 | 157 |
def is_valid(phrase):
words = phrase.split()
return len(set(words)) == len(words)
passphrases = open("day4.txt").readlines()
valid_phrases = list(filter(is_valid, passphrases))
print('Valid Passphrases:', len(valid_phrases)) # = 337
| 243 | 89 |
import datetime
import json
# import os.path
import re
import click
from PyOrgMode import PyOrgMode
def get_valid_filename(s):
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove a... | 5,926 | 1,937 |
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
This module is used to cache per-collection type information.
"""
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2017, G. Klyne"
__license__ = "MIT (http://opensource.org/licens... | 8,754 | 2,453 |
import aiinpy as ai
import numpy as np
# Create Dataset
inTrainData = np.random.choice(([0, 1]), (2, 100))
outTrainData = np.zeros((2, 100))
for i in range(100):
outTrainData[:, i] = [1, 0] if sum(inTrainData[:, i]) == 1 else [0, 1]
# NN model
model = ai.model(2, 2, [
ai.nn(outshape=16, activation=ai.relu(), lear... | 556 | 247 |
# Copyright 2017 Tensorflow. All Rights Reserved.
# Modifications copyright 2018 UT Austin/Saharsh Oza & Taewan Kim
# We follow the object detection API of Tensorflow
#
# 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... | 10,212 | 3,259 |
d = {
'John': 2.5,
'Paul': 1.5,
'Laura': 1
}
print(d['John']) # 2.5
| 80 | 47 |
from __future__ import print_function
import sys
from pyspark.sql import SparkSession
#<1> Import the print() function
#<2> Import System-specific parameters and functions
#<3> Import SparkSession from the pyspark.sql module
#==========================================
# NOTE:
#
# In general, avoid using groupByKey(... | 3,863 | 1,281 |
"""Functions to help play and score a game of blackjack.
How to play blackjack: https://bicyclecards.com/how-to-play/blackjack/
"Standard" playing cards: https://en.wikipedia.org/wiki/Standard_52-card_deck
"""
def is_ten(card):
tens = ["K", "J", "Q", "10"]
return card in tens
def is_ace(card):
retur... | 3,513 | 1,324 |
import tweepy
CONSUMER_KEY = 'EQxFiVurRxZRKZzH4tJ2PtsX8'
CONSUMER_SECRET = '59WSgueMvx7VUbuYywwC6rqwdlLUkc0yufiTnITvgmPJAN9RzE'
ACCESS_TOKEN = "349586645-4e7WmYpjvzKUmsKh3C9pNyv0QzlbVB80nlvR4q02"
ACCESS_TOKEN_SECRET = "qblYvvigttmP5elDFMsIJacO7gOknN794ubMThlyV0pfj"
auth = tweepy.OAuthHandler('EQxFiVurRxZRKZzH4tJ2PtsX8'... | 2,246 | 861 |
import dask.array as da
import numpy as np
import pytest
from skimage import data, morphology, set_backend
from uskimage_demo import diplib_backend
from skimage.morphology import footprints
modes = ['wrap', 'reflect', 'nearest', 'constant', 'mirror']
# note: 'reflect' unspported by diplib, falls back to ski... | 1,363 | 471 |
n = input('Digite algo: ')
numero = int(input("digite um numero: "))
num1 = float(input("digite um numero decimal: "))
nome = str(input("digite algum nome: "))
print(type(n)) # mostrar o tipo de 'n', se é int, float, bool, str...
print(n.isnumeric()) # vai dizer se n é numerico ou nao, imprimindo true or fal... | 797 | 280 |
from torch import nn
import torch.nn.functional as F
import torch
import math
import numpy as np
# https://github.com/caojiezhang/MWGAN
class ResidualBlock(nn.Module):
"""
Residual Block with instance normalization.
"""
def __init__(self, dim_in, dim_out):
super(ResidualBlock, self).__init__... | 7,265 | 2,757 |
#
# 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 ... | 3,115 | 877 |
import random
import time
from enviroment import Enviroment
ENV = Enviroment("")
def random_color():
return random.randint(0, 256)
while True:
ENV.console.print(
"[color({color})]COLOR SUPPORT[/color({color})]".format(color=random_color()))
time.sleep(1)
| 280 | 100 |
"""
Copyright (c) 2015, The Regents of the University of California (Regents).
All rights reserved.
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
... | 5,933 | 1,943 |
import discord
from discord.ext import commands
from discord import Game
class game(commands.Cog):
def __init__(self, Bot):
self.bot = Bot
#jus a comfy seperate cog to change game status, will add versions setup nd other backend codes here
@commands.Cog.listener()
async def on_ready(self):
await self.bot.... | 504 | 164 |
import flask
import json
from infosystem.common import utils
from infosystem.common.subsystem import controller
from infosystem.common import exception
from infosystem.subsystem.user.email import TypeEmail
class Controller(controller.Controller):
def __init__(self, manager, resource_wrap, collection_wrap):
... | 7,119 | 1,857 |
#!-*- coding:utf-8 -*-
#!/usr/bin/env python
#---------------------------------------------------
#コメント構造体
#copyright 2010-2012 ABARS all rights reserved.
#---------------------------------------------------
from google.appengine.ext import db
from google.appengine.api import users
from myapp.Bbs import Bbs
from mya... | 1,475 | 487 |
N = int(input())
for i in range(N):
print(str(N) * (N - i))
| 65 | 31 |
#!/usr/bin/env python
#
# pyfindactuators.py
#
# Simply call the hebiros_node to find the list of actuators.
import sys
import rospy
from hebiros.srv import EntryListSrv
if __name__ == "__main__":
# Initialize the basic ROS node.
rospy.init_node('pyfindactuators')
# You can choose to wait until the... | 1,284 | 425 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""logdweb forms"""
from django.forms import *
class CreatePageForm(Form):
name = CharField(max_length=50)
class ColorNameForm(Form):
stat = CharField(max_length=30)
color = CharField(max_length=10)
class ColorStatsForm(Form):
name = CharField(max_lengt... | 397 | 149 |
"""
Knowledge Extraction with No Observable Data (NeurIPS 2019)
Authors:
- Jaemin Yoo (jaeminyoo@snu.ac.kr), Seoul National University
- Minyong Cho (chominyong@gmail.com), Seoul National University
- Taebum Kim (k.taebum@snu.ac.kr), Seoul National University
- U Kang (ukang@snu.ac.kr), Seoul National University
This... | 5,386 | 1,735 |
import utils as u
with open(__file__ + ".input.txt", "r+") as file:
raw_input = file.read()
# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_
def get_place_coordinates(boarding_pass):
row_instructions = boarding_pass[:-3]
col_instructions = boarding_pass[-3:]
# hey ... | 1,740 | 767 |
from functools import partial
from Qt.QtCore import *
from Qt.QtWidgets import *
import tpDccLib as tp
import tpMayaLib as maya
from tpQtLib.core import window
from tpQtLib.widgets import splitters
from tpMayaLib.core import decorators
class JointOrient(window.MainWindow, object):
def __init__(self):
su... | 21,615 | 7,595 |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app, server
from pages import index
# ====== Navigation ====== #
# nav = html.Ul(
# [
# html.Li(html.A("print(fiction)", ... | 2,584 | 708 |
from tkinter.ttk import Button
# Convenience mixin to add back button to view
class ViewHasBackButton:
def add_back_button(self, *args, **kwargs):
Button(self.frame, text="Back", command=self.back_home).grid(*args, **kwargs)
def back_home(self):
from views import HomeView
self.app.replace_view(HomeVi... | 323 | 115 |
import unittest
from feminist_api import *
class FeministAPI(unittest.TestCase):
def test_ranking(self):
self.assertNotEqual((None, None, None, None), get_ranking_for_company('zara'))
self.assertNotEqual((None, None, None, None), get_ranking_for_company('facebook'))
self.assertNotEqual((None, None, None, None),... | 402 | 140 |
#
# PyANC350v4 example file
# by Brian Schaefer, adapted from pyanc-example.py by Rob Heath
#
from pyanc350.v4 import Positioner
import time
ax = {'x':0,'y':1,'z':2}
#define a dict of axes to make things simpler
anc = Positioner()
#instantiate positioner as anc
print('----------------------------------------------... | 3,408 | 1,178 |
# Copyright (c) 2019 PaddlePaddle Authors. 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 applic... | 7,978 | 2,349 |