text stringlengths 38 1.54M |
|---|
from django.db.models import Count
from rest_framework.permissions import IsAuthenticated
from drinks.models import Ingredient
from drinks.serializers import IngredientSerializer
from drinks.views.base import LazyViewSet
class IngredientViewSet(LazyViewSet):
audit_field = 'created'
http_method_names = ['get'... |
from django.contrib import admin
from forum.models import Publication, Answer
admin.site.register(Publication)
admin.site.register(Answer) |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 23:51:34 2020
@author: Yu Zhe
"""
from forecast_recommender import forecast_recommender
import pandas as pd
"""
Evaluation metric for learning model
1. Mean absolute error (MAE)
2. Mean squared error (MSE)
3. Root Mean Square Error (RMSE)
4. Mean absolute percentage e... |
from exceptions.exceptions import UninitializedValueAccess, OutOfBoundsAccess
class LanceScriptScalarVariable:
def __init__(self, name, type, value=None):
self.name = name
self.type = type
self.value = value
def get(self):
if self.value is None:
raise Uninitialized... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.addons.base.res.res_request import referenceable_models
from datetime import datetime
class PlanillaAfiliacionLineWizard(models.TransientModel):
_name="planilla.afiliacion.line.wizard"
#usados pa... |
## ui
# pyside2-uic signin.ui > ui_signin.py
scroll_bar = """
QScrollBar:vertical {
width:10px;
background-color:rgba(0,0,0,0%);
padding-top:10px;
padding-bottom:10px;
}
QScrollBar:horizontal {
height:10px;
background-color:rgba(0,0,0,0%);
padding-left:10px; padding... |
"""job_bilby Views for the Jobs application
Defines all views; scripts run at each URL.
This file belongs to the back end source code for team 'job-bilby' for the
University of Melbourne subject SWEN90014 Masters Software Engineering Project.
The project is a mobile-first web application for sharing tasks.
The back-e... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
return self.tree_range_sum(root, L, R, 0)
def tree_range_sum(self, node, left, right, total):
if nod... |
settings = {'USERNAME': 'afouch',
'PASSWORD': 'B.ailey123!',
# Example URL
# Find on your school's Banner Web page
'BASE_URL': 'https://ssb.ramapo.edu/pls/RCNJ/',
# Spring semester
'SEMESTER': '201740',
# List of classes
'CR... |
from nltk.compat import python_2_unicode_compatible
printed = False
ARC_PARENT = 0
ARC_REL = 1
ARC_CHILD = 2
@python_2_unicode_compatible
class FeatureExtractor(object):
@staticmethod
def _check_informative(feat, underscore_is_informative=False):
"""
Check whether a feature is informative
... |
import argparse
import os
import logging
from tqdm import tqdm
from typing import Callable
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.optim import Adam, Optimizer
from torchvision import transforms
from torchvision.utils impo... |
from threading import Thread
def one(): import video_text_detection_edited_v1.py
def two(): import text_to_voice.py
Thread(target=one).start()
Thread(target=two).start()
|
import telebot
import requests
import sys
import traceback
from telebot.types import Message
from bs4 import BeautifulSoup
from variables import TOKEN
bot = telebot.TeleBot(TOKEN)
def get_urban_meaning(word):
r = requests.get('https://www.urbandictionary.com/define.php?term={}'.format(word))
soup = BeautifulS... |
import uasyncio as asyncio
import machine
from pn532 import PN532Uart
# This example initializes the PN532 and then enters a forever loop
# waiting for rfid tags to be read.
#
# Pinout:
# esp32 tx = 22 = pn532 rx
# esp32 rx = 23 = pn532 tx
#
# esp32 OUT = 21 = buzzer (or led)
#
# Enable debug printing ... |
#coding:utf-8
def test(s1,s2):
alist = list(s2)
pos1 = 0
ok = True
while pos1<len(s1) and ok:
pos2 = 0
found = False
while pos2 <len(alist) and not found:
if s1[pos1] == alist[pos2]:
found = True
else:
pos2 = pos2+1
if found:
alist[pos2] = None
pos1 = pos1+1
else:
ok = False
... |
import argparse
import json
import random
from enum import IntEnum
from pathlib import Path
from subprocess import run
import indexed_dataset
import numpy as np
import torch
from model_training.custom_datasets.formatting import DatasetEntryLm, DatasetEntrySft, Role
from model_training.utils.utils import _strtobool, ge... |
from __future__ import absolute_import
from rest_framework import permissions
from rest_framework.serializers import ModelSerializer, ValidationError, \
Serializer, CurrentUserDefault
from rest_framework.viewsets import ModelViewSet
from fcm_django.models import FCMDevice
from django import VERSION as DJ_VERS... |
#! /usr/bin/env python3
import os
import requests
filepath = '/data/feedback'
filenames = os.listdir(filepath)
post_dict = {}
for file in filenames:
with open(filepath + '/' + file) as review:
post_dict["title"] = review.readline().rstrip()
post_dict["name"] = review.readline().rstrip()
post_dict["date"] = re... |
# _*_ coding: utf_8 _*_
"""
Created on 11/30/2016
@author: Eddie
"""
from pyshgp.utils import merge_sets
from pyshgp.push.interpreter import PushInterpreter
from pyshgp.push.registered_instructions import get_instructions_by_pysh_type
from pyshgp.gp.evolvers import SimplePushGPEvolver
from pyshgp.gp.variation import (... |
# %%
import seaborn as sns
tips = sns.load_dataset('tips')
flights = sns.load_dataset('flights')
tips.head()
flights.head()
tc = tips.corr()
# sns.heatmap(tc, annot=True, cmap='coolwarm')
fp = flights.pivot_table(index='month', columns='year', values='passengers')
# sns.heatmap(fp, cmap='coolwarm', linecolor='blac... |
#! /usr/bin/env python
import lineups
import datetime
retVal = lineups.get_lineups(datetime.datetime.now(), "Orioles")
print(retVal)
|
from die import Die
from actor import Player, Monster
class Parser():
@staticmethod
def parseRoll(die_str):
die_list = die_str.split('+')
dice = []
singles = []
for die in die_list:
die = [int(x) for x in die.split('d')]
if len(die) == 1:
... |
#!/usr/bin/python
from gen import Gen, AnnularCompGen, EmbeddedCompGen
from serp_concept import CylSurf, ConeSurf, PzSurf, CrossSurf, PadSurf
from comparable_object import CmpObj
from types import *
from mat import Mat
from numbers import Number
class Comp(CmpObj):
'''
a Comp is a component in th... |
import torch.nn as nn
import torch
import numpy as np
from quantizer_torch import quantize
class ResidualBlock(nn.Module):
def __init__(self):
super(ResidualBlock, self).__init__()
''' declare layers used in this network'''
# first block
self.conv1 = nn.Conv2d(128, 128, kernel_si... |
import json
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
# spacy for lemmatization
import spacy
from lda import guidedlda
# Enable logging for gensim
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)
import n... |
#!/usr/bin/env python
'''
Script to interact with Spark API sending information from our
temperature sensor to a spark room.
Updates needed:
1. Search for Sensor by ID, then pull Temp
2. Check for REST state errors and report if device is unreachable
3. Report if Spark becomes unreachable
'''
__version__ = ... |
import sys
import math
def solve():
try:
str1=input()
except:
pass
count=0
i=0
len1=len(str1)-1
while (i<len1):
# print(str1[i])
if(str1[i]!=str1[i+1]):
count+=1
i+=2
else:
i+=1
# print("I, Count = "+str(i)+","+str(count))
print(count)
try:
for tc in range(int(input())):
solve()... |
from Domain_Name import *
from IP_Address import *
from Nmap import *
from Robots import *
from WebScanner import *
from WhoIs import *
ROOT_DIR='companies/'
Directory(ROOT_DIR)
def gather_info(name,url):
domain_name=Get_Domain(url)
ip_addres=get_ipAddress(domain_name)
nmap=Nmap('-F',ip_a... |
import abc
import pandas as pd
from fda.util.exceptions import DataLoadingException
class DatasetReader(abc.ABC):
def __init__(self, fpath):
self._fpath = fpath
def read(self):
df = self._read(self._fpath)
if not isinstance(df.index, pd.DatetimeIndex):
raise D... |
import logging.config
config={
'version':1,
'formatters':{
'simple':{
'format':'%(asctime)s-%(name)s-%(levelname)s-%(message)s'
}
},
'handlers':{
'console':{
'class':'logging.StreamHandler',
'level':'DEBUG',
'formatter':'simple'
... |
import torch
import torch.nn as nn
class SubtextClassifier(nn.Module):
def __init__(self, window_size):
super(SubtextClassifier, self).__init__()
if window_size == 1:
conv_kernel_size = 2
linear_channel = 1
else:
conv_kernel_size = window_s... |
import pytest
import datetime
from pandas import NaT, Timestamp, Timedelta
from ..conftest import (
FauxJIRA as JIRA,
FauxIssue as Issue,
FauxChange as Change,
FauxFieldValue as Value,
)
from ..querymanager import QueryManager
from .cycletime import CycleTimeCalculator
@pytest.fixture
def jira(custo... |
from setuptools import setup, find_packages
import os
_dir_ = os.path.dirname(__file__)
def long_description():
"""Returns the value of README.rst"""
with open(os.path.join(_dir_, 'README.rst')) as f:
return f.read()
setup(name='django-multisite',
version='0.3.1',
description='Serve mul... |
from .. import AgentsHelper
class MinmaxAgent:
def __init__(self, color):
self.color = color
def deploy(self, map, armies):
children = AgentsHelper.giveBirth(map, self.color, armies) #Generate next level of states
for child in children:
output = self.minmax(child["state"], ... |
# -*- coding: utf-8 -*-
import scrapy
from finance import items,select_url
class FinanceSpiderSpider(scrapy.Spider):
name = 'finance_spider'
allowed_domains = ['sina.com']
start_urls = ['http://finance.sina.com.cn/']
results = select_url.serch_url()
urls = []
def parse(self, response):
... |
from flask import Flask, jsonify
from controller import Controller
app = Flask(__name__)
app.secret_key = 'mysecretkey'
@app.route('/test-tienda-nube', methods=['GET'])
def test_tienda_nube():
try:
return jsonify(Controller.get_shipments())
except Exception as e:
print('Oops! An err... |
n, t = map(int, input().split())
A = [int(input()) for _ in range(n)]
tmp = A[0] + t
cnt = t
for a in A[1:]:
if a > tmp:
cnt += t
else:
cnt += a + t - tmp
tmp = a + t
print(cnt) |
import numpy as np
import random
from tbempy.TwoD import *
from laplace import *
def log_u(x):
return np.log(np.sqrt(x[0] * x[0] + x[1] * x[1]))
def theta_u(x):
return np.arctan2(x[1], x[0])
def make_log_dudn(center):
def log_dudn(x):
loc = np.array([x[0], x[1]])
dist_to_origin2 = x[0] * ... |
from struct import unpack, pack
import sys
def debug(*args, **kwargs):
if '--debug' in sys.argv:
print(*args, **kwargs)
# https://www.adobe.com/content/dam/acom/en/devnet/pdf/amf0-file-format-specification.pdf
TYPE_NUMBER = 0
TYPE_BOOLEAN = 1
TYPE_STRING = 2
TYPE_OBJECT = 3
# UNUSED = 4
TYPE... |
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class User_info(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=255)
userName = models.CharField(max_length=255)
email = models.CharField(... |
import re
import time
from concurrent import futures
import requests
import pymongo
from lxml import html
from ganji_58.decorators import time_elapse, log
class WubaRecruit(object):
def __init__(self, base_url):
self.base_url = base_url
self.db = pymongo.MongoClient(host='127.0.0.1', port=27017)['... |
# Generated by Django 3.0.5 on 2020-04-14 07:42
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
# Description: Label + Button + Entry + xử lý USER && PASSWORD
from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
import cv2
import time
import shutil
import os
def btn_train_click():
file=open("aa.txt", "a") #Mở File
file.write ("abcd\n") #Ghi vào file
file.close(... |
import os
import re
import csv
import time
import requests
import pandas as pd
from lxml import etree
from get_list_data import headers
def read_csv(file_name):
position_urls = []
with open(file_name, 'r', newline='') as file_test:
reader = csv.reader(file_test)
i = 0
for row in reader... |
from __future__ import with_statement, print_function, division, absolute_import
import sys, os
sys.path.append(os.path.dirname(__file__))
from utils import make_samples_linear |
from abc import ABC, abstractmethod
from .alu_instructions import AluInstruction
class BitwiseInstruction(AluInstruction, ABC):
def __init__(self, dst_reg, op1, op2):
super().__init__(dst_reg)
self.OP1 = op1
self.OP2 = op2
@property
def operands_str(self):
return "{}, {},... |
# -*- coding: utf-8 -*-
# @Time : 2019/11/25 16:09
# @Author : ZarinMaster
# @Site :
# @File : net.py
# @Software: PyCharm
from email.header import Header
from email.mime.text import MIMEText
from smtplib import SMTP
def main():
# 请自行修改下面的邮件发送者和接收者
sender = 'grant_reg@163.com'
receivers = 'dugang106@163... |
read_int = lambda: int(input())
read_ints = lambda: list(map(int, input().split()))
read_tuple = lambda: tuple(map(int, input().split()))
def solve():
pass
def main():
T = read_int()
for i in range(T):
result = solve()
print(result, end='\n' if i != T - 1 else '')
if __name__ == '__mai... |
import os
class Experiment():
def __init__(self):
self.nas_main_dir = os.environ['CG_NAS_MAIN']
self.nas_patient_dir = os.environ['CG_NAS_PATIENT']
self.local_dir = os.environ['CG_LOCAL']
self.num_partitions = int(os.environ['CG_NUM_PARTITIONS']) |
import sys
from pathlib import Path
home = str(Path.home())
path = home+'/Platform/'
sys.path.insert (0, path)
from queue_req_resp import *
from app import app
import pika
import json
import pandas as pd
from flask import Flask,render_template,request,redirect
import numpy as np
from googleapiclient.discovery import b... |
from unittest import TestCase
from unittest_data_provider import data_provider
class TestSmallestMissing(TestCase):
conditions = lambda: (
({'arr': [0, 1, 2, 6, 9], 'n': 5, 'm': 10}, {'result' : 3}),
({'arr': [0, 1, 2, 3], 'n': 4, 'm': 5}, {'result' : 4}),
({'arr': [0, 1, 2, 3, 4, 5, 6, 7,... |
START_TOKEN_IDX = 2
END_TOKEN_IDX = 3
words = open('vocabulary.txt').read().split()
vocab = {}
for i, word in enumerate(words):
vocab[i] = word
vocab[word] = i
VOCABULARY_SIZE = len(words)
UNKNOWN_IDX = vocab['thing']
def words(indices):
return ' '.join(vocab[i] for i in indices)
def indices(text):
... |
numeros1 = [1,33,10,65,4]
numeros2 = [3,15,63,9,13]
arreglo_1 = numeros1 + numeros2
arreglo_1.sort()
def mayores (arreglo_1):
numero_mayor= arreglo_1[8]*arreglo_1[9]
print (f'Al multiplicar los numeros mayores de la lista sera: {numero_mayor}')
mayores(arreglo_1)
|
import numpy as np
from utils import *
# Function to get cosine similarity
# Arguments:
# a: A numpy vector of size (x, )
# b: A numpy vector of size (x, )
# Returns: sim (float)
# Where, sim (float) is the cosine similarity between vectors a and b. x is the size of the numpy vector.
def cosine_similarit... |
import numpy as np
edim = 16
arrange443 = np.array([0,16, 32,
1,17, 33,
2,18, 34,
3,19, 35,
4,20, 36,
5,21, 37,
6,22, 38,
7,23, 39,... |
import json
import logging
import qiniu
from django.contrib.auth.mixins import LoginRequiredMixin,PermissionRequiredMixin
from django.http import JsonResponse, Http404
from datetime import datetime
from django.contrib.auth.models import Group,Permission
from django.core.paginator import Paginator, EmptyPage
from djang... |
# INPUT NUMBER OF EVEN NUMBERS
n=int(input())
start=0
for i range(n):
print(start)
start+=2
|
import serial
import time
#ser = serial.Serial('COM8', 9600)
ser = serial.Serial('COM8', 9600, timeout=0, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
var1=''
var2=''
var3=''
var4=''
var5=''
while True:
count =0
nbytes = ser.inWaiting()
... |
from pytube import Playlist
def download_playlist(link):
playlist = Playlist(link)
for video in playlist.videos:
print("Downloading " + video.title)
mp4 = video.streams.filter(file_extension= "mp4").filter(res="720p")
mp4.first().download()
link = input("Enter the ... |
import numpy as np
import cudamat as cm
import pdb
class Layer_cuda():
'''
Class contains layers for building deep neural nets
'''
def __init__(self):
pass
def sigmoid(self, X):
'''
Performs sigmoid activation
'''
row,col= X.shape
x_exp = c... |
from find_prime_factorization import is_prime
from find_prime_factorization import prime_sieve
primes = prime_sieve(1000000, [])
truncatable_primes = []
def trunc_right(n):
return int(str(n)[:len(str(n))-1])
def trunc_left(n):
return int(str(n)[1:])
for i in primes[4:]:
setting = True
n = i
... |
# Course URL:
# https://deeplearningcourses.com/c/natural-language-processing-with-deep-learning-in-python
# https://udemy.com/natural-language-processing-with-deep-learning-in-python
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo ... |
# SVM = Support Vector Machine - Linear
# - Trovare la retta che massimizza la distanza tra 2 classi
# - Usa un sottoinsieme dei dati per definire la soluzione
# - Non è influenzato dagli outliers
# - Usa gli esempi "ambigui" per creare il modello -> definiscono i vettori di supporto
# https://towardsdatascience.c... |
import sys
sys.stdin = open('input.txt', 'r')
for n in range(10):
tc = input()
arr = [list(map(int, input().split())) for _ in range(100)]
arr2 = list(map(list, zip(*arr)))
res = []
d1, d2 = 0, 0 # 대각선 합
for i in range(100):
res.append(sum(arr[i]))
res.append(sum(arr2[i]))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-12-08 10:35:43
# @Author : cdl (1217096231@qq.com)
# @Link : https://github.com/cdlwhm1217096231/python3_spider
# @Version : $Id$
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
device = torch.device... |
import os
import shutil
import cv2
import xml.etree.ElementTree as ET
from tqdm import tqdm
if __name__ == "__main__":
""" Utils file to crop and split the openlogo dataset """
test_classes = [
"3m",
"abus",
"accenture",
"adidas",
"adidas1",
"adidas_text",
... |
#!/usr/bin/env python
"""
/***************************************************************************
-------------------
begin : 2016-11-12
git sha : $Format:%H$
copyright : (C) 2016 by Nejc Dougan
email ... |
#!/usr/bin/env python
from netutils_linux_monitoring.softnet_stat import SoftnetStatTop
if __name__ == '__main__':
SoftnetStatTop().main()
|
# Created by Krishnarjun Singh
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def aboutus(request):
return render(request, 'aboutus.html')
def analyzer(request):
# Main POST comand
pctect = request.POST.get('text', ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 20:37:34 2018
@author: acely
"""
import urllib2
import urllib
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf8')
html = urllib2.urlopen("https://dealer.autohome.com.cn/frame/spec/32014/110000/110100/0.html?isPage=1&source=www.baidu.... |
import inspect
import json
import unittest
import os
import sys
sys.path.insert(0, '..')
from lib import FileStatter
from lib import CSVparser
from lib import SchemaGenerator
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
testfile = os.path.join(current_dir, 'mockups', 'csv... |
# Generated by Django 3.1.7 on 2021-03-22 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("trackerapp", "0005_auto_20210322_1932"),
]
operations = [
migrations.RemoveField(
model_name="message",
name="title",
... |
//@version=4
strategy("Random Strategy with 3 TP levels and SL", overlay=true,max_bars_back = 50)
tpx = input(defval = 0.4, title = 'Atr multiplication for TPs?')
slx = input(defval = 0.6, title = 'Atr multiplication for SL?')
isLong = false
isLong := nz(isLong[1])
isShort = false
isShort := nz(isShort[1])
entryPric... |
#!/usr/bin/env python
import myokit
import matplotlib.pyplot as pl
from manual_APD import ap_duration
import numpy as np
from HF_model import Ord_HF_Gomez
## O'hara Restitution
## S1S2 steady state S1 pacing at 1000ms, single
'''
# Using APD 90 for final S1 AP to calculate DI
percent = 90
bcl = 1000
m = myokit.load_mo... |
import os
class constants:
DYNAMO_DB_TABLE_NAME = os.environ['DYNAMODB_TABLE']
USER_DB_TABLE_NAME = os.environ['USER_TABLE']
ITEMS_DB_TABLE = os.environ['ITEM_TABLE']
OUTLET_DB_TABLE = os.environ['OUTLET_TABLE'] |
from turtle import Turtle
class Snake:
def __init__(self):
self.body = []
self.create_snake()
def create_snake(self):
for i in range(3):
new_section = Turtle('square')
new_section.penup()
new_section.color('white')
new_section.setpos((i *... |
import ast
def recursive(func):
""" decorator to make visitor work recursive """
def wrapper(self, node):
func(self, node)
self.generic_visit(node)
return wrapper
class DetectUnusedImport(ast.NodeVisitor):
"To detect unused import using ast"
ignore = ["*", "__future__"]
de... |
import os
import re
import sys
import numpy as np
from rouge import Rouge
from nltk import PorterStemmer
stemmer = PorterStemmer()
def get_num(str):
return int(re.search(r'\d+', str).group())
def prepare(gt, res):
clean_gt = [" ".join([stemmer.stem(i) for i in line.split()]) for line in gt]
clean_res = [" ".... |
from django.shortcuts import render
from django.views.generic import CreateView, UpdateView
from django.urls import reverse_lazy, reverse
from django.shortcuts import redirect, HttpResponseRedirect
from .forms import SettingForm
# Create your views here.
from .models import Profile, Setting
from django.contrib.auth.mix... |
"""
реализовать калькулятор
пользователь вводит с консоли раздельно операнды и операцию
результат выводится в консоль
результат сохраняется и используется как первый операнд следующей операции
"""
PLUS = '+'
AVAILABLE_OPERATION = (PLUS, '-', '*', '/')
first_number = int(input('enter number 1: '))
while True:
opera... |
import os
import sys
import argparse
import random
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.utils.data
import torchvision.transforms as transforms
from torch.autograd import Variable
import utils
from utils import PointLoss
from utils import distance_squre
import data_util... |
from core.utils import display_msg
from glob import glob
import os
import time
import json
import tqdm
BUFFER_SIZE = 1 * 4096
SEPARATOR = "<SEPARATOR>"
class FileTransfer:
def __init__(self, server):
self.server = server
def upload_with_tqdm(self, filename):
if filename == "quit":
... |
#! /usr/bin/python
'''
Description: Second step of dsx binding site search: cataloging all identified motifs and
determining the most frequently found putative binding sites.
Author: Barbara Vreede
Contact: b.vreede@gmail.com
Date: 24 August 2016
'''
from collections import Counter
import dsx_config
infile = open("s... |
# Zope imports
from zope.i18n.interfaces import ITranslationDomain
from zope.interface import implements
from App.ImageFile import ImageFile
from Globals import InitializeClass
from zope.i18n import interpolate
# Product imports
from portal_tool import NaayaI18n, manage_addNaayaI18n
import patches
try:
from Prod... |
import matplotlib
use = 'tk' # qt tk
if use == 'tk':
matplotlib.use('TkAgg') # Qt4Agg TkAgg
import matplotlib.backends.backend_tkagg as tkagg
from matplotlib.backend_bases import cursors
tkagg.cursord[cursors.POINTER] = 'hand1' # hand1 hand2 # http://www.tcl.tk/man/tcl8.4/TkCmd/cursors.htm
else:
... |
# coding=utf-8
# Copyright (c) 2019 Alibaba PAI team.
#
# 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 ... |
# coding: utf-8
"""
BIMData API
BIMData API is a tool to interact with your models stored on BIMData’s servers. Through the API, you can manage your projects, the clouds, upload your IFC files and manage them through endpoints. # noqa: E501
The version of the OpenAPI document: v1
Contact: suppor... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'guest_book.apps.book.views.index_redirect',
name='index_redirect'),
url(r'^board/', include('guest_... |
import itertools
def right(starti, endi, startj, endj):
# Generate list of starting indices
ins = tuple(itertools.product(range(starti,endi+1), range(startj,endj+1)))
# Foreach index-pair, collect it and its neighbors in a list
x = map( lambda t: [g[t[0]][j] for j in range(t[1],t[1]+4)], ins)
# lis... |
#!/usr/bin/env pypy
import fileinput, base64, binascii
__author__ = "Alonso Vidales"
__email__ = "alonso.vidales@tras2.es"
__date__ = "2013-05-06"
class Problem:
__debug = False
def resolve(self):
result = []
for line in self.__lines:
result.append(base64.b64decode(line))
... |
""" Main module to start the application. """
from os.path import dirname, join
from moview import __version__
from moview.ui.app import get_qapp
def main():
qapp = get_qapp()
from moview.ui.mainwindow import MoViewWindow
w = MoViewWindow()
w.show()
qapp.exec_()
if __name__ == '__main__':
... |
feed1 = """
<html><body>
<article class="h-entry">
<h1 class="p-name">A new article</h1>
<div class="e-content">
<p>This is the text of the article.</p>
<p>It has 2 paragraphs.</p>
</div>
<a class="u-url" href="https://example.org/a-new-article">permalink</a>
</article>
... |
import pytest
from flask import Response, url_for
from flask_wtf.csrf import CSRFError
from notifications_python_client.errors import HTTPError
from tests.conftest import set_config_values
def test_bad_url_returns_page_not_found(client_request):
page = client_request.get_url(
"/bad_url",
_expecte... |
#!/usr/bin/env python3
from __future__ import annotations
import re, copy
from more_itertools import split_at
from typing import List, Tuple, Optional
def reverse(value: str) -> str:
return value[::-1]
class Tile:
def __init__(self, lines: List[str]):
match = re.match(r'Tile (\d+):', lines[0])
... |
#!/usr/bin/env python
import os
import sys
try:
# Python 3
from urllib.parse import urlparse
except ImportError:
# Python 2
from urlparse import urlparse
def __main__(cmd, url=None):
command = 'redis-cli'
if url is None:
params = [command]
else:
parsed = urlparse(url)
... |
import pandas
import matplotlib.pyplot
import seaborn
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
from sklearn import svm
from pybrain.datasets import Supervi... |
def is_prime(num):
divis_list = []
# Add divisible numbers to list
for i in range(2, num - 1):
if num % i == 0:
divis_list.append(i)
# If nothing is added to the list,
# the number is prime
if len(divis_list) != 0:
print("Not prime.")
else:
print("Prime... |
"""PYTHON CHALLENGE HOMEWORK- Mohamed Musa"""
#import OS and CSV libraries
import os
import csv
#variables for calculations
month_counter = 0
sum_revenue = 0
sum_revenue_change = 0
#repeat code once for each data file
#this is helpful when there are multiple files
for file_count in range(1):
file_name = "budget... |
#!/usr/bin/python
import re
str = 'Xan examplXe word:cat!! aiosdi IVaslkdj XI'
match = re.search(r'\s+[XVLMCDI]+\s+|\s+[XVLMCDI]+$|^[XVLMCDI]+\s+', str)
if match:
print 'found', match.group()
else:
print 'did not find'
|
import logging
import matplotlib.pyplot as plt
import math
import os
from datetime import datetime
DATETIME_NOW = datetime.now().strftime("%Y%m%d%H%M%S")
LOGS_DIR = os.path.join(os.path.dirname(__file__), 'logs')
def generate_market_logger(model_name):
market_log_path = '{}-{}-{}'.format(model_name, DATETIME_N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.