text stringlengths 8 6.05M |
|---|
import os,sys,argparse,re
import json
import itertools
import logging
logger = logging.getLogger('device2')
import logcat
import common
from common import Experiment
class AllYouCanMeasure(dict):
ACTION_LOCATION_UPDATE = "edu.buffalo.cse.phonelab.allyoucanmeasure.receivers.LocationReceiver.LocationUpdated"
ACTION... |
from jitcache import Cache
import time
from concurrent.futures import ThreadPoolExecutor
cache = Cache()
@cache.memoize
def slow_fn(input_1, input_2):
print("Slow Function Called")
time.sleep(1)
return input_1 * input_2
n_threads = 10
executor = ThreadPoolExecutor(max_workers=n_threads)
future_list =... |
from django.db import models
# Create your models here.
class Movies(models.Model):
belongs_to_collection = models.TextField(blank=True, null=True)
budget = models.IntegerField(blank=True, null=True)
genres = models.TextField(blank=True, null=True)
homepage = models.TextField(blank=True, null=True)
... |
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse_lazy, reverse
from django.views.generic import CreateView
from django.views.generic.base import View, TemplateView
from planner import services
from planner.forms import ... |
from typing import List
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
hasset = set()
A.sort()
for i in A:
hasset.add(i)
n = len(A)
if n == 0:
return 0
all = []
for i in range(1, n):
if A[i] == A[i... |
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.externals.six import StringIO
import pydotplus
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
iris = load_iris()
#print iris.feature_names
#print iris.target_names
#for i in ran... |
from typing import List, Dict, Union
import pandas as pd
import itertools
from autumn.core.inputs import get_population_by_agegroup
from autumn.core.utils.utils import weighted_average
def get_relevant_indices(
standard_breaks: List[int],
model_groups: List[str],
) -> Dict[str, List[int]]:
"""
Find t... |
import sys
from rtruffle.source_section import SourceSection
if sys.version_info.major > 2:
from rtruffle.base_node_3 import BaseNode
else:
from rtruffle.base_node_2 import BaseNode
class Node(BaseNode):
def __init__(self, source_section=None):
assert source_section is None or isinstance(source_... |
#!/usr/bin/python3
"""2-is_same_class.py"""
def is_same_class(obj, a_class):
"""tests whether an object is an instance of a specified class"""
if type(obj) == a_class:
return True
return False
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2013 R.F. Smith <rsmith@xs4all.nl>. All rights reserved.
# $Date: 2015-04-27 18:04:10 +0200 $
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redist... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# class LedIndicator(QtGui.QWidget):
# def __init__(self, status):
from PyQt4 import QtCore, QtGui
import PyTango
import ui_control
import setting
import json
import time
import datetime
import os
from threading import Thread, Timer
server_name = setting.server_name
j... |
# -*- coding: utf8 -*-
print('hello world!')
print("世界,好!")
input("Press enter key to close this window") |
# Generated by Django 3.1.5 on 2021-03-16 09:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0021_auto_20210316_1504'),
]
operations = [
migrations.AddField(
model_name='profile',
name='lat',
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
t=int(input())
for i in range(t):
n=int(input())
while n%2==0:
n//=2
print("YES" if n!=1 else "NO")
|
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView, LogoutView
from django.views.generic import FormView
from .forms import LoginForm
from app.forms import UserChangeForm
from django.urls import reverse_lazy
from django.shortcuts import render, get_object_or_404
fr... |
inp=raw_input("enter correct filename")
inp2=raw_input("enter parser o/p")
f=open(inp)
a=f.readlines()
f.close()
f=open(inp2)
b=f.readlines()
f.close()
x=[]
for i in range(0,50):
x.append(0)
y=[]
for i in range(0,50):
y.append(0)
countw=0
startsentence = 0
wrong=0
assert (len(a)==len(b))
for i in range(len(a))... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.10.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # ... |
print("this is using python")
print(1 + 2)
print("the end", "or is it", "keep watching", 3)
|
import twl
import setup
print(setup.init_board())
# 100 letters total
# 7 letters per player to start
|
from andrimne.common import run_shell_command
import andrimne.config as config
def run():
flags = config.read_or_default('maven_flags', '')
run_shell_command('mvn {} clean install'.format(flags), charset='latin-1')
|
n = int(input("Enter the number of queens"))
b = [[0]*n for _ in range(n)]
def att(i, j):
for k in range(0,n):
if b[i][k]==1 or b[k][j]==1:
return True
for k in range(0,n):
for z in range(0,n):
if (k+z==i+j) or (k-z==i-j):
while(b[k]... |
from mlpnn.Structure.Neuron import Neuron
class NeuronFactory(object):
@staticmethod
def create(id):
return Neuron(id)
|
n = int(input())
a = list(map(int, input().split()))
M = 1000000007
def mod(a, b):
return (a % b + b) % b
def gcd(a ,b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return a // gcd(a,b) * b
def extGCD(a,b):
if b==0:
return a,1,0
d, y, x = extGCD(b, a%b)
y -... |
#Se debe ingresar la ubicación del archivo .bvh a importar.
#EJEMPLO: blender --background ARCHIVO.blend --python import_bvh.py -- FILEPATH_BVH
import bpy
import sys#se agrega para poder manejar parametros de entrada, los mismos se deben colocar a continuación del nombre del script python y después de "-- ", observar... |
fruits = ['apples', 'oranges', 'pears', 'apricots']
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
i = 0
while i < len(fruits):
fruit = fruits[i]
print "fruit is: ", fruit
i = i + 1
|
def get_dp_index(*dps):
new_dps = dps[0]
for dp in dps[1:]:
new_dps.extend(reset_index(len(new_dps), dp))
return ','.join([str(i) for i in new_dps])
def reset_index(nxt_idx=0, dp_index=[]):
next_index = nxt_idx
new_indices = []
current_indices = [0]
for i in range(1, len(dp_inde... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Sequence
from sqlalchemy import Table, Column, String, Integer, MetaData
from sqlalchemy.orm import mapper
url = "oracle+zxjdbc://user:pass@example.com:1521/orc4"
engine = create_engine(url, echo=True)
metadata = Me... |
import sys,re,string
path_to_stop_words = '../BasicData/stop_words.txt'
# path_to_text = './BasicData/Pride_And_Prejudice.txt'
def extract_words(path_to_file):
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
stop_words = set(open(path_to_stop_words).read().split(','))
return [w for w in... |
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^(\d+)/(\d+)$', views.show,name='show'),
url(r'^index2$',views.index2,name='index2'),
url(r'^user1',views.user1,name='user1'),
url(r'^user2',views.user2,name='user2'),
url(r'^htmlTest$', view... |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import os,time
import random
import guesssp
import Single
import dataarrange
import arrangement
import pred
fro... |
# # 프로젝트 1. 영화 리뷰 감정 분석
# **RNN 을 이용해 IMDB 데이터를 가지고 텍스트 감정분석을 해 봅시다.**
# 이번 책에서 처음으로 접하는 텍스트 형태의 데이터셋인 IMDB 데이터셋은 50,000건의 영화 리뷰로 이루어져 있습니다.
# 각 리뷰는 다수의 영어 문장들로 이루어져 있으며,
# 평점이 7점 이상의 긍정적인 영화 리뷰는 2로, 평점이 4점 이하인 부정적인 영화 리뷰는 1로 레이블링 되어 있습니다.
# 영화 리뷰 텍스트를 RNN 에 입력시켜 영화평의 전체 내용을 압축하고,
# 이렇게 압축된 리뷰가 긍정적인지 부정적인지 판단해주는 간단한... |
# Show statistic results (average, standard deviation, min & max)
import numpy as np
import math
# Calculate the average
def calAve(csvPath):
y = np.loadtxt(csvPath, delimiter='\n', unpack=True)
return sum(y)/len(y)
# Calculate the standard deviation
def calmsd(csvPath):
y = np.loadtxt(csvPath, delimiter=... |
#this is a project made at hackriddle 2016
#it is a "smart" toaster using clarifai, simplecv, and twilio
#by: Jessie Pullaro, Frank Calas and Kyle Spomer
from clarifai import rest
from clarifai.rest import ClarifaiApp
import json
#pulls the api keys from keys.py
app = ClarifaiApp("nnDJHbfgjR6qFYT_zv9RVoMBmR9-vFnv... |
from itertools import accumulate
N, M = map( int, input().split())
l = 1
r = N
for _ in range(M):
a, b = map( int, input().split())
if l <= a:
l = a
if b <= r:
r = b
if r - l >= 0:
print(r-l+1)
else:
print(0)
|
import random
#keep imports to the top
#imports a random number generator
y0 = 50
x0 = 50
y1 = 50
x1 = 50
#variable set up (may as well keep this together)
#random.random generates a random number between 0 to 1
if random.random() < 0.5:
y0 += 1
else:
y0 -= 1
#control flows saying if the random number is belo... |
"""
textui: Python text UI, a text based user interface package
A note on error handling: many of the functions in this packages throw exceptions if
your input (not the user input) is of the wrong type. You may not wish such errors to
occur when the program is in use by the end user. There are several ways to handle t... |
from django.forms import (CharField, EmailField, Form, PasswordInput)
class AddUserForm(Form):
username = CharField(label='Username', strip=True)
password = CharField(label='Password', widget=PasswordInput)
first_name = CharField(label='First Name', strip=True, required=False)
last_name = CharField(la... |
#-*-coding:utf-8-*-
import cv2
import os
import glob
import numpy as np
from PIL import Image, ImageDraw
#因为工程化生成的cpr斑块mask仅是在cpr上的斑块轮廓,需要将斑块轮廓转化为斑块mask,所有这里要先提取出cpr并生成只有cpr斑块的轮廓,之后对cpr斑块轮廓生成斑块mask。
tar_dir = '/mnt/DrwiseDataNFS/drwise_runtime_env/data1/inputdata/' #'/mnt/users/ffr_10datasets/ffr_cpr_mask/'#diagnose_... |
# @Time : 2018/3/11 12:56
# @Author : Jing Xu
import threading
import requests
from bs4 import BeautifulSoup
from queue import Queue
class MyThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while not self.queue.empty():
url = self.qu... |
# Generated by Django 3.0.7 on 2020-11-16 08:23
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('cl_table', '0084_auto_20201116_0822'),
]
operations = [
migrations.AddField(
model_name='poshaud',
... |
t = int(input())
for _ in range(t):
n = int(input())
l = list(map(int,input().split()))
k = int(input())
print(len(set(l[k:]))) |
# Problem Set 1
# Tomas Oliveira
# Exercise 1
numtest = 3 # Number to be tested if prime
numprime = 0 # Number of primes
divisor = 2 # Divisor
while numprime < 999:
while numtest==numtest:
if ( numtest % divisor == 0) and divisor != numtest: # if this condition is true the number is divisible by a number other t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 08:58:52 2018
@author: nick
"""
import numpy as np
def q1(x):
z = x[:, :2]
y = x[:, :2].dot([[3, 0], [0, 2]]);
print(z)
print(y)
if __name__ == '__main__':
x = np.array([[1, 2, 3, 4],
[5, 6, 7,... |
# Generated by Django 3.2.4 on 2021-08-04 07:19
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import requests
"""
This script is for filtering testing
ATOM-based text is shown with the specific collection
"""
#For this test, please follow the rule shown blew, which is strictly stick to the assignment specification
#e.g:
#Type1: http://127.0.0.1:5000/areas/filter?lgaName eq Sydney or lgaName eq ... |
a = input('First number: ')
b = input('Second number: ')
som = int(a) + int(b)
print('Som entry {} and {} is {}'.format(a, b, som)) |
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
possible input situations:
(1) Whitespaces at the front
(2) Take the first non-whitespace character. Plus or minus
(3) Size limitation and error handling (return 0 if non convertible... |
from nltk.tokenize import sent_tokenize
from image_search import ImageSearch, DisplayImage
import yake
from datetime import datetime, timedelta
from time import sleep
import pdb
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
from text_speech import Audio
FILE_NAME = "doc.txt"
class StoryTe... |
import uuid
from src.common.database import Database
from src.common.utils import Utils
import src.models.users.errors as UserErrors
import src.models.users.constants as UserConstants
from src.models.sked.sked import Sked
class User(object):
def __init__(self, email, password, name, _id=None):
self.name =... |
import os
import json
from flask import Flask, redirect, request, Response
app = Flask(__name__)
@app.route('/')
def home():
return "HealthyPay"
@app.route('/payment', methods = ['POST', 'GET'])
def payment():
if request.method == 'POST':
username = request.form['username']
password = reque... |
# file pygrep.py
from pathlib import Path
import re
import argparse
# features
# highlight match
# case in/sensitive option
# recursive option
# only display file names
# display line numbers
# ignore paths in file/.gitignore
def format_green(str):
"""
Render a string in the color green in the terminal.
... |
from odoo import api, fields, models, _
class saleOrder(models.Model):
_inherit = "sale.order"
order_line = fields.One2many('sale.order.line', 'order_id', string='Order Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True)
product_uom_qty = field... |
#!/usr/bin/python2
import os
import gettext
import sys
sys.path.append('/usr/lib/linuxmint/common')
import additionalfiles
DOMAIN = "mint-common"
PATH = "/usr/share/linuxmint/locale"
prefix = "[Nemo Action]\n"
suffix = """Exec=thunderbird -compose to=,\"attachment='%F'\"
Icon-Name=mail-attachment
Selection=NotNone
... |
import string
from words import choose_word
from images import IMAGES
'''
Important instruction
* function and variable name snake_case -> is_prime
* contant variable upper case PI
'''
def display_image(image_index):
return IMAGES[image_index]
def is_word_guessed(secret_word, letters_guessed):
... |
from django.urls import path
from . import views
app_name = 'game'
urlpatterns = [
path('game_create/', views.GameCreateView.as_view(),
name='game-create'),
path('game_list/', views.GameListView.as_view(),
name='game-list'),
path('game_details/<game_id>', views.GameDetails.as_view(),
... |
from Cut import *
class RunCut:
def __init__(self):
pass
def inputOutTxt(self, inputfile, outputfile):
cut = Cut(3)
inf = open(inputfile, 'r', encoding='UTF-8')
outf = open(outputfile, 'w', encoding='UTF-8')
for row in inf:
row = row.strip('\n')
... |
# © 2018 Danimar Ribeiro, Trustcode
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from datetime import datetime
from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError
class PurchaseMulticompany(models.Model):
_name = "... |
from sys import maxsize
class Contact:
def __init__(self, fName = None, mName = None, lName = None, nick = None, title = None, company = None,
address = None, mobile = None, home_phone = None, work_phone = None, fax = None,
email = None, email2 = None, email3 = None, homePage = No... |
#!/usr/bin/python3
#\file lr_sch_1.py
#\brief Test learning schedulers of PyTorch.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Sep.30, 2021
import numpy as np
import torch
import matplotlib.pyplot as plt
import time
import sys
if __name__=='__main__':
log_file_name= sys.argv[1]
wit... |
# Find the smalles missing elemenet from an array
def find_smallest_missing(arr):
low = 0
high = len(arr) - 1
# handle our edge case where 0 is the smallest missing
if arr[0] != 0:
return 0
# handle edge case where no element is missing
if arr[high] == high:
return arr[-1] +... |
from selenium.webdriver.common.by import By
from .abstract import PageElement
from .abstract import PageElements
from .abstract import PageObject
class AllPostsPage(PageObject):
posts = PageElements(By.CSS_SELECTOR, "article")
content = PageElement(By.CSS_SELECTOR, "textarea#id_content")
tell = PageEleme... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#
# $BeginLicense$
#
# (C) 2015-2021 by Camiel Bouchier (camiel@bouchier.be)
#
# This file is part of cb_find_duplicates.
# All rights reserved.
# You ... |
# https://github.com/alexwaweru/kickstart_practice_2018/blob/master/kickstart_practice_round_2018/GBus_count/solution.py
import numpy as np
output = open("./out_small_2.txt", 'w+')
with open('A-small-practice.in') as fp:
T = int(fp.readline())
cur_rd = 1
while cur_rd <= T:
key = 'Case #'+str(int(cu... |
import sys
import utime
import urandom
import machine
from machine import Pin, Signal, ADC, I2C, PWM
import driver_i2clcd1602
# VARIABLE
mode=0
userpassword=[0,0,0,0]
status="opened"
checkpass=0
wrongpass=0
saveinput=[0,0,0,0]
# GPIO DEFINE
pin_servo=PWM(Pin(4, Pin.OUT), freq=50, duty=75)
pin_button01=Signal(Pin(27, ... |
from django import forms
class SearchForm(forms.Form):
search_input = forms.CharField(required=True)
|
import os
import cv2
# import mmcv
import torch
import random
import argparse
import mot.utils
import mot.detect
import mot.encode
import mot.metric
import mot.predict
import numpy as np
import torchvision
import mot.associate
from third_party.TSM import MobileNetV2, GroupNormalize, ToTorchFormatTensor
from mot.tracker... |
# Copyright (c) 2013, DBF and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
def execute(filters=None):
report = filters.get("report")
if report == "Room Type Occupancy":
columns, data = get_room_type_occupancy(filters)
if repor... |
# ex14: Prompting and passing
from sys import argv
script, user_name, location = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "You're running me from %s." % location
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
prin... |
comida = ""
if (comida == "omelete"): print("Omelete se faz com ovos!")
elif (comida == "bolo"): print("Bolo precisa de leite!")
elif (comida == "sanduíche"): print("Sanduíche precisa de hamburguer!")
else: print("Não sei fazer essa comida!")
|
import pandas as pd
from sklearn import metrics
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.preprocessing import LabelEncoder
df_train = pd.read_csv("data/training.csv")
positive_string = ""
negative_string = "... |
# -*- coding: utf-8 -*-
import sys, traceback
import requests
import os
from datetime import datetime
import time
import json
import collections
import logging
from bs4 import BeautifulSoup
#
import argparse
import progressbar as pb
#
import settings
import grobidAPI
import tei2dict
import csv
import utils
logger = lo... |
#! /usr/bin/env python
import urllib2
from bs4 import BeautifulSoup
#____________________________________________________________________________||
topNewsDict = {'id':'top-news','class':'top-news'}
firstColDict = {'class': 'first-column-region region'}
headDict = {'class': 'story-heading'}
summaryDict = {'class': '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
验证用户登录
"""
from contextlib import contextmanager
from typing import Dict, Iterator, Optional
from flask import current_app
from flask_jwt_extended import create_access_token, create_refresh_token
from flask_smorest import abort
from loguru import logger
from werkzeug.e... |
import django.dispatch
init_service = django.dispatch.Signal()
class ServiceContainerInit:
def notify_listeners(self):
init_service.send(sender=self.__class__)
|
#!/usr/bin/python
from BeautifulSoup import BeautifulSoup, Comment
try:
file = open('input.html')
except IOError:
print('Could not load source file. You must have a file named input.html in the script folder.')
exit()
input = file.read()
soup = BeautifulSoup(input)
#first remove comments - NB this s... |
#!/usr/bin/env python3
"""
test for the psurl module.
"""
import unittest
from base_test import PschedTestBase
from pscheduler.psurl import *
class TestPsurl(PschedTestBase):
"""
URL tests.
"""
def test_url_bad(self):
"""IP addr tests"""
# Missing scheme
no_scheme = "no-s... |
# Generated by Django 3.0.8 on 2020-07-17 14:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0004_auto_20200717_2200'),
]
operations = [
migrations.RemoveField(
model_name='reviews',
name='GuideID',
... |
from onegov.activity.matching.score import PreferAdminChildren
from onegov.activity.matching.score import PreferOrganiserChildren
from onegov.activity.matching.score import PreferGroups
from onegov.activity.matching.score import Scoring
from onegov.feriennet import _
from onegov.form import Form
from wtforms.fields imp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-16 02:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0002_auto_20161115_2348'),
]
operations = [
migrations.AddField(
... |
import chainer
import chainer.functions as F
from chainer import Variable
class AdversarialUpdater(chainer.training.StandardUpdater):
def __init__(self, *args, **kwargs):
self.gen, self.dis = kwargs.pop('models')
super().__init__(*args, **kwargs)
def loss_dis(self, y, y_dash):
loss1 ... |
import tkinter
import tkinter as tk
from tkinter import Label,Entry,Button,NORMAL,END
from MEETINGpack.Model import FormValues
from tkinter import messagebox
from tkinter.ttk import *
class MyForm:
dt1=""
pur1=""
des1=""
root=""
def clear(self):
self.dt1.delete(0,tk.END)
... |
from xml.dom.minidom import Element
from log_4_j.location_info import LocationInfo
class DomLocationInfo(LocationInfo):
def __init__(self, dom_element: Element) -> None:
LocationInfo.__init__(
self,
dom_element.getAttribute("class"),
dom_element.getAttribute... |
def calseq(infile,outfile1,outfile2):
from fasta import fasta_iter
import gzip
fasta = {}
for ID,seq in fasta_iter(infile):
if seq in fasta:
fasta[seq][1] += 1
else:
fasta[seq] = [ID, 1]
out1 = gzip.open(outfile1, "wt", compresslevel=1)
out2 = gzip.open(o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 24 09:31:02 2021
@author: georgengin
"""
import numpy as np
import os
import matplotlib.pyplot as plt
import random
import tensorflow as tf
from pathlib import Path
from tensorflow.keras import applications
from tensorflow.keras import layers
from t... |
class Solution:
def maxDepth(self, root):
if not root: return 0
leftdepth = self.maxDepth(root.left)
rightdepth = self.maxDepth(root.right)
return leftdepth + 1 if leftdepth > rightdepth else rightdepth + 1 |
class Solution:
def prisonAfterNDays(self, cells, N):
"""
:type cells: List[int]
:type N: int
:rtype: List[int]
"""
hist = {}
for i in range(N):
nc = [0] * len(cells)
for j in range(1, len(cells)-1):
if (cells[j-1] + cel... |
from osgeo import gdal
from skimage.morphology import erosion
from skimage.morphology import black_tophat, skeletonize, convex_hull_image
from skimage.morphology import disk
#import tifffile as tiff
import sys
from scipy import ndimage
import numpy as np
#filename = sys.argv[1]
#dst_filename=sys.argv[2]
filename="rast... |
from .src import main_gui
|
class BMW:
def __int__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start(self):
print("starting the car")
def stop(self):
print("stopping the car")
class ThreeSeries(BMW):
def __int__(self, cruiseControlEnabled, make, mod... |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.http import JsonResponse
import json
from . import models
import face_recognition
import base64
from io import ... |
import numpy as np
import matplotlib.pyplot as p
x=np.array([[1.0,100.0,2.0],[1.0,120.0,3.0],[1.0,150.0,3.0],[1.0,170.0,4.0],[1.0,150.0,4.0],[1.0,190.0,6.0]])
y=np.array([50.0,60.0,80.0,110.0,85.0,150.0])
#y=1000*y
n=6
##x[:,1]=(x[:,1]-np.mean(x[:,1]))
##x[:,2]=(x[:,2]-np.mean(x[:,2]))
##y=(y-np.mean(y))
theta=np.arra... |
# Generated by Django 2.0.5 on 2018-05-29 08:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('whatsapp', '0004_log_broadcasted'),
]
operations = [
migrations.AlterField(
model_name='log',
... |
#!/usr/local/bin/python3
# Copyright: (c) 2018, Shihao Li <shli@thoughtworks.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = '''
---
module: welcome
author: Shihao Li <shli@thoughtworks.com>
short_description: Print welcome message.
'''
EXAMPLES = '... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
def solution(head1:Node, head2:Node):
length1 = get_list_length(head1)
length2 = get_list_length(head2)
if length1>length2:
node1 = head1
node2 = head2
diff = length1-length2
else:
... |
from vectors import v
class AbstractComponent(object):
""" A component describes one facet of one entity in a game world. """
def __init__(self, owner=None):
self.owner = owner
class Lifecycle(AbstractComponent):
"""Every object should have a Lifecycle. It basically centralizes access to the containing screen as... |
from cosmo_utils.pyncdf import getfobj_ncdf_timeseries
radarpref = '/project/meteo/w2w/A6/radolan/netcdf_cosmo_de/raa01-rw_10000-'
radarsufx = '-dwd---bin.nc'
from datetime import timedelta
from cosmo_utils.helpers import yyyymmddhh_strtotime
tstart = '2016052601'
tend = '2016061000'
dtradar = timedelta(minutes = 10)
... |
from pwn import *
import sys
#import kmpwn
sys.path.append('/home/vagrant/kmpwn')
from kmpwn import *
#fsb(width, offset, data, padding, roop)
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "./pwn1"
HOST = "79gq4l5zpv1aogjgw6yhhymi4.ctf.p0wnhub.com"
PORT = 11337
if len(sys.argv) > ... |
"""Advent of Code 2019 Day 10 - Monitoring Station."""
from math import atan2, degrees, pi
with open("input.txt", "r") as f:
space = [list(row) for row in f.read().strip().split('\n')]
space_dict = {}
y = 0
for row in space:
x = 0
for col in row:
value = space[y][x]
if value == '#':
... |
# Generated by Django 2.0.1 on 2018-01-09 12:10
from django.db import migrations, models
import django.db.models.deletion
import heroku_connect.db.models.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name=... |
import os
import sys
import logging
import boto3
import urllib
import traceback
import time
import json
import gzip
import datetime
from botocore.exceptions import ClientError
from io import BytesIO, StringIO
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
from da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.