repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
icbi-lab/miopy
miopy/correlation.py
<filename>miopy/correlation.py ############### #### AMYR ##### ############### import re from typing import DefaultDict from pandas.core.reshape.concat import concat import scipy.stats import pandas as pd from .R_utils import tmm_normalization, deg_edger, deg_limma_array, voom_normalization import numpy as np impor...
icbi-lab/miopy
miopy/data.py
import pandas as pd import numpy as np from os import path import io import numpy as np def _get_path_data(): return path.join(path.dirname(__file__), 'data') def get_target_query(method = "and", lTarget = []): #Build DB query: dbQ = "" lHeader = load_matrix_header() if method == "and": ...
icbi-lab/miopy
miopy/feature_selection.py
<reponame>icbi-lab/miopy from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier,GradientBoostingClassifier, RandomForestClassifier from sklearn.linear_model import LogisticRegression, RidgeClassifier from sklearn.svm import SVC # used for normalization from sklearn.preprocessing import StandardScaler from s...
icbi-lab/miopy
bin/mio_correlation.py
<gh_stars>0 import pandas as pd import argparse from miopy.correlation import (read_count, concat_matrix, all_methods, tmm_normal, voom_normal, get_mir_gene_ratio, header_list, intersection, gene_set_correlation, process_matrix_lis...
icbi-lab/miopy
miopy/multilabel_feature_selection.py
<reponame>icbi-lab/miopy import numpy as np import matplotlib.pyplot as plt from itertools import cycle from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier,GradientBoostingClassifier, RandomForestClassifier from sklearn.linear_mo...
alcorzheng/learn_python
Learn_pkgs/learn/BeautifulSoup/spider_ssq.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: 2018-03-14 # desc: 双色球开奖结果爬取 from bs4 import BeautifulSoup from Spiders.spiders.lottery.lottery_model import LotteryCNSSQ from Spiders.common import config, database, utils, utils_html def get_page_num(url, headers): """获取url总页数""" ...
alcorzheng/learn_python
Algorithms/algorithms/algorithms.py
<gh_stars>1-10 #!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: # desc: from Algorithms.algorithms import Sorts if __name__ == "__main__": sotr_list = [2, 8, 4, 9, 3, 6] print(Sorts.insertion_sort(sotr_list))
alcorzheng/learn_python
Spiders/spiders/blankchain/finance_eth.py
<filename>Spiders/spiders/blankchain/finance_eth.py<gh_stars>1-10 #!/usr/bin/python # -*- coding:utf-8 -*- """ @auth: alcorzheng<<EMAIL>> @file: finance_eth.py @time: 2018/4/315:24 @desc: ETH钱包地址财务统计 """ import requests from bs4 import BeautifulSoup def cal_ethorses(): # 以太马地址 ethorses_address = '0xf1c38359f...
alcorzheng/learn_python
Spiders/common/config.py
#!/usr/bin/python # -*- coding:utf-8 -*- """ @auth: alcorzheng<<EMAIL>> @file: config.py @time: 2018/4/109:47 @desc: 配置文件 """ # ------------------------------- # 数据库配置信息 DB_TYPE = 'postgresql' DB_NAME = 'zhengx_study' DB_USER = 'data_analysis' DB_PASS = '<PASSWORD>' DB_HOST = 'db.zhengx.xyz' DB_PORT = '5432' # -------...
alcorzheng/learn_python
Spiders/common/utils_html.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: 2018-03-14 # desc: HTML通用工具类 import requests #伪装成浏览器登陆,获取网页源代码 def getPage(url,headers): try: req = requests.get(url, headers=headers) req.raise_for_status() req.encoding = req.apparent_encoding return req...
alcorzheng/learn_python
Spiders/common/database.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: 2018-03-22 # desc: 数据库工具 from sqlalchemy import create_engine, and_ from sqlalchemy.orm import sessionmaker from Spiders.common import config class CommonDBExecutor(object): def __init__(self, db_url, table=None): """初始化""" ...
alcorzheng/learn_python
Test/pgsqlByPsycopg2.py
# /usr/bin/env python # -*- coding:utf-8 -*- import psycopg2 # 连接数据库 conn = psycopg2.connect("dbname=study_python user=study password=<PASSWORD> host=127.0.0.1 port=5432") # 创建cursor以访问数据库 cur = conn.cursor() # 创建表 cur.execute( 'CREATE TABLE Employee (' 'name varchar(80),' 'address varcha...
alcorzheng/learn_python
CrazyPythonFor163/crazyPy/class03/Class03_HomeWork.py
<filename>CrazyPythonFor163/crazyPy/class03/Class03_HomeWork.py # /usr/bin/env python # -*- coding:utf-8 -*- # 画美国国旗 import turtle import math # 自定义参数 baselen = 100 af_Color_White="#FFFFFF" af_Color_Red="#B22234" af_Color_Blue="#3C3B6E" # 国旗固定参数 af_Stripe_Length=1.9*baselen af_Stripe_Width=0.0769*baselen af_StarAr...
alcorzheng/learn_python
Learn_pkgs/learn_pkgs.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: # desc: from Learn_pkgs.learn.pyecharts import test if __name__ == "__main__": test
alcorzheng/learn_python
Spiders/spiders/lottery/lottery_cn_dlt.py
#!/usr/bin/python # -*- coding:utf-8 -*- """ @auth: alcorzheng<<EMAIL>> @file: lottery_cn_dlt.py @time: 2018/4/1013:59 @desc: """
alcorzheng/learn_python
CrazyPythonFor163/test/test.py
# /usr/bin/env python # -*- coding:utf-8 -*- import math # 自定义参数 baselen = 500 af_color_white="#FFFFFF" af_color_red="#B22234" af_color_blue="#3C3B6E" # 国旗固定参数 af_stripe_length=1.9*baselen af_stripe_width=0.0769*baselen af_stararea_length=af_stripe_length*2/5 af_stararea_width=af_stripe_width*7 ad_star_high=af_star...
alcorzheng/learn_python
Spiders/spiders/lottery/lottery_model.py
<filename>Spiders/spiders/lottery/lottery_model.py #!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: # desc: from sqlalchemy import Column, Integer, String, Date, Numeric from sqlalchemy.ext.declarative import declarative_base from Spiders.common import utils # 创建对象的基类: Base = declarative_...
alcorzheng/learn_python
Algorithms/algorithms/Sorts.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: 2018-03-19 # desc: 排序算法 """ 插入排序 """ def insertion_sort(lists): lists_len = len(lists) for i in range(1, lists_len): key = lists[i] j = i-1 while j >= 0: if lists[j] > key: lists[j+...
alcorzheng/learn_python
Test/envparam.py
<gh_stars>1-10 #!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: # desc: 全局配置文件 import re import os import tempfile global _env CONF_FILE_URL = "config/lottery.properties" def _init_(): """初始化""" global _env _env = Properties(CONF_FILE_URL).properties def setVal(key, value, ...
alcorzheng/learn_python
Learn_pkgs/learn/BeautifulSoup/spider_dlt.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: 2018-03-14 # desc: 大乐透开奖结果爬取 from bs4 import BeautifulSoup from Spiders.spiders.lottery import lottery_model from Spiders.common import config, database, utils, utils_html def get_page_num(url, headers): """获取url总页数""" soup = Beauti...
alcorzheng/learn_python
Spiders/spiders/lottery/lottery_cn_ssq.py
<gh_stars>1-10 #!/usr/bin/python # -*- coding:utf-8 -*- """ @auth: alcorzheng<<EMAIL>> @file: lottery_cn_ssq.py @time: 2018/4/1013:59 @desc: """ from requests_html import HTMLSession session = HTMLSession() def spiders_data(): """"按照规则爬取数据""" response = session.get('http://kaijiang.zhcw.com/zhcw/html/ssq/li...
alcorzheng/learn_python
Learn_pkgs/learn/tushare/GetDataByID.py
# /usr/bin/env python # -*- coding:utf-8 -*- import tushare as ts data=ts.get_hist_data('300032') print(data)
alcorzheng/learn_python
Spiders/common/utils.py
<gh_stars>1-10 #!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: 2018-03-15 # desc: 基础工具包 def obj2int(val): """整数转换处理,空值转为0""" if val: return int(val) else: return 0 def to_dict(self): """将sqlAlchemy中的对象转换为dict""" return {c.name: getattr(self, c.name, Non...
alcorzheng/learn_python
CrazyPythonFor163/crazyPy/class03/Class03_DrawStar.py
<reponame>alcorzheng/learn_python # /usr/bin/env python # -*- coding:utf-8 -*- import turtle turtle.forward(100) turtle.right(144) turtle.forward(100) turtle.right(144) turtle.forward(100) turtle.right(144) turtle.forward(100) turtle.right(144) turtle.forward(100)
alcorzheng/learn_python
Spiders/spiders.py
#!/usr/bin/python # -*- coding:utf-8 -*- # auth: alcorzheng<<EMAIL>> # date: # desc: from Learn_pkgs.learn.BeautifulSoup import spider_ssq if __name__ == "__main__": print("-----开始-----") spider_ssq.ins_data_ssq() # spider_dlt.ins_data_dlt() print("-----结束-----")
diadochos/quora-scraper
setup.py
<filename>setup.py from setuptools import setup def readme(): with open('README.md') as f: README = f.read() return README setup( name = 'quora-scraper', packages = ['quora_scraper'], version = '1.1.3', license='MIT', description = "Python based code to scrap and download data ...
diadochos/quora-scraper
quora_scraper/scraper.py
<gh_stars>0 # __main__.py DEBUG = 1 import os import re import subprocess import sys import time import ast import csv import json import pathlib from pathlib import Path import random import userpaths import dateparser import argparse from datetime import datetime, timedelta from bs4 import BeautifulSoup from selenium...
l0nax/gitlint
qa/samples/user_rules/incorrect_linerule/my_line_rule.py
from gitlint.rules import LineRule class MyUserLineRule(LineRule): id = "UC2" name = "my-line-rule" # missing validate method, missing target attribute
l0nax/gitlint
gitlint/tests/test_cache.py
<gh_stars>0 # -*- coding: utf-8 -*- from gitlint.tests.base import BaseTestCase from gitlint.cache import PropertyCache, cache class CacheTests(BaseTestCase): class MyClass(PropertyCache): """ Simple class that has cached properties, used for testing. """ def __init__(self): Property...
l0nax/gitlint
examples/my_line_rules.py
# -*- coding: utf-8 -*- from gitlint.rules import LineRule, RuleViolation, CommitMessageTitle from gitlint.options import ListOption """ Full details on user-defined rules: https://jorisroovers.com/gitlint/user_defined_rules The SpecialChars class below is an example of a user-defined LineRule. Line rules are gitlin...
l0nax/gitlint
gitlint/rules.py
# pylint: disable=inconsistent-return-statements import copy import logging import re from gitlint.options import IntOption, BoolOption, StrOption, ListOption, RegexOption from gitlint.utils import sstr class Rule(object): """ Class representing gitlint rules. """ options_spec = [] id = None name = N...
l0nax/gitlint
gitlint/tests/test_display.py
# -*- coding: utf-8 -*- try: # python 2.x from StringIO import StringIO except ImportError: # python 3.x from io import StringIO try: # python 2.x from mock import patch except ImportError: # python 3.x from unittest.mock import patch # pylint: disable=no-name-in-module, import-error...
l0nax/gitlint
gitlint/tests/config/test_config_precedence.py
# -*- coding: utf-8 -*- try: # python 2.x from StringIO import StringIO except ImportError: # python 3.x from io import StringIO from click.testing import CliRunner try: # python 2.x from mock import patch except ImportError: # python 3.x from unittest.mock import patch # pylint: dis...
l0nax/gitlint
gitlint/tests/contrib/rules/test_signedoff_by.py
# -*- coding: utf-8 -*- from gitlint.tests.base import BaseTestCase from gitlint.rules import RuleViolation from gitlint.contrib.rules.signedoff_by import SignedOffBy from gitlint.config import LintConfig class ContribSignedOffByTests(BaseTestCase): def test_enable(self): # Test that rule can be enable...
l0nax/gitlint
gitlint/tests/git/test_git_context.py
# -*- coding: utf-8 -*- try: # python 2.x from mock import patch, call except ImportError: # python 3.x from unittest.mock import patch, call # pylint: disable=no-name-in-module, import-error from gitlint.tests.base import BaseTestCase from gitlint.git import GitContext class GitContextTests(BaseTe...
l0nax/gitlint
gitlint/tests/rules/test_meta_rules.py
<filename>gitlint/tests/rules/test_meta_rules.py<gh_stars>0 # -*- coding: utf-8 -*- from gitlint.tests.base import BaseTestCase from gitlint.rules import AuthorValidEmail, RuleViolation class MetaRuleTests(BaseTestCase): def test_author_valid_email_rule(self): rule = AuthorValidEmail() # valid em...
l0nax/gitlint
gitlint/__init__.py
__version__ = "0.14.0dev"
l0nax/gitlint
gitlint/tests/samples/user_rules/parent_package/my_commit_rules.py
<filename>gitlint/tests/samples/user_rules/parent_package/my_commit_rules.py # -*- coding: utf-8 -*- from gitlint.rules import CommitRule class MyUserCommitRule(CommitRule): name = u"my-user-cömmit-rule" id = "UC2" options_spec = [] def validate(self, _commit): return []
l0nax/gitlint
qa/samples/user_rules/extra/extra_rules.py
# -*- coding: utf-8 -*- from gitlint.rules import CommitRule, RuleViolation, ConfigurationRule from gitlint.options import IntOption, StrOption, ListOption from gitlint.utils import sstr class GitContextRule(CommitRule): """ Rule that tests whether we can correctly access certain gitcontext properties """ na...
l0nax/gitlint
gitlint/tests/samples/user_rules/my_commit_rules.py
<reponame>l0nax/gitlint<filename>gitlint/tests/samples/user_rules/my_commit_rules.py # -*- coding: utf-8 -*- from gitlint.rules import CommitRule, RuleViolation from gitlint.options import IntOption class MyUserCommitRule(CommitRule): name = u"my-üser-commit-rule" id = "UC1" options_spec = [IntOption('vi...
l0nax/gitlint
gitlint/hooks.py
<filename>gitlint/hooks.py import io import shutil import os import stat from gitlint.utils import DEFAULT_ENCODING from gitlint.git import git_hooks_dir COMMIT_MSG_HOOK_SRC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "files", "commit-msg") COMMIT_MSG_HOOK_DST_PATH = "commit-msg" GITLINT_HOOK_IDE...
l0nax/gitlint
gitlint/tests/rules/test_title_rules.py
# -*- coding: utf-8 -*- from gitlint.tests.base import BaseTestCase from gitlint.rules import TitleMaxLength, TitleTrailingWhitespace, TitleHardTab, TitleMustNotContainWord, \ TitleTrailingPunctuation, TitleLeadingWhitespace, TitleRegexMatches, RuleViolation class TitleRuleTests(BaseTestCase): def test_max_li...
l0nax/gitlint
gitlint/tests/config/test_config.py
<gh_stars>0 # -*- coding: utf-8 -*- try: # python 2.x from mock import patch except ImportError: # python 3.x from unittest.mock import patch # pylint: disable=no-name-in-module, import-error from gitlint import rules from gitlint.config import LintConfig, LintConfigError, LintConfigGenerator, GITLIN...
l0nax/gitlint
gitlint/tests/samples/user_rules/incorrect_linerule/my_line_rule.py
<gh_stars>100-1000 # -*- coding: utf-8 -*- from gitlint.rules import LineRule class MyUserLineRule(LineRule): id = "UC2" name = "my-lïne-rule" # missing validate method, missing target attribute
l0nax/gitlint
gitlint/tests/test_utils.py
# -*- coding: utf-8 -*- from gitlint import utils from gitlint.tests.base import BaseTestCase try: # python 2.x from mock import patch except ImportError: # python 3.x from unittest.mock import patch # pylint: disable=no-name-in-module, import-error class UtilsTests(BaseTestCase): def tearDown...
l0nax/gitlint
gitlint/tests/samples/user_rules/import_exception/invalid_python.py
# flake8: noqa # This is invalid python code which will cause an import exception class MyObject:
l0nax/gitlint
examples/my_configuration_rules.py
# -*- coding: utf-8 -*- from gitlint.rules import ConfigurationRule from gitlint.options import IntOption """ Full details on user-defined rules: https://jorisroovers.com/gitlint/user_defined_rules The ReleaseConfigurationRule class below is an example of a user-defined ConfigurationRule. Configuration rules are gi...
l0nax/gitlint
gitlint/cache.py
<filename>gitlint/cache.py class PropertyCache(object): """ Mixin class providing a simple cache. """ def __init__(self): self._cache = {} def _try_cache(self, cache_key, cache_populate_func): """ Tries to get a value from the cache identified by `cache_key`. If no value is fou...
vinayak19th/Brevis-2.0
brevis/predict/apps.py
<reponame>vinayak19th/Brevis-2.0<gh_stars>0 from django.apps import AppConfig from .paper import get_articles class PredictConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'predict'
vinayak19th/Brevis-2.0
brevis/predict/admin.py
<filename>brevis/predict/admin.py from django.contrib import admin from .models import Article class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'body',) prepopulated_fields = {'slug': ('title',)} admin.site.register(Article, ArticleAdmin)
vinayak19th/Brevis-2.0
brevis/predict/startup.py
from .models import Article import os import signal import sys from .models import Article from .paper import get_articles def startup_hook(): print("Clearing DB old") Article.objects.all().delete() print("Gathering articles") articles = get_articles() for title in articles: a = Arti...
vinayak19th/Brevis-2.0
brevis/predict/forms.py
<gh_stars>0 from django import forms """ Class based form model to extend usage to add ability to save summaries into database""" class WebsiteForm(forms.Form): weblink = forms.URLField(label = 'Paste url here (with https)')
vinayak19th/Brevis-2.0
brevis/predict/bart.py
import requests import json from transformers import BartTokenizer class SummaryModel: model = "facebook/bart-large-xsum" tokenizer = BartTokenizer.from_pretrained(model) print("Tokenizer loaded") def __init__(self): print("model loaded") def preprocess(self,text,maxlen): """F...
vinayak19th/Brevis-2.0
brevis/tools/trie.py
import os import string import pickle import json from pathlib import Path import argparse from tqdm import tqdm punctuations = string.punctuation + "'' “”'-" class TrieNode: def __init__(self): self.is_end = False self.children = {} class Trie: def __init__(self): self.root = TrieNo...
vinayak19th/Brevis-2.0
brevis/predict/models.py
<filename>brevis/predict/models.py from django.db import models from django.template.defaultfilters import slugify from django.urls import reverse from .summarizer import summarizer class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() body_summarized = models.Tex...
vinayak19th/Brevis-2.0
brevis/predict/urls.py
<reponame>vinayak19th/Brevis-2.0 from django.urls import path from . import views urlpatterns = [ path('', views.ArticleListView.as_view(), name='article_list'), path('<slug:slug>', views.ArticleDetailView.as_view(), name='article_detail') #path('', views.index, name='index') ] from .startup import run_s...
vinayak19th/Brevis-2.0
brevis/predict/migrations/0001_initial.py
# Generated by Django 3.2 on 2021-04-14 05:28 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.BigAutoField...
vinayak19th/Brevis-2.0
brevis/predict/views.py
from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import DetailView, ListView from .models import Article from .paper import get_articles def index(request): hot_articles = get_articles() return render(request, 'predict/index.html', { "hot_articles" :...
vinayak19th/Brevis-2.0
brevis/predict/paper.py
import random import os import sys import newspaper from tools.trie import * import requests from bs4 import BeautifulSoup from newsapi import NewsApiClient # NUM_POPULAR_URLS = 3 # NUM_EACH_POPULAR = 2 # FORGET_ARTICLE = False NUM_ARTICLES = 20 BASE_DIR = Path(__file__).resolve().parent.parent SAVED_TRIE_DIR = B...
vinayak19th/Brevis-2.0
brevis/predict/summarizer.py
<filename>brevis/predict/summarizer.py from .bart import SummaryModel def summarizer(text,maxlen=200): model = SummaryModel() summary = model.pred(text,maxlen=maxlen) if (len(summary[0])>2): summary = summary[0] print("Summary:",len(summary)) print("Summary[0]:",len(summary[0])) return ...
milebag/pythons
app.py
#-*- coding: UTF-8 -*- import socket,select import sys import threading from multiprocessing import Process class Proxy: def __init__(self,soc): print("init") self.client,_=soc.accept() print("accept") self.target=None self.request_url=None self.BUFSIZE=4096 s...
skdys/thermalspin
old_sph_version/set_simulation.py
#!/usr/bin/env python3 from thermalspin.set_simulation import set_simulation set_simulation()
skdys/thermalspin
old_sph_version/thermalspin/dynamic_simulation.py
<filename>old_sph_version/thermalspin/dynamic_simulation.py #!/usr/bin/env python3 """ User interface for initializing and run simulations """ import getopt import sys from thermalspin.heisenberg_simulation import init_simulation_tilted, init_simulation_random, init_simulation_aligned, \ run_simulation from ther...
skdys/thermalspin
old_sph_version/thermalspin/heisenberg_system.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Classical Heisenberg model Monte Carlo simulator """ import numpy as np from numba import jit from skdylib.spherical_coordinates import sph_dot, sph2xyz, sph_urand class HeisenbergSystem: """ This class represent a system described by an Heisenberg Hamilton...
skdys/thermalspin
old_sph_version/thermalspin/heisenberg_simulation.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Classical Heisenberg model Monte Carlo simulator """ import json import os import shutil import time import numpy as np from kent_distribution.kent_distribution import kent2 from skdylib.spherical_coordinates import sph_urand, xyz2sph from thermalspin.heisenberg_sy...
skdys/thermalspin
src/thermalspin/data_analysis.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Show simple data of the simulation """ import colorsys import os import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from numba import jit from skdylib.spherical_coordinates import xyz2sph SIMULATIONS_DIRECTORY = "./simulation...
skdys/thermalspin
src/set_simulation.py
#!/usr/bin/env python3 """ Wrapper for the real program """ from thermalspin.set_simulation import set_simulation set_simulation()
skdys/thermalspin
old_sph_version/dynamic_simulation.py
<gh_stars>1-10 #!/usr/bin/env python3 from thermalspin.dynamic_simulation import dynamic_simulation dynamic_simulation()
skdys/thermalspin
src/thermalspin/set_simulation.py
#!/usr/bin/env python3 """ Run multiple instance of Heisenberg """ import getopt import os import sys import time from multiprocessing import pool, cpu_count import numpy as np from skdylib.counter import Counter from thermalspin.read_config import read_config_file from thermalspin.simulation import init_simulation_...
skdys/thermalspin
src/kent_distribution/kent_distribution.py
<filename>src/kent_distribution/kent_distribution.py #!/usr/bin/env python """ The algorithms here are partially based on methods described in: [The Fisher-Bingham Distribution on the Sphere, <NAME> Journal of the Royal Statistical Society. Series B (Methodological) Vol. 44, No. 1 (1982), pp. 71-80 Published by: Wiley ...
skdys/thermalspin
src/dynamic_simulation.py
<reponame>skdys/thermalspin #!/usr/bin/env python3 """ Wrapper for the real program """ from thermalspin.dynamic_simulation import dynamic_simulation dynamic_simulation()
skdys/thermalspin
old_sph_version/skdylib/spherical_coordinates.py
<reponame>skdys/thermalspin #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Mathematical utility functions """ import numpy as np from numba import jit @jit(nopython=True, cache=True) def xyz2sph(v): """ Convert a unit vector from cartesian coordinates to spherical coordinates :param v: unit vector ...
skdys/thermalspin
src/thermalspin/read_config.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Read the configuration file """ import json import os CONFIG_FILE_NAME = "config.json" def read_config_file(): if os.path.isfile(CONFIG_FILE_NAME): config_file = open(CONFIG_FILE_NAME, "r") config = json.load(config_file) else: rai...
skdys/thermalspin
src/thermalspin/spin_system.py
<gh_stars>1-10 #!/usr/bin/env python3 """ Classical Spin System Monte Carlo simulator """ import numpy as np from numba import jit from skdylib.spherical_coordinates import xyz_sph_urand USE_NUMBA = True class SpinSystem: """ This class represent a spin system with Heisenberg interaction, DMI and Zeeman t...
lucasjurado/Alura-IO
contatos_uteis.py
<gh_stars>0 import csv, pickle, json from contato import Contato def csv_para_contatos(caminho, encoding='latin_1'): contatos = [] with open(caminho, encoding=encoding) as arquivo: leitor = csv.reader(arquivo) for linha in leitor: id = linha[0] nome = l...
lucasjurado/Alura-IO
contato.py
class Contato: def __init__(self, id, nome, email): self.id = id self.nome = nome self.email = email # Pensando em uma abordagem mais orientada a objetos, podemos utilizar um objeto de acesso a dados que fica # sendo responsável pela comunicação do mundo Python com o mundo dos arquivos. # ...
lucasjurado/Alura-IO
main.py
<gh_stars>0 # Ao abrir o arquivo com uma codificação diferente da que ele foi escrito, alguns caracteres podem apresentar erros # try/finally é usado para certificar que mesmo que houver algum erro no processo indentado try, o arquivo será fechado import contatos_uteis try: contatos = contatos_uteis.csv_para_cont...
lucasjurado/Alura-IO
testa_escrita.py
# Sempre que abrimos algum arquivo em modo w, o Python vai truncar o arquivo, isto é, limpará seu conteúdo. # Para adicionar conteúdo a um arquivo sem apagar o que já está escrito, temos que utilizar o modo a. # (+) --> mode de atualização do arquivo arquivo_contatos = open('contatos-lista.csv', encoding='latin_1', mo...
dpoulopoulos/forma
forma/detector.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/detector.ipynb (unless otherwise specified). __all__ = ['FormatDetector'] # Cell import numpy as np import pandas as pd from typing import Any, Dict, Callable from tqdm import tqdm from .judge import FormatJudge from .utils import PatternGenerator # Cell class Format...
dpoulopoulos/forma
forma/utils.py
<gh_stars>0 # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/utils.ipynb (unless otherwise specified). __all__ = ['PatternGenerator'] # Cell import re from typing import Tuple, Any from itertools import groupby from collections import defaultdict # Cell class PatternGenerator: """Generates a generic pattern give...
dpoulopoulos/forma
forma/_nbdev.py
<gh_stars>0 # AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"FormatDetector": "detector.ipynb", "FormatJudge": "judge.ipynb", "PatternGenerator": "utils.ipynb"} modules = ["detector.py", "judge.py", "utils.py"] doc...
dpoulopoulos/forma
forma/judge.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/judge.ipynb (unless otherwise specified). __all__ = ['FormatJudge'] # Cell import heapq import numpy as np from typing import Any, List from nltk.lm import MLE from nltk.util import ngrams from nltk.lm.preprocessing import flatten from nltk.lm.preprocessing import pad...
lig/picket2014
picket/documents.py
<gh_stars>1-10 from datetime import datetime from django.db.models import permalink from mongoengine.document import Document from mongoengine.fields import (SequenceField, StringField, ListField, ReferenceField, DateTimeField) from users.documents import User class Project(Document): meta = { 'orde...
lig/picket2014
users/management/commands/picketuseradd.py
<reponame>lig/picket2014<gh_stars>1-10 from django.core.management.base import BaseCommand from ...documents import User class Command(BaseCommand): args = '<email> <display_name> <password>' help = 'Creates picket admin user' def handle(self, *args, **options): email, display_name, password = a...
lig/picket2014
users/auth.py
<reponame>lig/picket2014 from .documents import User class Backend(object): def authenticate(self, username=None, email=None, password=None): email = User.normalize_email(username or email) user = User.objects(email=email.lower()).first() if user and password and user.check_password(pass...
lig/picket2014
picket/settings/local_sample.py
from mongoengine import connect # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-' # SECURITY WARNING: don't run with debug turned on in production!...
lig/picket2014
picket/settings/dist.py
<reponame>lig/picket2014 """ Django settings for picket project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.pat...
lig/picket2014
picket/forms.py
from django import forms from .documents import Project class ProjectForm(forms.Form): name = forms.CharField() class IssueForm(forms.Form): project = forms.ModelChoiceField(queryset=Project.objects.all()) subject = forms.CharField() text = forms.CharField(required=False, widget=forms.Textarea) ...
lig/picket2014
users/documents.py
from django.utils.translation import ugettext_lazy as _ from mongoengine.django.auth import make_password, check_password from mongoengine.django.utils import datetime_now from mongoengine.document import Document from mongoengine.fields import (StringField, EmailField, DateTimeField, BooleanField) class User(Doc...
lig/picket2014
users/views.py
from actionviews.base import TemplateView from actionviews.decorators import action_decorator from django.contrib.auth.decorators import login_required from mongoengine.django.shortcuts import get_document_or_404 from .documents import User class UserView(TemplateView): @action_decorator(login_required) def...
lig/picket2014
picket/context_processors.py
<gh_stars>1-10 from .documents import Project def projects(request): return {'projects': Project.objects.all()}
lig/picket2014
users/urls.py
<reponame>lig/picket2014 from django.conf.urls import patterns, include, url from users.views import UserView urlpatterns = patterns('', url(r'^', include('django.contrib.auth.urls')), url(r'^profile/', include(UserView.urls)), )
lig/picket2014
picket/settings/__init__.py
from .dist import * try: from .local import * except ImportError: from .local_sample import * from warnings import warn warn('Cannot import local settings. Using local_sample instead.')
lig/picket2014
picket/urls.py
<reponame>lig/picket2014 from django.conf.urls import patterns, include, url from .views import ProjectView, IssueView urlpatterns = patterns('', url(r'^', include(ProjectView.urls)), url(r'^', include(IssueView.urls)), url(r'^accounts/', include('users.urls')), )
lig/picket2014
picket/views.py
from actionviews import TemplateView from actionviews.decorators import action_decorator, child_view from django.contrib.auth.decorators import login_required from django.shortcuts import redirect from mongoengine.django.shortcuts import get_document_or_404 from .documents import Issue, Project from .forms import Issu...
dreamorosi/quip-spreadsheet
quip_spreadsheet/quip.py
<gh_stars>0 from __future__ import annotations import logging from typing import Any, List, Dict, Optional, Union from json.decoder import JSONDecodeError from dataclasses import dataclass, field from enum import Enum import xml.etree.ElementTree import requests from requests.exceptions import Timeout, ConnectionErr...
dreamorosi/quip-spreadsheet
tests/test_quip_client.py
import os import unittest from copy import deepcopy from xml.etree.ElementTree import Element import requests_mock from requests.exceptions import ConnectTimeout, ConnectionError from quip.quip import ( QuipClient, QuipPage, QuipRow, QuipSearchResults, QuipSpreadsheetClientException, API_ROUTE...
dreamorosi/quip-spreadsheet
tests/constants.py
<gh_stars>0 QUIP_ACCESS_TOKEN = "<KEY> # This is a fake token :D QUIP_BASE_URL = "https://platform.quip.com" ENV = "DEBUG" LOGS_PREFIX = ":quip.quip:" USER_JSON = { "name": "<NAME>", "id": "1234", "is_robot": False, "affinity": 0.0, "desktop_folder_id": "abc1234", "archive_folder_id": "abc5678",...
MainTime/MotionDetection
main.py
import cv2 def difference(value0, value1): return value1 - value0 def find_movement(bild1, bild2): bild1 = convert_to_grayscale(bild1) bild2 = convert_to_grayscale(bild2) bild1 = cv2.GaussianBlur(bild1, (21, 21), 0) bild2 = cv2.GaussianBlur(bild2, (21, 21), 0) # Differenz zu 2 Bildern berech...
daoluan/Leaderboard-python
Leaderboard.py
<filename>Leaderboard.py # -*- coding: utf-8 -*- #!/usr/bin/python import redis class Leaderboard: def __init__(self,host,port,key,db): self.host = host self.port = port self.key = key self.db = db self.r = redis.StrictRedis(host=self.host,port=self.port,db=self.db) d...