text stringlengths 8 6.05M |
|---|
# Generated by Django 2.2.4 on 2019-12-01 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('school', '0009_auto_20191201_1352'),
]
operations = [
migrations.AlterField(
model_name='career',
name='code',
... |
from __future__ import print_function
import sys
import os
sys.path.append(os.getcwd())
#[ getting_started_listing_04
import histogram as hg
# make 1-d histogram with 5 logarithmic bins from 1e0 to 1e5
h = hg.histogram(hg.axis.regular_log(5, 1e0, 1e5, "x"))
# fill histogram with numbers
for x in (2e0, 2e1, 2e2, 2e3,... |
"""smbus2-asyncio setup.py."""
import re
from setuptools import setup
# http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package
VERSIONFILE = "smbus2_asyncio/version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, v... |
from django.db import models
from django.conf import settings
from django.urls import reverse
import os
class DataSchema(models.Model):
"""Model which describes data schemas."""
title = models.CharField(max_length=50)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(au... |
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import selenium
import time
import re
import requests
from readFile import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 获取微信公众Biz
def weChatBiz():
# 读取txt文档但不读取文档的抬头,把位置为在最左的字串更换为list数据格式
wechatlist = readFi... |
from astropy.io import fits
from regions.core import PixCoord
from regions import CirclePixelRegion, CircleSkyRegion
from astropy.units import Quantity
import numpy as np
from astropy.coordinates import Angle, SkyCoord
import astropy.wcs as wcs
from astropy import constants as const
from basic_funcs import *
import ast... |
#coding:utf-8
"""
"""
class Task(object):
def __init__(self, id_, project_name, title, serial_no, timelimit, timestamp, note, status):
self.id_ = id_
self.project_name = project_name
self.title = title
self.serial_no = serial_no
self.timelimit = timelimit
self.timesta... |
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import euclidean_distances
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import minmax_scale
df = pd.read_excel('first_300_des_res.xlsx', engine='openpyxl')
cities = ... |
num_staircases = int(input())
staircase_heights = []
for i in range(num_staircases):
height = int(input())
staircase_heights.append(height)
def ways(steps, mem = {0: 0, 1: 1}):
if steps not in mem:
mem[steps] = ways(steps, mem)
if steps >= 0:
if steps == 1:
return(1)
... |
#title :permissions.py
#description :.
#author :juniorgerdet
#date :04-06-2015
#version :0.1
#usage :
#notes :
#python_version :2.7.10
#==============================================================================
from rest_framework import permissions
... |
a,b=input().split()
e=[]
f=''
for i in range(int(a)+1,int(b)):
c=1
d=0
while c<=i:
if i%c==0:
d+=1
c+=1
if d==2:
e.append(i)
for i in range(len(e)-1):
f+=str(e[i])+" "
print(f+str(e[-1]))
|
"""
SearchEngine.py
Defines a class SearchEngine which contains the main search logic for the search engine
program.
"""
from Crawler import Crawler
from Indexer import Indexer
from PageRank import Computer
from math import log10,sqrt,pow
from collections import defaultdict
from bokeh.glyphs impo... |
from bibliopixel import LEDStrip
import bibliopixel.colors as colors
from bibliopixel.animation import BaseStripAnim
import random
class Searchlights(BaseStripAnim):
"""Three search lights sweeping at different speeds"""
def __init__(self, led, colors=[colors.MediumSeaGreen,colors.MediumPurple,colors.MediumV... |
from django.contrib import admin
from kratos.apps.tasktpl.models import Tasktpl
admin.site.register(Tasktpl)
|
from keras.models import Sequential
from keras.layers import Conv1D
from keras.layers import Flatten
from keras.layers import Dropout
from keras.layers import Activation
from keras.layers import MaxPooling1D
from keras.layers import BatchNormalization
from keras.layers import Dense
class Rede_convolucional:
@stati... |
# Generated by Django 3.1.1 on 2020-11-23 01:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Credentials',
fields=[
... |
from Target import Target
class TargetList:
#global printList, findTarget
def __init__(self, total):
self.targetList = []
for i in range(0, total):
self.targetList.append(Target())
def PrintList(self):
print "\nList of available target ip addresses: "
for i in range(len(self.targetList)):
print s... |
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
import torch
import pickle
import matplotlib.pyplot as plt
# weird_function('원본') = '오염'
# weird_function('랜덤') = '가설'
# weird_function(x1) = weird_function(x2) -> x1 = x2 를 가정하는 듯.
# '오염' 과 '가설' 사이의 오차를 줄이며 '랜덤'을 갱신하면 '랜덤'과 '원본'이 같아져있을 것이다.
# 책에서 오차를 '가설... |
import sys
MASS_TABLE = {
'A': 71.03711,
'C': 103.00919,
'D': 115.02694,
'E': 129.04259,
'F': 147.06841,
'G': 57.02146,
'H': 137.05891,
'I': 113.08406,
'K': 128.09496,
'L': 113.08406,
'M': 131.04049,
'N': 114.04293,
'P': 97.05276,
'Q': 128.05858,
'R': 156.1011... |
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
# 贪心
# time: O(nlogn) n 是 g 或 s 中较长的 , space: O(1)
kids = sorted(g)
foods = sorted(s)
i, j = 0, 0
children = 0
while i < len(kids) and j < len(foods):
if kids[i] <= ... |
import os
import argparse
import pickle
import logging
import pandas as pd
import numpy as np
from scipy.sparse import load_npz
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.externals import joblib
LR_COLS = ['tweet_id', 'label', 'tfidf']
key_word_dict = {
'donaldt... |
# -*- coding: utf-8 -*-
{
'name': 'Descuento en notas de venta',
'version': '0.1',
'category': 'sale',
'description': """
descuento en ventas
""",
'author': 'Econube | Jose Pinto,Pablo Cabezas',
'website': 'http://www.econube.cl',
'depends': ['sale','account','account_voucher'],
'dat... |
# -*- coding: utf-8 -*-
import dataiku
import pandas as pd, numpy as np
from dataiku import pandasutils as pdu
# Recipe input
folder = dataiku.Folder("3ep5yCky")
paths = folder.list_paths_in_partition()
# Core recipe
LABEL_0 = "lion"
LABEL_1 = "tiger"
df = pd.DataFrame(columns=['path', 'label'])
for i,j in enumera... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 11:01:27 2019
@author: saib
Purpose: Variables Type
"""
x = 45
y = 56.87
z = "Hello"
print("X is", type(x))
print("Y is", type(y))
print("Z is", type(z))
"""
Types of quotes
"""
print('"Hello" WOrld')
print("'Hello' WOrld")
print(''Hello' WOrld")
|
from django.views.generic.edit import UpdateView, DeleteView
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.http import JsonResponse
from .forms import CreateWordFor... |
# sigam(1/x) when x goes to positive infinity
# Farhad Ramezanghorbani
step=1 # set step to 1
sigma=0.0 # set sigma of 1/x to 0
error=10**(-6) # def err (which is subtraction-
# of two consequent sigma)
pytresult=open("hw21result.txt","w") # open an empty .txt for writing the result
def div(x): ... |
from datetime import datetime, date, timedelta
import sys
import requests
import json
from bs4 import BeautifulSoup
'''
Uses JSON requests to grab my timetable from opentimetables and outputs to the console.
'''
current_date = datetime.today().strftime("%Y-%m-%d")
l_date = date(int(current_date.split("-")[0]), int(... |
N, M = map(int, input().split())
S = [ list(input()) for i in range(N)]
ans = 0
for i in range(N):
for j in range(M):
U, D, L, R = 0,0,0,0
if S[i][j] == '#':
continue
for k in range(i-1,-1,-1):
if S[k][j] == '#':
break
else:
... |
# Generated by Django 2.0.5 on 2018-07-21 06:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0014_auto_20180713_1443'),
]
operations = [
migrations.AlterField(
model_name='set',
name='image_url',
... |
from django.urls import path
from . import views
app_name = "bbs"
urlpatterns = [
# path('', views.index, name='index'),
path('', views.QuestionListView.as_view(), name='index'),
path('my-page', views.my_page, name='my-page'),
# ex: /bbs/5/
# path('<int:question_id>/', views.detail, name='detail')... |
default_app_config = 'communications.apps.CommunicationsAppConfig'
|
from tkinter import *
import GameLogic
class CardManager:
def __init__(self, window):
self.window = window
self.cards = []
self.acePosition = []
self.cardIndex = 0
self.CreateCards()
def SetNextCard(self, cardType):
print(cardType)
try:
self.cards[self.cardIndex].config(text = cardType, bg ='white... |
#!/usr/bin/env python3
import glob
import itertools
import logging
import os
import re
import socket
import sys
import warnings
import hydra
import joblib
import matplotlib.pyplot as plt
import neptune_tensorboard
import numpy as np
import pandas as pd
import scipy
import seaborn as sns
import tensorflow as tf
import... |
import pytest
import requests_mock
from flask import Flask
@pytest.fixture
def app():
return Flask(__name__)
@pytest.yield_fixture
def rmock():
with requests_mock.mock() as rmock:
real_register_uri = rmock.register_uri
def register_uri_with_complete_qs(*args, **kwargs):
if 'comp... |
from rest_framework.response import Response
from rest_framework.views import APIView
from app.utils import get_query_param_filters
from app.pools.models.pool_user import PoolUser
from app.transactions.models.transaction import Transaction
from app.transactions.serializers.transaction import TransactionSerializer
cl... |
import dataclasses
import hashlib
import json
def _ensure_bytes(bytes_or_something) -> bytes:
if isinstance(bytes_or_something, bytes):
return bytes_or_something
if isinstance(bytes_or_something, str):
return bytes_or_something.encode()
raise NotImplementedError(f'how bytes? ({bytes_or_som... |
#!/usr/bin/env ganga
import getpass
from distutils.util import strtobool
b=Job()
b.application=DaVinci()
b.application.optsfile='DNTupleMaker.py'
b.outputfiles=[DiracFile('Output.root')]
b.inputdata=browseBK()
b.splitter = SplitByFiles(filesPerJob=50)
b.backend=Dirac()
queues.add(b.submit)
|
from collections import defaultdict
N, M = map( int, input().split())
S = list( input())
E = [ list( map( int, input().split())) for _ in range(M)]
V = [ 1 for _ in range(N)]
Edges = [set() for _ in range(N)]
A = [0]*N
B = [0]*N
d = defaultdict(int)
for i in range(M):
a, b = E[i]
a, b = a-1, b-1
a, b = min(... |
# -*- coding:utf-8 -*-
import pickle
import json
import re
character_num = {}
character_table = {}
count = 0
with open("Frequency.pickle", 'rb') as d:
character_num = pickle.load(d)
with open("Character.pickle", 'rb') as d:
character_table = pickle.load(d)
for pinyin in character_table:
character_num[piny... |
# Generated by Django 2.0.6 on 2018-06-17 13:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rooms', '0002_auto_20180617_1650'),
]
operations = [
migrations.RemoveField(
model_name='question',
name='name',
... |
# -*- coding: utf-8 -*-
# Делаем базовые настройки
from chatterbot import ChatBot
# Способ записать, что делает нейросеть (логинрование)
# logging.basicConfig(level=logging.INFO)
# Создаем чатбота
bot=ChatBot(
"Feedback Bot",
# Адаптор памяти
storage_adapter='chatterbot.storage.SQLStorageAdapter',
# у... |
# ==================================================================================================
# Copyright 2014 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, RandomSampler
from torchvision import models
from torchvision import transforms
from transformers import AdamW
import tools
class PretrainedClassifier(nn.Module):
"""
A binary classifier based o... |
import argparse
from nmt.data import Vocabulary, Dataset
from nmt.evaluation import TransformerModelConfig, Evaluator
from nmt.util import get_device
import logging
logger = logging.getLogger("Evaluator")
def evaluate_model(args: argparse.Namespace):
source_vocab = Vocabulary(args.src_vocab)
target_vocab = Vocabu... |
import logging
import urllib
import urlparse
import urllib2
import simplejson
import openerp
from openerp.osv import osv, fields
from openerp import SUPERUSER_ID
from bsddb.dbtables import _columns
_logger = logging.getLogger(__name__)
class res_users(osv.Model):
_inherit = 'res.users'
_columns = {
... |
#!/usr/bin/python3
"""Python script that takes GitHub credentials (username and
password) and uses the GitHub API to display the user id."""
import requests
from sys import argv
if __name__ == "__main__":
auth = (argv[1], argv[2])
request = requests.get("https://api.github.com/user", auth=auth)
print(requ... |
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import to... |
def is_palindrome(word):
# 코드를 입력하세요.
index = len(word) - 1
for spell in word:
if spell != word[index]:
return False
index -= 1
return True
# 테스트
print(is_palindrome("racecar"))
print(is_palindrome("stars"))
print(is_palindrome("토마토"))
print(is_palindrome("kayak"))
print(is... |
# -*- coding: utf-8 -*-
#############
#
# Copyright - Nirlendu Saha
#
# author - nirlendu@gmail.com
#
#############
from __future__ import unicode_literals
import inspect
import sys
from libs.logger import app_logger as log
from django.db import models
##
#
# Person Primary Manager
#
##
class PersonPrimaryManager... |
# coding=utf-8
# Proxy1: http://www.xicidaili.com/
# Proxy2: http://www.haoip.cc/index/2377233.htm
# proxy = {'http':'ip:port'} # dictionary
# html = requests.get('https://www.baidu.com',proxies=proxy)
#Org doc refer to https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen
#Now refer to http:/... |
#!/usr/bin/python
import torch
import numpy as np
def get_data(train_path, max_len=100):
print('Loading data...')
# read sents and get vocab
sents = []
vocab = {'<pad>': 0, '<UNK>': 1, '<bos>': 2, '<eos>': 3}
i = ... |
#Use only functions supplied by tkinter and the controller
from tkinter import *
#from photomosaicmvc.controller import number_button, place_call_button, clear_button, special_entry
#Lay out the main GUI (Phone) left->right as two frames and a Button
root = Tk()
root.title("Photomosaic")
main = Frame(root... |
import sys
import traceback
import logging
# package
import config
from rules import Rules
import exchange
from fhandler import ReadFile
from fhandler import WriteFile
from stats import Stats
def main():
# read exchange rates file
logging.info("Reading Exchange Rates.")
if not exchange.load... |
def check(a,b,c,d,V):
V[a][b] += 1
V[c][d] += 1
V[a][d] -= 1
V[c][b] -= 1
N, K = map( int, input().split())
L = K*2
KK = [[0]*(L+1) for _ in range(L+1)]
for i in range(N):
x, y, c = input().split()
x, y = int(x), int(y)
if c == "B":
x, y = x%L, y%L
else:
x, y = (x+K)%L... |
from django.urls import path
from .views import users
urlpatterns = [
path('', users, name='users'),
]
|
import urllib2#python2
import web_parse
from Tkinter import *
import tkMessageBox
class lydi():
def entotw(self):
print ('entotw')
def translate(self):
self.afgt.configure(state=NORMAL)
query=self.befgt.get('1.0','end-1c')
out=web_parse.parse(query)
self.afgt.delete('1.0','end-1c')
self.afgt... |
from collections import defaultdict
def twopower(n):
for i in range(32):
if n < 2**i:
return 2**i
N = int( input())
A = list( map( int, input().split()))
d = defaultdict( int)
e = defaultdict( int)
for i in range(N):
d[A[i]] += 1
A.sort(reverse=True)
i = 0
ans = 0
while i < N:
if e[A[i]]... |
import os
import logging
import zmq
import math
import traceback
import datetime
import time
import multiprocessing
import rethinkdb
import utils
__all__ = [
'ImportManager',
'ImportWorker',
]
LOG = logging.getLogger(__name__)
class ImportManager(object):
def __init__(self, controller, config):
... |
import os
import random
import tarfile
from os import path
from pathlib import Path
import networkx as nx
import numpy as np
import pandas as pd
import requests
import torch
import torch_geometric
from pymatgen.io.cif import CifParser
from torch_geometric.data import InMemoryDataset
class BinaryDataSet(InMemoryDatas... |
# -*- coding: utf-8 -*-
import cv2
import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as mpatches
def create_colormap(svs_im, matrix_0, title, output_dir):
plt_size = (svs_im.size[0] // 100, svs_im.size[1] //100)
flg, ax = plt.subplo... |
paranoid_andriod = 'Marvin, the paranoid Andriod'
letters = list(paranoid_andriod)
for char in letters[:6]:
print('\t',char)
print()
for char in letters[-7:]:
print('\t' * 2,char)
print()
for char in letters[12:20]:
print('\t' * 3,char) |
from apay import app, db, models
from flask import request, jsonify
@app.route('/companies', methods=['POST', 'GET'])
def company():
if request.method == 'POST':
try:
company = models.Company(request.get_json())
db.session.add(company)
db.session.commit()
r... |
# -*- coding: UTF-8 -*-
''' Utility functions supporting image & model operation '''
import math
import io
import pickle
import face_recognition
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from bson.binary import Binary
ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg']
FONT_DIR_NAME = "/usr/share/fonts/... |
from django.conf.urls import url
from myapp.views import signup_view, feed_view, login_view, post_view, like_view, comment_view, logout_view, upvoting_view, search_view
urlpatterns = [
url('post/', post_view),
url('feed/', feed_view),
url('like/', like_view),
url('comment/', comment_view),
url('log... |
from flask import render_template, request, make_response, redirect, Blueprint, url_for, flash
from app.controllers.login import authenticate
login_view = Blueprint('login', __name__)
@login_view.route('/logout')
def logout():
response = make_response(render_template('loginpage.html'))
response.set_cookie('email'... |
#!/usr/bin/python
# Solar_Doomsday
# Code by: -Redacted for Privacy-
# Challenge: Write a function called answer(data, n) that takes in a list of
# less than 100 integers and a number n, and returns that same list but with
# all of the numbers that occur more than n times removed entirely.
# The returned list shou... |
import string
alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"
def encrypt():
print("Este es el sistema para el cifrado de cesar\n")
message = input("Escribe el mensaje que deseas encriptar: ").lower()
print()
key = int(input("Introduce la llave: ")) #Key=ROT
enc... |
from unittest import TestCase
PT_SVC_ADDR = 'http://0.0.0.0:5000/'
#PT_SVC_ADDR = 'http://127.0.0.1/project'
from bat.tests.common_api_tests import CommonAPITest
class ServiceFunctionalTest(TestCase, CommonAPITest):
def setUp(self):
self.service_address = PT_SVC_ADDR
|
from django.contrib import admin
from auth_.models import MainUser
@admin.register(MainUser)
class MainUserAdmin(admin.ModelAdmin):
list_display = ['email',]
|
from midiutil import MIDIFile
from audiolazy import str2midi
def note_to_numeral(note):
"""
This function takes my internal note data structure.
{'note': 'c', 'octave': 4}
"""
letter = note['note'].strip()[0].upper()
octave = note['octave']
if len(note['note']) == 2:
letter = note['... |
# Importing necessary libraries and loading data.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import math
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
sns.set(color_codes=True)
# Load training and test data into panda... |
#!/usr/bin/python3
# vim:fileencoding=utf-8:ts=2:sw=2:expandtab
# Setup the path
import os, os.path, sys; sys.path.insert(1, os.path.abspath(sys.path[0] + "/../Python"))
import json
from base64 import b64encode
try:
from DocStruct import Setup
from DocStruct.Config import EnvironmentConfig
from DocStruct.Base ... |
__author__ = 'natalie'
import sys
PYTHON3 = sys.version_info[0] > 2
# decode a string. if str is a python 3 string, do nothing.
def decode(str_, codec='utf8'):
if PYTHON3:
return str_
else:
return str_.decode(codec)
# encode a string. if str is a python 3 string, do nothing.
def encode(str... |
__author__ = 'rakesh.varma'
from ConfigParser import SafeConfigParser
class ConfigFactory:
def __init__(self):
self.config = SafeConfigParser()
self.config.read('config.ini')
self.section = 'all'
@property
def username(self):
return self.config.get(section = self.section, ... |
import csv
a = []
with open("/home/basar/Downloads/icd10cm_codes_2020.txt") as f:
for line in f :
line = line.split(None, 1)
line[1] = line[1][:-1]
a.append(line)
with open("icd10cm_codes_2020.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)
|
import time
import joblib
import os
import os.path as osp
import tensorflow as tf
from spinup import EpochLogger
from spinup.utils.logx import restore_tf_graph
import gym
from gym import spaces
from gym.spaces import Box, Discrete
from gym.utils import seeding
import random
import math
import numpy as np
import sys
... |
import inspect
from typing import Any, Dict, List, Iterator, Optional
from functools import wraps, partial, update_wrapper
# TODO
_HookType = Any
class AsyncHookable:
__hooks__: Dict[str, List[_HookType]] = {}
def _hooks_for(self, name: str) -> Iterator[_HookType]:
yield from self.__hooks__.get(nam... |
# Generated by Django 2.0 on 2018-09-30 23:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mili', '0002_auto_20180930_1355'),
]
operations = [
migrations.CreateModel(
name='Examination',
fields=[
... |
"""
from projects.models import Publication
Publication.objects.all()
order = Publication.objects.all()[0]
order.amount
order.description
"""
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-31 12:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post_app', '0003_blacklist'),
]
operations = [
migrations.AlterField(
... |
from mpi4py import MPI
from subprocess import Popen, PIPE, STDOUT, call, check_output
import random
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
command = 'Rscript'
sim_path = '/sciclone/home00/geogdan/MatchIt/demo/pySims.R'
iterations = 100000
c = rank
while c < iterations:
out_path = ... |
sum = 0
for x in range(0, 101 ,2):
sum += x
print(x)
print(sum) |
# coding: utf-8
# Copyright 2013 The Font Bakery 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 re... |
import json
import os
from stackapi import StackAPI
user_id = 792935
SITE = StackAPI('stackoverflow')
DATA_PATH = 'W:\\GITHUB\\NLP_SO\\Data\\'
def main():
u = SITE.fetch('users/{}/comments'.format(user_id))
dumpJson('comments000', u)
# de facto URL limit ~2000 chars. so let's get comments in batches ... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
class TuerqiPipeline(object):
def __init__(self):
self.username = 'new_news'
self.passwo... |
import requests
import json
import spacy
import os
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from core.config import ALLOWED_HOSTS, DEBUG, PROJECT_NAME
from api.router import router as api_router
def get_application() -> FastAPI:
application = FastAPI(title=PROJECT_NAME,... |
from typing import Any, Callable, Dict, Iterable, List, Set
from .package import Package
NodeApply = Callable[["Node", int], Any] # Tried to use TypeVar instead of Any
def identity(node: "Node", level: int = 0) -> "Package":
return node.package
# def bfs_recurse(
# nodes: List["Node"], apply_fn: NodeAppl... |
"""
Controle de flux: instructions itératives conditionnelles.
(séquence) BOUCLE FOR
Imaginez que vous ayez une liste de quatre éléments dont vous voulez afficher les éléments
les après les autres. Dans l'état actuel de vos connaissances,
il faudrait taper quelque chose de style
"""
"""
Si votre liste ne contient q... |
import pymysql
import requests
from bs4 import BeautifulSoup
from abc import *
import crawling
class NaverTrendsCrawling(crawling.Crawling, ABC):
def __init__(self, main_url, db_host, db_port, db_user, db_pw, db_name, db_charset):
super().__init__(main_url, db_host, db_port, db_user, db_pw, db_name, db_c... |
import sys
import glob, os
import json
from string import Template
################################################################################
# Check the input files
abcfiles = []
os.chdir("./")
for file in glob.glob("*.abc"):
abcfiles.append(file[:-4])
#######################################################... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from storage.models import Storage
from history.models import History
@login_required(login_url='login:login')
def index(request):
history_lst = History.objects.filter(status__... |
from adapters.dimmable_bulb_adapter import DimmableBulbAdapter
from adapters.generic.motion_sensor import MotionSensorAdapter
from adapters.generic.temp_hum_sensor import TemperatureHumiditySensorAdapter
from adapters.tuyatec.GDKES02TZXD import GDKES02TZXD
from adapters.tuyatec.GDKES03TZXD import GDKES03TZXD
tuyatec_a... |
preco = float(input("Digite o Preço: "))
valor = float(input("Digite o Valor: "))
troco = preco - valor
print(troco) |
in_file = open('input_14.txt', 'r')
# in_file = open('test_14.txt', 'r')
def masked(mask, memAddress):
newAddress = list(memAddress.zfill(len(mask)))
for idx in range(len(newAddress)-1, -1, -1):
if mask[idx] != '0':
newAddress[idx] = mask[idx]
return ''.join(newAddress).lstrip('0') or '0'
mem = dict()
def int... |
# Generated by Django 3.1.3 on 2020-12-07 03:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app01', '0003_auto_20201207_1102'),
]
operations = [
migrations.AlterField(
model_name='img',
name='src',
... |
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Parks
class ParkForm(ModelForm):
class Meta:
model = Parks
exclude = ['user']
|
# coding: utf-8
# In[1]:
# opengrid imports
from opengrid.library import misc, houseprint, caching
from opengrid.library.analysis import DailyAgg
from opengrid import config
c=config.Config()
# other imports
import pandas as pd
import charts
import numpy as np
import os
import datetime as dt
import pytz
BXL = pytz.... |
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Apache License, version 2.0.
# If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www.apache.org/licenses/LICENSE-2.0.
# SP... |
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D,Input
from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import SGD
from keras.callbacks import CSVLogger
import sys
n_categories=5
batch_size=32
train_dir='../.... |
# coding: utf-8
#__author__ = cmathx
from theano.tensor.shared_randomstreams import RandomStreams
from theano import function
srng = RandomStreams(seed = 234)
rv_u = srng.uniform((2, 2))
rv_n = srng.normal((2, 2))
f = function([], rv_u)
g = function([], rv_n, no_default_updates = True)
nearly_zeros = function([], rv_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.