text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
import sys
import yaml
from pybtex.database import BibliographyData
from pybtex.database.input import bibtex
from StringIO import StringIO
from pybtex.database.output import bibtex as bibtexo
import json
filename = sys.argv[1]
out = sys.argv[2]
parser = bibtex.Parser()
bib_data = parser.parse_fi... |
from rest_framework import serializers
from ..models import University
class UniversitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = University
fields = ["url", "id", "name", "country", "city"]
|
# -*- coding:utf-8 -*-
def main():
string = "A screaming comes across the sky."
print(string.replace("s", "$"))
if __name__ == '__main__':
main()
|
# attempt
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
visited = []
longest = []
for char in s:
if char not in visited:
visited.append(char)
else:
if len(visited) > len(longest):
longest = visit... |
n_site = 2
n_mode = 200
vij = 0
for i in range(n_site-1):
j = i + 1
print i+1, j+1
print vij
for i_mode in range(1, n_mode):
print 0
print j+1, i+1
print vij
for i_mode in range(1, n_mode):
print 0
|
import sys
sys.path.append("..")
import xgboost as xgb
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import UniformFloatHyperparameter, \
UniformIntegerHyperparameter, UnParametrizedHyperparameter, Constant, \
CategoricalHyperparameter
from Forecasting import A... |
statement = input()
if statement == "t":
print("Yes")
if input != "x":
print("Rubbish")
else:
pass
elif statement == "N":
print("No")
else:
print("What?")
|
def solution(A, B):
temp = []
if len(A)<len(B): temp = B; B = A; A = temp
A.sort()
B.sort()
i = 0
for a in A:
if i < len(B) - 1 and B[i] < a:
i += 1
if a == B[i]:
return a
return -1
if __name__ == '__main__':
real_answer = solution([1,3,2,5],[4,4,... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 12 09:11:29 2019
@author: bittu
"""
import cv2
import numpy as np
import sqlite3
# we are using cascade classifier
faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#load the web cam
cam=cv2.VideoCapture(0); #for web cam the capture id is generall... |
"""
D
/ \
A B C
\ / /
Mc
"""
class D:
def f1(self):
print('from D')
class A(D):
pass
class B(D):
def f1(self):
print('from B')
class C:
def f1(self):
print('from C')
class Mc(A,B,C):
pass
print(Mc.mro()) |
__author__ = 'tomas'
import numpy as np
# import tools
PRIORITY_LOW = 0 # for lessions that are extracted autonomously
PRIORITY_HIGH = 1 # for lessions that are added by the user, these wil not be filtrated by sliders (area, density, ...)
def create_lesion_from_pt(pt, density, lbl, priority=PRIORITY_HIGH):
"""... |
from django.contrib import admin
from .models import Tyre, UserInfo, Feedback, TyresGroup, Images
admin.site.register(TyresGroup)
admin.site.register(Tyre)
admin.site.register(Images)
admin.site.register(UserInfo)
admin.site.register(Feedback) |
# Python modules
import simpleaudio as sa
import time
import random
import _thread
import sys
# Project modules
import userInput as ui
import playback as pb
import beatGenerator as bgen
import writeMidi as midi
# Terminal colors
colorErr = "\033[31m"
colorReset = "\033[0m"
# Display some nice things
ui.titleText()
... |
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from django.contrib.auth.models import User
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest... |
'''
let's see how easy moving to use semiinteger and semicontinuous decision variables with docplex.
Semiinteger means for example for a quantity of buses that it's either 0 or within a given range.
In our bus example, suppose we cannot rent less than 4 buses for any given size.
We then write:
'''
from docplex.mp... |
import os
import sys
from flask import Flask
from cms.models import Entry
from cms.models import User
CONFIGS = {
'production': 'config-production.py',
'development': 'config-development.py',
}
def create_app():
app = Flask(__name__, instance_relative_config=True)
config_name = CONFIGS[os.getenv('... |
"""
1) Use 2 references
Note: String are inmutable so we must pass in an array of ch if we want to do it inplace
Time: O(n) Space:O(1)
"""
def reverse_inplace(ch_arr):
if len(ch_arr) < 2:
return ch_arr
beg = 0
end = len(ch_arr) - 1
while beg < end:
tmp = ch_arr[beg]
ch_arr[... |
#!/usr/bin/env python3
# encoding: utf-8
from collections import defaultdict
from copy import deepcopy
from typing import Dict, List
import numpy as np
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.side_channel.engine_configuration_channel import \
EngineConfigurationChannel
... |
#COMMIT DAMN YOU
from Item import *
from Map_Object import *
import csv
class Item_Database(Map_Object):
def __init__(self):#This class is used to house all items that will be accessible in the game
self.items=[]
self.numberOfItems=0
def add_item(self,Item):#This function adds an ite... |
# -*- coding: utf-8 -*-
# This is a simple wrapper for running application
# $ python main.py
# $ gunicorn -w 4 -b 127.0.0.1:5000 main:app
from application import app
import application.views
if __name__ == '__main__':
app.run()
|
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem
# Difficulty: Easy
# Max Score: 30
# Language: Python
# ========================
# Solution
# ========================
A, B = map(int, input().st... |
#-*- coding:utf8-*-
import sys
class test:
def __enter__(self):
print("enter")
def __exit__(self,*args):
print ("exit")
with test() as a:
print "in with"
print "yes" |
def mountain(n):
k = n-1
for row in range(0,n):
for column in range(0,k):
print(end=" ")
k = k-1
for column in range(0,row+1):
print("* ",end = " ")
print("\n")
n1 = int(input())
mountain(n1)
|
import engine
import genetic_components.node as n
import tensorflow as tf
import pytest
import math
@pytest.fixture
def x_tensor():
x_size = 10
y_size = 20
x_size_tensor = tf.range(x_size)
x_size_tensor = tf.reshape(x_size_tensor, [-1,1])
x_size_tensor = tf.tile(x_size_tensor, [1, y_size])
x_te... |
import argparse
import os
import cv2
import sys
import random
import time
import _pickle as cPickle
import torch
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from pointnet.seg_dataset_fus import PoseDataset
from pointnet.model_seg import FusionInstanceSeg
import torch.nn.functional as F
... |
import logging
import numpy as np
import config.sr_network_conf as base_config
from core_network.Network import *
__author__ = 'ptoth'
_LOGGER = logging.getLogger(__name__)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
# Load up the training data
_LOGGER.info('Loading training dat... |
import requests
from bs4 import BeautifulSoup
def has_usage(info):
try:
return all([(span.name == "span" and span.has_attr("title")) or str(type(span)) == "<class 'bs4.element.NavigableString'>"
for span in info])
except:
return False
def getFromVerben(word):
... |
from assignment_5_wang_custom_knn_class import Custom_knn
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot ... |
import datetime
day1= (2014,7,2)
day2= (2014,7,11)
(y1,m1,d1)= day1
day1=datetime.datetime(y1,m1,d1)
(y2,m2,d2)= day2
day2=datetime.datetime(y2,m2,d2)
print(int(day2.strftime('%j'))-int(day1.strftime('%j')))
|
'''
pipe_event
==========
This module provides a Event class which behaves just like threading.Event
but is based on two pipes created using os.pipe() functions.
Before Python 3.3, monotonic time is not introduced so adjusting system
clock may affect Event.wait() function if specific timeout is set.
Following notes... |
##
# this file is used to operate some command in server
#
# __author__: chuxiaokai
# data: 2016/3/28
import os
from app.models import *
"""
some operation on server
"""
class Server(object):
ip = "127.0.0.1" # default ip
# hash_id = 0
def __init__(self):
"""
get server... |
from skmultiflow.trees import HAT, RegressionHAT
from decai.simulation.contract.classification.scikit_classifier import SciKitClassifierModule
class DecisionTreeModule(SciKitClassifierModule):
def __init__(self, regression=False):
if regression:
model_initializer = lambda: RegressionHAT(
... |
import json
import requests
api_key = input("Your API key again: ")
films = []
i = 0
while len(films) < 1000:
response = requests.get("https://api.themoviedb.org/3/movie/{id_f}?api_key={api_key}&language=en".format(api_key=api_key, id_f=i))
if "status_code" not in response.text:
films.append(json.loa... |
class Car:
def __init__(self, objectId, licenseNumber, make, model):
self._id = objectId
self._license = licenseNumber
self._make = make
self._model = model
@property
def id(self):
return self._id
@property
def license(self):
return self._license
... |
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.views.generic import CreateView, DetailView, UpdateView, DeleteView
from webapp.models import Goal, Project
from webapp.forms import Go... |
from django.shortcuts import render
from pmpportal.models import Registration
def mentors(request):
allmentors = Registration.objects.all()
context = {'mentors': allmentors}
return render(request, 'mentorcards.html', context)
|
import numpy as np
import copy
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import accuracy_score
class OneVsOneClassifier:
def __init__(self, estimator = None):
self.base_estimator_ = estimator
self.binary = True
def init_params(self, X, Y):
if len(np.unique(Y... |
from funcoes import maior
from funcoes import somaLista
from funcoes import mediaLista
from funcoes import valoresIguais
from funcoes import primeiroIgual
a = 5
b = 5
lista = [3, 4, 6, 7]
lista2 = [7, 12, 'dsa', 43, 6]
print(maior.maior(a, b))
print(somaLista.somaLista(lista,5))
print(mediaLista.mediaLis... |
"""
Classes from the 'SwiftUI' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
_TtC7SwiftUIP33_D03BD89F5A2D484C8BA01348D5E2C30219AllFinishe... |
import copy
import string
assignments = []
### Setup
board_rows = string.ascii_uppercase[0:9]
board_cols = string.digits[1:10]
subboard_rows = [board_rows[0:3], board_rows[3:6],board_rows[6:9]]
subboard_cols = [board_cols[0:3], board_cols[3:6],board_cols[6:9]]
subboards = [[r+c for r in sub_row for c in sub_col] for ... |
# Generated by Django 3.0.4 on 2020-07-14 20:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('todo', '0009_nancy_scheduled'),
]
operations = [
migrations.DeleteModel(
name='Todo',
),
]
|
# Generated by Django 2.1.2 on 2019-01-07 18:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0048_dialouge_author'),
]
operations = [
migrations.RemoveField(
model_name='dialouge',
name='member',
)... |
# Author: Matthew Wicker
# Companion Code for paper: Analysis of 3D Deep Learning in an Adversarial Setting
# CVPR 2019
"""
This file impliments the PointNet model (Qi et. al. 2017) in keras
It is aware of weights that are saved in the Models directory of this
repository. So if you would like to modify/retrain this m... |
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from .views import home,all_blogs,Blogdetailview,my_profile,pay_foundation,payment,response,change_status,contact_save,pay... |
from lxml import etree
import os
class Spells():
def __init__(self,interface):
self.interface = interface
self.list_spell = {}
def update_spells(self,spells_data):
self.interface.ongletsSorts.removes_spells()
for spell in spells_data[:len(spells_data)-1]:
... |
from redash import models
from redash.models import db
from redash.permissions import ACCESS_TYPE_MODIFY
from redash.serializers import serialize_query
from tests import BaseTestCase
class TestQueryResourceGet(BaseTestCase):
def test_get_query(self):
query = self.factory.create_query()
rv = self.... |
import script_context
import os
import h5py
import matplotlib.pyplot as plt
import numpy as np
from Stonks.Analytics import Analytics
import time as tm
import importlib
importlib.reload(Analytics)
def instrument_price(sell_price, buy_price, base_price=6, delta=.5):
delta_price = -(sell_price - buy_price) * delt... |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import sqlite3
# In[2]:
# Create your connection.
cnx = sqlite3.connect('mortgage.db')
loan_df_new = pd.read_sql_query("SELECT * FROM loan_data", cnx)
# In[3]:
# Droppping the additional index column
loan_df_new = loan_df_new.drop('index', ax... |
import nltk
from nltk.corpus import stopwords
s = '''Good muffins cost $3.88\nin New York. Please buy me
... two of them.\n\nThanks.'''
tokens = nltk.wordpunct_tokenize(s)
filtered = [w for w in tokens if not w in set(stopwords.words('english'))]
|
#!/usr/bin/env python
import rospy
import math
import tf
import geometry_msgs.msg
import numpy as np
import json
import sys
from scipy.spatial.transform import Rotation
from hrca_action.utilities import *
import actionlib
from hrca_action.panda_arm import PandaArm
if __name__ == '__main__':
rospy.init_node('obj... |
import unittest
from sources.controller.controller import Controller
class ControllerTests(unittest.TestCase):
def testControllerConstructor(self):
self.controller = Controller()
self.assertEquals(0,0) |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
import os, sys, traceback, json
from web3.auto import w3
if __name__ == '__main__':
abifile = open(os.path.join(os.path.dirname(__file__), "sol/build/abi.json"), "r")
abi = json.load(abifile)
abifile.close()
key = "0x620b0c04de671567431e962c6d0eadc28b9f25d... |
import os
import random
list_txtpath='/home/zhanwj/Desktop/pyTorch/Detectron.pytorch/lib/datasets/data/cityscapes/label_info_coarse/train.txt'
save_path='/home/zhanwj/Desktop/pyTorch/Detectron.pytorch/lib/datasets/data/cityscapes/annotations/'
coarse_train='coarse_train.txt'
data_path='/home/zhanwj/Desktop/pyTorch/Dete... |
import math
def add(operator,x,y):
return x+y
def subtract(operator,x,y):
return x-y
def divide(operator,x,y):
return x/y
def multiply(operator,x,y):
return x*y
def power(operator,x,y):
return x**y
def card(start,end):
exp=0
for i in range(start,end):
... |
class Tumor:
def __init__(self,tumor, tumorType):
self.tumor = tumor
self.tumorType = tumorType |
def bissexto(x):
if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0:
return True
return False
def huluculu(x):
if x % 15 == 0:
return True
return False
def buluculu(x):
if x % 55 == 0 and bissexto(x):
return True
return False
f = True
a = input()
w... |
# -*- coding:UTF-8 -*-
"""
xvideos视频爬虫
https://www.xvideos.com/
@author: hikaru
email: hikaru870806@hotmail.com
如有问题或建议请联系
"""
import os
import re
import time
import traceback
from pyquery import PyQuery as pq
from common import *
COOKIE_INFO = {}
VIDEO_QUALITY = 2
ACTION_WHEN_BLOCK_HD_QUALITY = 2
CATEGORY_WHITELIST ... |
szam = int(input("Adj meg egy számot! "))
if szam < 0:
print("A megadott szám negatív!")
else:
print("A megadott szám nem negatív!")
print(" Itt a vége! ") |
# -*- encoding: utf-8 -*-
__author__ = "Chmouel Boudjnah <chmouel@chmouel.com>"
import httplib2
import os
import sys
import json
import pprint
import time
import datetime
import cloudlb.base
import cloudlb.consts
import cloudlb.errors
class CLBClient(httplib2.Http):
"""
Client class for accessing the CLB API.... |
# The python implementation which corresponds
# https://github.com/kaelzhang/gaia/blob/master/example/hello/controller/Greeter.js
import asyncio
def SayHello(helloRequest, HelloReply):
return HelloReply(message = f'Hello {helloRequest.name}')
async def DelayedSayHello(*args):
await asyncio.sleep(300)
r... |
class WyzeClientError(Exception):
"""Base class for Client errors"""
class WyzeRequestError(WyzeClientError):
"""Error raised when there's a problem with the request that's being submitted."""
class WyzeFeatureNotSupportedError(WyzeRequestError):
"""Error raised when the requested action on a device isn... |
import cleanup
import pdb
import random
class Dictogram(dict):
def __init__(self, word_text=None):
'''Everytime this dictogram class is instantiated word text is given'''
if word_text:
self.word_text = word_text
for word in self.word_text:
self.add_count(wor... |
"""A shim module for deprecated imports
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import types
class ShimModule(types.ModuleType):
def __init__(self, *args, **kwargs):
self._mirror = kwargs.pop("mirror")
super(ShimModule, s... |
"""
:py:class:`GlobalUtils` contains global utilities
=================================================
This software was developed for the SIT project.
If you use all or part of it, please give an appropriate acknowledgment.
Author Mikhail Dubrovin
"""
import sys
import numpy as np
def info_ndarr(nda, name='', fi... |
import tensorflow as tf
from ceiling_segmentation.UNET.VGG16.EncoderDecoder import EncoderDecoder
from ceiling_segmentation.utils.LoadData import LoadData
import matplotlib.pyplot as plt
import datetime
import numpy as np
import pathlib
tf.config.experimental.set_memory_growth(tf.config.experimental.list_physical_devi... |
#!/usr/bin/python3
'''python script'''
import requests
def count_words(subreddit, word_list):
'''function to check nbre of sub'''
requestpost = requests.get("https://www.reddit.com/r/{}/hot.json".format(
subreddit), headers={"User-Agent": "amine"})
if requestpost.status_code != 200:
return... |
# Generated by Django 2.1.3 on 2019-01-01 19:48
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 unittest
from spikeinterface.postprocessing import check_equal_template_with_distribution_overlap, TemplateSimilarityCalculator
from spikeinterface.postprocessing.tests.common_extension_tests import WaveformExtensionCommonTestSuite
class SimilarityExtensionTest(WaveformExtensionCommonTestSuite, unittest.Test... |
from fuzzy_control import RuddRuleBase, AccRuleBase, plot_fuzzy_set, defuzzyfication
from fuzzy_inputs import *
if __name__ == "__main__":
"""
This program is made for testing one of the
rule bases created in the exercise. It will plot
resultant FuzzySet and show defuzzyficated value of this
resultant FuzzySet.
... |
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras as keras
class MfHybridModel(object):
"""
Class for hybrid model object
Args:
num_user (int): The total number of users in the full data
item_dim (int): The dimension of item representation. Default is... |
# Generated by Django 3.1.1 on 2021-06-09 07:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('travelauth', '0039_travelrequest_tbl_pptr'),
]
operations = [
migrations.AddField(
model_name='travelrequest_tbl',
n... |
#!/usr/bin/python
'''
Simulation Visualiser for Embedded Cadmium
By: Ben Earle
ARSLab - Carleton University
This script will parse the I/O files and animate the pin values
for the duration of the simulation.
Note, if tkinter is not installed by default run the following
command in the te... |
__author__ = 'Pedram'
import nose
from graph import Graph
from graph_functions import *
def test_complete_C1():
g = Graph({'A':['B','D'],'B':['A'],'D':['A']})
assert is_complete(g) == False
def test_complete_C2():
g = Graph({'A':['B','D'],'B':['A','D'],'D':['A','B']})
assert is_complete(g) == True
de... |
package com.red.dwarf;
import com.google.gson.*;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Util {
// **********************************... |
#!python3
# -*- coding: utf-8 -*-
# Author: JustinHan
# Date: 2021-01-25
# Introduce: 正规方程求解线性回归系数
# Dependence
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.me... |
from typing import List, Dict, Any, Callable
import json
import re
import os
import errno
from collections import defaultdict
from tqdm import tqdm
from loader.Database import DBViewIndex, DBManager, DBView, DBDict, check_target_path
from loader.Actions import CommandType
from exporter.Mappings import AFFLICTION_TYPES... |
"""Upgrade User and Survey Objects
Revision ID: 823a9e3627a9
Revises: a5e33684a022
Create Date: 2021-04-06 10:16:13.980341
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '823a9e3627a9'
down_revision = 'a5e33684a022'
branch_labels = None
depends_on = None
def... |
# -*- coding: utf-8 -*-
"""
Created on 2020-02-24
@author: duytinvo
"""
from collections import Counter
from sklearn import metrics
from mlmodels.utils.special_tokens import PAD, SOT, EOT, UNK, NULL
sys_tokens = [PAD, SOT, EOT, UNK]
class APRF1:
@staticmethod
def sklearn(y_true, y_pred):
acc = metric... |
from collections import deque
class Circle:
"""
A circle to play a game of marbles
with the other elves in.
"""
def __init__(self, players, target, log=False):
self.log = log
self.marbles = deque([0])
self.target_marbles = target
self.players = [0 for _ in range(pl... |
"""
@Author: Joseph K. Nguyen
@Date: 02/22/2021
AnagramChecker.py
Anagram is defined as: when two strings are the same length and have same counts of all characters.
NOTE: This version doesn't do multiple same characters count.
"""
array1= ["cat", "tac"]
array2 = ["bad", "dab"]
array3 = ["test", "tset"]
array4= ["do... |
import numpy as np
@np.vectorize
def relu(x):
return max(x, 0)
def feedforward(inputs, w):
a = inputs # Сначала inputs
for i in range(0, len(w)):
a = np.append(a, 1)
# a = relu(np.dot(w[i], a))
a = np.tanh(np.dot(w[i], a))
return a
|
import sys
import string
import re
glide_regex = re.compile('{[a-z0-9]*}')
style_regex = re.compile('-[0-9]-')
comment_regex = re.compile('-- .*')
count_regex = re.compile('[0-9]$')
# primary stress, secondary stress, or unstressed
stress_regex = re.compile('[0-2]$')
A2P = {'AA':'5', 'AE':'3', 'AH':'6', 'AO':'53', 'A... |
# coding: utf8
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseForbidden
from dwebsocket import require_websocket
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from models import tomcat_status, tomcat_ur... |
# Generated by Django 3.1.1 on 2021-02-20 21:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='gamemodel',
name='year',
... |
"""constructs a daily time series for Finland of the daily change in COVID-19 tests.
API documentation: https://thl.fi/fi/tilastot-ja-data/aineistot-ja-palvelut/avoin-data/varmistetut-koronatapaukset-suomessa-covid-19-
"""
import json
import requests
import pandas as pd
def main():
url = "https://services7.arcgis... |
#!/usr/bin/python
import sys,cv2
import math
import numpy as np
import matplotlib.pyplot as plt
import cv2.cv as cv
# ----------------- LOAD IMAGE -------------------------
sIPath="./original"
sFPath="./filter"
sOPath="./result"
sImgID=sys.argv[1]
img = cv2.imread(sIPath+"/"+sImgID+".tif")
# ----------------- FILTE... |
import asyncio
import logging
import os
from .settings import BaseSettings
logger = logging.getLogger('foxglove.redis')
async def async_flush_redis(settings: BaseSettings):
from arq import create_pool
redis = await create_pool(settings.redis_settings)
await redis.flushdb()
await redis.close(close_c... |
from authentication import auth
from flask_restful import Resource
class Login(Resource):
@auth.login_required
def post(self):
"""
simply checks if provided creds match any records
"""
return {"username": auth.current_user().name}, 200 |
#!/usr/bin/env python3
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import WorkerOptions
from apac... |
#Take list as user input and print all names whi have grater than 5 letters
lst = [] #Empty list
n= int(input("enter list")) # Taking user input
for i in range(n):
name = str(input()) #Again user input for string type
lst.append(name) #Appending input st... |
"""
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
"""
import unittest
def check_two_numbers_add_up_to_target(array, target):
"""
Given a list... |
#Generators: generate sequence of values
#range() is a generator
#special keyword - yield
def make_list(num):
result= []
for i in range(num):#range is a generator
result.append(i*2)
return result
my_list = make_list(100)
#print(my_list)
#it is taking up space
print(list(range(100000))... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def external_func():
return 23
def _internal_func():
return 42
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 11:25:00 2019
@author: Administrator
"""
#导入包
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
#新建地图
map = Basemap()
#绘制海岸线
map.drawcoastlines()
#添加多个点
lons = [0, 10, -20, -20]
lats = [0, -10, 40, -20]
x, y = map(lons, lats)
map.scatter(x, y, ... |
import sys
import csv
import math
numParameters = int(sys.argv[3])
with open(sys.argv[2]) as model:
reader = csv.DictReader(model)
modeledData = [float(s["Modeled data"]) for s in reader]
with open(sys.argv[1]) as benchmark:
reader = csv.DictReader(benchmark)
benchmarkData = [float(s["Value"]) for s ... |
#!/usr/bin/python3
import datetime
import time
import glob
import os
import math
import cv2
import math
import numpy as np
import scipy.optimize
from lib.VideoLib import get_masks, find_hd_file_new, load_video_frames, sync_hd_frames
from lib.UtilLib import check_running, angularSeparation
from lib.CalibLib import rad... |
L = []
n = 1
while n < 99:
L.append(n)
n+=2
print(L)
print('dsfsdfsdfdsdf=====',len(L) / 2)
n = 0
sum = 0
while n < len(L) / 2:
print(L[n])
sum+=1
n+=1
print(sum)
|
import os
import re
import json
data_src = '/home/melody/develop/caffe-tensorflow/caffe_name.txt'
param_map = {'variance': 'moving_variance',
'scale': 'gamma',
'offset': 'beta',
'mean': 'moving_mean',
'weights': 'weights'}
psp_map = {
'1': '1',
'2': '2',
... |
#!/usr/bin/env python3.6
# Author: Eric Turgeon
# License: BSD
# Location for tests into REST API of FreeNAS
import unittest
import sys
import os
import xmlrunner
apifolder = os.getcwd()
sys.path.append(apifolder)
from functions import POST
from auto_config import results_xml
RunTest = True
TestName = "create group"
... |
from source.geometry.geometric_functions import GeometricFunctions
class Insulation(object):
@staticmethod
def return_insulation_single_element_area(diameter_strand, diameter_strand_with_insulation, total_winding_length,
number_of_elements, contact_correction_fac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.