text stringlengths 38 1.54M |
|---|
import numpy as np
import scipy.misc as misc
import matplotlib.pyplot as plt
disc_se = np.array([[False, True, False], [True, True, True], [False, True, False]], dtype=np.bool)
def dilation(binary_img, structure_element=disc_se):
dialated = np.zeros_like(binary_img)
cent_y = structure_element.shape[0] // 2
... |
#!/usr/bin/env python
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# 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 rig... |
from enum import Enum
class OdinEnum(Enum):
"""Enumeration Class for OdinEnum
This enumeration class instructs all enumeration objects inheriting from it
to show their value when they are requested to be printed to the standard
output.
"""
def __str__(self):
return self.value
|
import discord
from discord.ext import commands
class Node:
def __init__(self, question, emoji):
self.question = question
self.emoji = emoji
self.children = []
def add_children(self, *children):
for child in children:
self.children.append(child)
def get_node(s... |
list1 = ['apple', 'orange', 'pear']
print([i[0].upper() for i in list1])
list2 = ['apple', 'orange', 'pear']
print([i for i in list2 if i.count('p') > 0])
list3 = ["TA_parth", "student_poohbear",
"TA_michael", "TA_guido", "student_htiek"]
print([i[3:] for i in list3 if i.startswith('TA_')])
lis... |
from django.db import models
from django.contrib.auth.models import User
from saekki_pro import settings
from django.contrib.postgres.fields import ArrayField
# 약속게시물
class Promise(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=20... |
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
new_node = Node(value)
if self.root == None:
self.root = new_node
else:
current_node = self.... |
"""
simple reporter utilities for SMC
"""
import numpy as np
from jax.lax import stop_gradient
import jax
from jax.ops import index, index_add, index_update
from jax import numpy as jnp
from jax.config import config; config.update("jax_enable_x64", True)
class BaseSMCReporter(object):
"""
generalized reporter ... |
"""Programatically interact with a Google Cloud Storage bucket."""
from pip._internal import main as pipmain
from os import environ
import os
try:
from google.cloud import storage
except ModuleNotFoundError:
pipmain(['install', 'google-cloud-storage'])
from google.cloud import storage
bucketName = enviro... |
from typing import List
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from src import models, schemas, crud
from src.database import engine, SessionLocal
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yie... |
#《TF Girls 修炼指南》第四期
# 正式开始机器学习
# 首先我们要确定一个目标: 图像识别
# 我这里就用Udacity Deep Learning的作业作为辅助了
# 1. 下载数据 http://ufldl.stanford.edu/housenumbers/
# 2. 探索数据
# 3. 处理数据
# 4. 构建一个基本网络, 基本的概念+代码 , TensorFlow的世界
# 5. 卷积ji
# 6. 来实验吧
# 7. 微调与结果
|
"""
URL patterns for personal app
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^portfolio$', views.portfolio, name='portfolio'),
url(r'^about$', views.about, name='about'),
]
|
from clint.textui import progress
from django.core.management.base import BaseCommand
from django.db.models import Count
from shapes.models import MaterialShape
from normals.tasks import auto_rectify_shape
class Command(BaseCommand):
args = ''
help = 'Auto-rectify all shapes'
def handle(self, *args, **... |
__author__ = 'Vit'
from bs4 import BeautifulSoup
from urllib.parse import unquote
from data_format.url import URL
from data_format.fl_data import FLData
from common.util import _iter, quotes, psp
from interface.view_manager_interface import ViewManagerFromModelInterface
from model.site.parser import BaseSiteParser
... |
#!/usr/bin/python
#File name: if.py
number = 23
guess = int(input('Enter an integer:'))
if guess == number:
print ('Congurations, you guessed it.')
print ('But you do not win any prizes!')
elif guess < number:
print ('No, it is a litter higher than that')
else:
print ('No, it is a litter lower than that')
print... |
import pandas as pd
import numpy as np
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import cross_val_score
amino_acids = np.array(['R', 'H' ,'K' ,'D' ,'E' ,'S' ,'T... |
from codecs import open
from re import findall, sub, IGNORECASE
import sys
with open('../transcript.txt', 'r') as f:
lines = f.readlines()
search_patterns = [None] * len(lines)
for i, line in enumerate(lines):
line = line.strip()
line = sub(r'[\wą-ž]', r'\g<0>[~`^]?', line)
line = sub(r' ', r'[\s... |
# from django.contrib.auth.models import User
from django.http import Http404
# from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.models import User
from .models import Client, Ta... |
#
from positive import *
# safely join directory strings
def osjoin(a,b):
import os
return str( os.path.join( a, b ) )
# Class for basic print manipulation
class print_format:
magenta = '\033[0;35m'
cyan = '\033[0;36m'
darkcyan = '\033[0;36m'
blue = '\033[0;34m'
green = '\033[92m'
yellow = '... |
# 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"); you may ... |
TEMPLATE_TYPE_BUTTON = 'button'
TEMPLATE_TYPE_GENERIC = 'generic'
class TemplateElement(object):
def __init__(self, title, subtitle=None, item_url=None, image_url=None, buttons=None):
assert len(title) < 81, 'Title limit of 80 chars reached'
if subtitle is not None:
assert len(subtit... |
def replace(identifier_commit_invalid):
print('line_maps')
print('mode_clean_invalid_mask_valid_am_fetch')
"""Replaces a snapshot"""
app = get_app()
tracker_or_and_reader_failover = app.get_snapshot(identifier_commit_invalid
)
if not tracker_or_and_reader_failover:
click.echo("Co... |
print('This app will do things to rainfall data')
print('----------------------------------------')
rainFall = []
monthlyFall = input('Enter the monthly rainfall sep by comma eg 5,6,7,8')
rainFall = monthlyFall.split(',')
#go through each element of the list
#and convert it to an integer
for i in range(len(rainFall))... |
# Установка драйвера для браузера
# В этом курсе мы будем работать с драйвером для Chrome, так как на данный момент это самый популярный браузер, и в первую очередь следует убедиться, что веб-приложение работает для большинства пользователей.
# http://gs.statcounter.com/browser-market-share/desktop/worldwide/#monthly-... |
#!/usr/bin/python
import sys, os, string, re
#This script goes through a ChangeLog and grabs sections based on the search string
#entered by the user. Sections are defined as text between dates
if(len(sys.argv) != 3):
print "Invalid Number of Args"
print "Usage - adjustChangeLog.py filename searchString"
sys.... |
from __future__ import print_function, unicode_literals
import datetime
from decimal import Decimal
import json
from mock import patch
from gratipay import wireup
from gratipay.billing.payday import Payday
from gratipay.testing import Harness
class DateTime(datetime.datetime): pass
datetime.datetime = DateTime
c... |
from setuptools import setup
setup(
name='fake project',
author='Nobody Important',
packages=['fakeproject', 'fakeproject/sub'],
version=0.1,
)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 11:23:28 2017
@author: mmic
"""
import numpy as np
import scipy.stats as st
from scipy.stats import norm
import scipy.integrate as integrate
import numba
def rouwen(rho, mu, step, num):
'''
Adapted from Lu Zhang and Karen Kopecky. Python by Ben Tengelsen.
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import astropy.units as u
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest, assert_quantity_allclose
from ...datasets imp... |
#!/usr/bin/env python3
import asyncio
import discord
import datetime
from discord.ext import commands
from utils import database, shared, utils, checks
def time_until_next_birthday():
last_message = utils.read_property('last_birthday_check')
if last_message:
today = datetime.datetime.utcnow().strftime... |
from datetime import date
from django.db import IntegrityError
from django.urls import reverse
import django_comments
from fiscal.forms import MemberForm
from workshops.models import Member, MemberRole, Membership
from workshops.tests.base import TestBase
CommentModel = django_comments.get_model()
class Membership... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''Copyright (C) 2018, Nudt, JingshengTang, All Rights Reserved
#Author: Jingsheng Tang
#Email: mrtang@nudt.edu.cn
# This gui program employs the vertical synchronization mode on the basis of using the directx
# graphic driver. It makes the program update the drawing syncho... |
# -*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class College(models.Model):
title = models.CharField(u'标题', max_length=500)
show = models.BooleanField(u'是否发布', default=False)
time = models.DateField(u'发布时间', auto_now_add=True)
... |
from random import randint
jogos = []
aposta = []
quant = int(input('Gerar quantos jogos? '))
while len(jogos) != quant:
while True:
num = randint(1, 60)
if num not in aposta:
aposta.append(num)
if len(aposta) == 6:
break
jogos.append(aposta[:])
aposta.clear... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from pwn import *
local = 0
link = '159.138.137.79:65267'
host,port = map(str.strip, link.split(':')) if link != '' else ("",0)
context.log_level = 'debug'
#context.terminal = "/home/noone/hyperpwn/hyperpwn-client.sh"
context.terminal = ['mate-terminal','--geometry=94x60... |
import cv2
import numpy as np
print("Package Imported")
img = cv2.imread('E:\Python Project\Resources\car.jpg')
cv2.imshow("car", img)
cv2.waitKey(0)
cv2.destroyAllWindows() |
import pandas as pd
import pymongo
import time
from sqlalchemy import create_engine
client =pymongo.MongoClient("my_mongodb")
db = client.infobvg
collection = db.koepenick
time.sleep(10)
entries = collection.find()
pg = create_engine('postgresql://postgres:1234@my_postgres:5432/my_bvg_data', echo=True)
pg.execute(... |
import os.path
from lsst.utils import getPackageDir
config.load(os.path.join(getPackageDir("obs_subaru"), "config", "hsc", "isr.py"))
from lsst.obs.hsc.detrends import HscFlatCombineTask
config.combination.retarget(HscFlatCombineTask)
config.combination.load(os.path.join(os.environ['OBS_SUBARU_DIR'], 'config', 'hsc'... |
# -*- coding: utf-8 -*-
import json
from django.http import Http404
from django.core.serializers.json import DjangoJSONEncoder
from django.shortcuts import (
HttpResponse, redirect, render_to_response, RequestContext
)
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import... |
#Copyright (C) 2016 Paolo Galeone <nessuno@nerdz.eu>
#
#This Source Code Form is subject to the terms of the Mozilla Public
#License, v. 2.0. If a copy of the MPL was not distributed with this
#file, you can obtain one at http://mozilla.org/MPL/2.0/.
#Exhibit B is not attached; this software is compatible with the
#lic... |
#!/apps/anaconda/anaconda-2.0.1/bin/python
from params import *
run = ''
output = work_folder+'/calib'
indir = replay_folder_me
batch = False
show = 0
gains_file = ''
final = None
method = 'island'
# input parameters
args = sys.argv
#if len(args)<3: sys.exit('no arguments')
for i,a in enumerate(args):
if a in ['-r... |
from django.db import models
from apex_api.models import User
class UserAmount(models.Model):
user = models.ForeignKey(to=User, on_delete=models.CASCADE)
balance = models.DecimalField(max_digits=19, default="0", decimal_places=2)
def __str__(self):
return f"Hello {self.user} this is your balance ... |
# Dan Schellenberg
# Drawing a square of any size
# Note that this program is inefficient. We haven't explored for/while loops yet.
import turtle
the_window = turtle.Screen()
the_background = the_window.textinput("Background Color", "Please enter the background color")
the_window.bgcolor(the_background)
sarah = tu... |
# Imports
import torch
from torch.autograd import Variable
from models.classes.adjustable_lenet import AdjLeNet
from models.classes.first_layer_unitary_lenet import FstLayUniLeNet
from data_setup import Data
from academy import Academy
from adversarial_attacks import Attacker
import torchvision.transforms.fun... |
from skimage.feature import daisy
from skimage import data
import matplotlib.pyplot as plt
import csv
import imquality.brisque as brisque
import PIL.Image
import os
from os.path import expanduser
import numpy as np
import sys
from skimage.transform import rescale, resize, downscale_local_mean
from blob_detection impor... |
from dynamic_rest.viewsets import DynamicModelViewSet
from .models import Parent, Child
from .serializers import ParentSerializer, ChildSerializer
class ChildViewSet(DynamicModelViewSet):
queryset = Child.objects
serializer_class = ChildSerializer
class ParentViewSet(DynamicModelViewSet):
queryset ... |
def solution(h):
answer = []
h.reverse()
while h:
tmp = h.pop(0)
flag = len(h)
for i in h:#reversed(h):
if i > tmp:
break
flag-=1
# answer.insert(0,flag)
answer.append(flag)
answer.reverse()
return answer |
import tensorflow as tf
import utility
@utility.multi_input_model
@utility.named_model
def cnn_multi_input_v2_basic():
def get_submodel():
input_ts = tf.keras.layers.Input(shape=(20, 1))
temp1 = tf.keras.layers.Convolution1D(8, 3, activation="relu")(input_ts)
temp1 = tf.keras.layers.MaxPo... |
from django.urls import path
from . import views
urlpatterns= [
path('', views.home, name='home'),
path('settings/', views.SettingsView.as_view(), name='settings'),
path('skills/', views.SkillListview.as_view(), name='skill-list'),
path('skills/create', views.SkillCreateView.as_view(), name='skill-creat... |
# Problem #58 [Medium]
# An sorted array of integers was rotated an unknown number of times.
#
# Given such an array, find the index of the element in the array in faster than linear time.
# If the element doesn't exist in the array, return null.
#
# For example, given the array [13, 18, 25, 2, 8, 10] and the ele... |
#coding: utf-8
import random,sys,math
import logging
from config import *
__all__ = ['generate']
def exponential (mean):
return (-mean * math.log(random.random()))
def getPacketSize (averagePacketSize):
packetSize = int(exponential(averagePacketSize))
while (packetSize < MIN_PACKET_SIZE) or (packetSize > MAX_P... |
""""
作者:jx
日期:2018-11-1
版本:1
文件名:data_process.py
功能:对striatum、cortex、liver三个组织的数据分别进行预处理
"""
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
def pre_select_gene(str_2m_df, str_6m_df, str_10m_df, N):
"""
预处理基因表达数据
... |
# encoding: utf-8
import argparse
import json
import os
import traceback
import tornado.ioloop
import tornado.web
import mrep.builder as builder
import mrep.morph as morph
import mrep.pattern as pattern
class Database(object):
def __init__(self, sentences):
parser = morph.MeCabParser()
data = [... |
from util import merge_dict, ComparableMixin
import pandas as pd
import numpy as np
import queue
import math
import random
# Random Encoding
def create_encoding_random(unique_classes):
"""
:param unique_classes: container with the unique classes
:return: a dictionary having the classes as key and binary... |
'''
Name:
Date:
Class:
Assignment:
'''
import webapp2# uses the webapp2 library
class MainHandler(webapp2.RequestHandler): #Declaring a class
def get(self):# Function that starts everything. Catalyst.
about_button = Button()
about_button.label = "About Us"
about_button.show_label()
... |
# encoding: utf-8
# -*- test-case-name: ipython1.test.test_nodes -*-
"""The classes and interfaces for nodes and cells for use in notebooks
"""
__docformat__ = "restructuredtext en"
#-------------------------------------------------------------------------------
# Copyright (C) 2005 Fernando Perez <fperez@colora... |
print('testing 061121')
print('this is a change')
print('just generated a gpg key for the sake of verifying commits') |
# get the user's information
print("\nPlease enter the following information:\n")
first_name = input("First name: ")
last_name = input("Last name: ")
email = input("Email address: ")
phone = input("Phone number: ")
job_title = input("Job title: ")
id_number = input("ID number: ")
hair = input("Hair color: ")
eyes = inp... |
import pytest, time
from utils import environment as env
from utils.environment import Pages as on
@pytest.mark.usefixtures("test_setup")
class TestCNTProject(object):
def test_sal(self):
self.driver.get(env.page_url)
on.Home.navigate_to_saysalot_page(self)
on.SAL.scrolling_down_page(self... |
#!/usr/bin/python
#import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module
def _get_blazar_hosts(reservation):
req_url = reservation.get_endpoint() + "/os-hosts"
return reservati... |
import os
import sys
import time
from codebase.utils.log import Log
from codebase.datasets import TextDataset, DataPreprocess
from codebase.utils.prepare import Preparation
from codebase.condGAN import condGAN
dir_path = (os.path.abspath(os.path.join(os.path.realpath(__file__), './.')))
sys.path.append(dir_path)
if ... |
def intro(**data):
print("\nData type of argument:",type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)
intro(Firstname="John", Lastname="Wood", Email="johnwood@nomail.com", Country="Wakanda", Age=25, Phon... |
# MIT License
#
# Copyright (c) 2018 Capital One Services, LLC
#
# 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, m... |
import heapq
from collections import defaultdict
from sys import maxsize
class Graph:
def __init__(self, n):
self.graph = defaultdict(list)
self.n = n
def add_edge(self, u, v, weight):
self.graph[u].append((v, weight))
def printer(self):
print(f"U\tV\tW")
print(f"... |
"""
============================
Author:柠檬班-木森
Time:2020/1/6 21:30
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
需求:1、计算1+2+3+4+。。。。100的结果
内置函数range:
range(n):默认生成一个 0到n-1的整数序列,对于这个整数序列,我们可以通过list()函数转化为列表类型的数据。
range(n,m):默认生成一个n到m-1的整数序列,对于这个整数序列,我们可以通过list()... |
# Given a string, determine if it is a palindrome, considering only
# alphanumeric characters and ignoring cases.
#
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem.
# import string
# def isPalindrome(s):
# s = s.lower() #ignoring case
# # s = s.translate(None, string.punctuation)
# s.translate(s... |
import numpy as np
my_list1=[1,2,3,4]
my_list2=[5,6,7,8]
my_array=np.array([my_list1,my_list2])
#print (my_array)
#usage of shape function
#print (my_array.shape)
#finding out the datatype of the memeber of the array
#print (my_array.dtype)
#zeros, ones, empty, eye, arrage
#new_array1=np.zeros(5)
#print (new_array... |
from csv2libsvm import csv2libsvm
from optparse import OptionParser, OptionValueError, Option
import copy
import json
def check_csv_str(option, opt, value):
try:
return value.split(",")
except ValueError:
raise OptionValueError("option %s: invalid csv list value: %s" % (opt, value))
def check... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2017, 2018
# --------------------------------------------------------------------------
# Author: Olivier OUDOT... |
def mount_drive():
from google.colab import drive
drive.mount('/content/gdrive')
my_drive = '/content/gdrive/My Drive/'
image_folder = my_drive + 'TestImages/'
training_folder = my_drive + "Traning/"
return my_drive, image_folder, training_folder |
import socket
from Cryptodome.Cipher import AES
import time
import os.path, os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from lazyme.str... |
import random
import sys
import datetime
def main(data_size, file_num):
file_name = "data" + str(file_num) + ".txt"
with open(file_name, "w") as f:
track = random.randint(1, data_size - 2)
f.write(str(data_size) + " " + str(track) + "\n")
for i in range(0, data_size):
... |
# Problem 1: Two Sum
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You ... |
# mdump basic function
from __future__ import print_function
import time
import sys
from api import CallbackManager
import api
import bisect
from collections import defaultdict
import functools
from volatility.plugins.overlays.windows.xp_sp2_x86_syscalls import syscalls
from utils import ConfigurationManager as conf_m... |
import unittest
from v8_ComMeN.ComMeN.Base.Events.Translocate import *
from v8_ComMeN.ComMeN.Base.Node.Patch import *
from v8_ComMeN.ComMeN.Base.Network.MetapopulationNetwork import *
class TranslocateTestCase(unittest.TestCase):
def setUp(self):
self.probability = 0.1
self.compartment = 'a'
... |
import pickle
from rltk.io.serializer import Serializer
class PickleSerializer(Serializer):
"""
`Pickle serializer <https://docs.python.org/3/library/pickle.html>`_ .
"""
def loads(self, string):
return pickle.loads(string)
def dumps(self, obj):
return pickle.dumps(obj)
|
#!/usr/bin/python3
import sys, os
file_list = os.listdir()
input_file = sys.argv[1]
output_file = open("sorted_polymorphic", 'w')
output_file2 = open("sorted_length", 'w')
block = ''
block_list = []
flag = False
with open(input_file, 'r') as f:
for line in f:
if line.startswith("#"):
if b... |
#
# Created as part of the StratusLab project (http://stratuslab.eu),
# co-funded by the European Commission under the Grant Agreement
# INFSO-RI-261552."
#
# Copyright (c) 2011, SixSq Sarl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
#coding:utf8
from django.shortcuts import render, redirect
from page import models
def add_link(request):
if request.method == 'GET':
link = models.Link.objects.all().order_by('count', '-date')[:20]
return render(request, 'add_link.html', {'list': link})
elif request.method == 'POST':
add_link_to = request.PO... |
from dotenv import load_dotenv
import instabot
import os
import argparse
from instabot import Bot
from os import listdir
load_dotenv()
INSTAGRAM_LOGIN = os.getenv("INSTAGRAM_LOGIN")
INSTAGRAM_PASSWORD= os.getenv("INSTAGRAM_PASSWORD")
def upload_photo_to_instagram(image_name, caption):
bot = Bot()
bot.login(usern... |
register={.01: 'PENNY',
.05:'NICKEL',
.10:'DIME',
.25:'QUARTER',
.50:'HALF DOLLAR',
1.00:'ONE',
2.00:'TWO',
5.00:'FIVE',
10.00:'TEN',
20.00:'TWENTY',
50.00:'FIFTY',
100.00:'ONE HUNDRED'}
def calculate(pp,ch):
#left_cash=float("{0:.2f}".format(ch-pp))
left_cash=float(ch)-float(pp)
print(left_cash)
resul... |
'''
@Author: Sankar
@Date: 2021-04-10 07:38:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-10 07:45:09
@Title : List_Python-13
'''
'''
Write a Python program to append a list to the second list.
'''
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
list1.extend(list2) |
from collections import Counter
import os
import itertools
#abspath = os.path.abspath(__file__)
#dname = os.path.dirname(abspath)
#os.chdir(dname)
from own.loading import load_reviews_and_rids
from own.saving import make_dirs
##file_path = os.path.join("..","data", "reviews", "processed_testset.txt")
#re... |
# -*- coding: utf-8 -*-
# Rafael Corsi @ insper.edu.br
# Dez/2017
# Disciplina Elementos de Sistemas
#
# script para gerar hack a partir de nasm
# suporta como entrada um único arquivo
# ou um diretório
# Possibilita também a geração do .mif
import os,sys
import argparse
import platform
SIMULATOR = os.path.join(os.pa... |
from django.conf.urls import url, patterns
urlpatterns = patterns('pyconde.sponsorship.views',
url(r'^$',
'list_sponsors',
name='sponsorship_list'),
url(r'^send_job_offer/$',
'job_offer',
name='sponsorship_send_job_offer')
)
|
import xml.etree.ElementTree as ET
def exercise(xml):
"""Iterate over all node elements, check if they are leaf nodes (i.e., have
no node child nodes), and retrieve the creator and title, supplying empty
strings as default values.
"""
ns = {"t": "http://martin.hoppenheit.info/code/generic-tree-xml... |
array=[]
n=int(input('How many elements u want in array: '))
for i in range(n):
f= int(input('Enter no: '))
array.append(f)
print('Entered array: ',array)
if len(array)>=1:
max1=max(array)
min1 = min(array)
diff=max1-min1
print('The difference of largest &smallest value from array: ',diff)
|
#Finds the 4 fractions that can be reduced by cancelling a digit
#in the denominator and the numerator
def forwardArray(a):
#creates an array of the number by inserting each digit
f=[]
a=n
while(a!=0):
f.insert(0,a%10)
a=a/10
return f
def main():
numerator=[]
denominator=[]
... |
import pandas as pd
import matplotlib.pyplot as plt
#assignment 1 Q 4.a
myData = pd.read_csv('/home/cloudera/Desktop/diwakar/data/Auto.csv')
# change path as required
for i in range(0, len(myData.index)):
print (myData.iloc[i])
#assignment 1 Q 4.b
print( myData.shape)
print( myData.describe())
#assignm... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 19:18:19 2020
@author: CEC
"""
from math import exp
ex=1
try:
while True:
print(exp(ex))
ex *= 2
except OverflowError:
print("El número es demasiado grande") |
# -*- coding: utf-8 -*-
from tina.base.api.permissions import TinaResourcePermission, AllowAny, IsAuthenticated, IsSuperUser
from tina.permissions.permissions import HasProjectPerm, IsProjectAdmin
from tina.permissions.permissions import CommentAndOrUpdatePerm
class UserStoryPermission(TinaResourcePermission):
... |
# scene_blend_info.py Copyright (C) 2020, ModellbahnFreak
bl_info = {
"name": "Play/Stop Spacebar",
"author": "ModellbahnFreak",
"version": (0, 1, 0),
"blender": (2, 80, 0),
"location": "3DView -> Side Panel -> Misc -> Playback",
"description": "Changes playback behaviour of the spa... |
import sys
n, a, b = [int(x) for x in sys.stdin.readline().split()]
if a < b:
a, b = b, a
p, q = 1, 1
c1, c2 = 1, 1
for i in range(1, a+1):
p *= n+i-1
q *= i
c1 += p/q
if i == b:
c2 = c1
print c1*c2 |
class Solution:
def maxProduct(self, words: List[str]) -> int:
result = 0
for i in range(len(words)):
for j in range(i+1, len(words)):
if not set(words[i]) & set(words[j]):
result = max(result, len(words[i]) * len(words[j]))
return result
|
"""PathControlAvoidance controller."""
from controller import Motor,GPS,InertialUnit,DistanceSensor,Robot
from pathControl import ProportionalControl as pControl
from pathControl import ObstacleAvoidance as oav
import numpy as np
import csv
TIME_STEP = 16
MAX_VEL = 12
#Index
xyz_Zposition = 2
xyz_Xpositio... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 16:52:19 2018
@author: Bllue
"""
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
#filenames = os.walk('./')
img_width = 100
img_height = 100
#path = os.walk('data/')
#for d in path:
# print(d[0])
# print(len(d[... |
import pandas as import pd
import matplotlib.pyplot as plt
angles = ['0','15','30','45','60','75','90','angInt'])
colNames = ['E_cm','E_ex','phi_cm','fit_XS','fit_S','XS','XS_unc','S','S_unc']
chanNames = ['AZUREOUT_aa=1_R=3.out','AZUREOUT_aa=1_R=4.out','AZUREOUT_aa=1_R=5.out',
'AZUREOUT_aa=2_R=3.out','A... |
#!/usr/bin/env python3
import numpy as np
import spacy
from spacy.lang.en import English
import torch
from infersent.models import InferSent
MODEL_VERSION = 1
MODEL_PATH = "infersent/encoder/infersent%s.pkl" % MODEL_VERSION
MODEL_PARAMS = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool... |
class Solution:
def minAdjDiff(self,arr, n):
min_dff = abs(arr[0]-arr[1])
for i in range(1,len(arr)-1):
if abs(arr[i]-arr[i+1]) < min_dff:
min_dff = abs(arr[i]-arr[i+1])
else:
continue
if min_dff > abs(arr[0]-arr[n-1]):
min_... |
import MySQLdb
conn = MySQLdb.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='bai910214',
db='dawn',
charset='utf8'
)
cursor = conn.cursor()
sql = "select * from user"
cursor.execute(sql)
rs = cursor.fetchall()
for row in rs:
print "user_id = %s, username = %s" % row
sqlInsert ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.