hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 11
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 251 | max_stars_repo_name stringlengths 4 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 251 | max_issues_repo_name stringlengths 4 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 251 | max_forks_repo_name stringlengths 4 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.05M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.04M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
00214dc954dea8b8ef76726b14c1872ccfd1e59a | 799 | py | Python | robotarm/armservice/app.py | AmidBidee/Robot-Arm | cfacfc779b2f025846e9748167bcfb15ce207923 | [
"MIT"
] | 1 | 2022-03-27T20:09:10.000Z | 2022-03-27T20:09:10.000Z | robotarm/armservice/app.py | AmidBidee/Robot-Arm | cfacfc779b2f025846e9748167bcfb15ce207923 | [
"MIT"
] | 4 | 2022-03-25T03:45:10.000Z | 2022-03-29T14:31:16.000Z | robotarm/armservice/app.py | AmidBidee/RobotArm | cfacfc779b2f025846e9748167bcfb15ce207923 | [
"MIT"
] | null | null | null | #!/usr/bin/python3
"""
RobotArm API service config file
"""
import pathlib
from robotarm.armservice.views import api_views
from flask import (
Flask,
make_response,
jsonify
)
from robotarm.armservice import getenv
# initialize flask app
app = Flask(__name__)
# register/mount blueprint
app.register_blueprint(api_views)
# allow missing trailing
app.url_map.strict_slashes = False
if __name__ == '__main__':
host = getenv("ARM_API_HOST", "0.0.0.0")
port = getenv("ARM_API_PORT", "5555")
app.run(host=host, port=port)
| 17.755556 | 47 | 0.677096 |
0023e5b95c57b280f82e4d979d1eecb37cba4ae9 | 4,685 | py | Python | xbrr/edinet/reader/element_schema.py | 5laps2go/xbrr | 4c0824b53bfe971111d60e6c1ff4e36f4f4845a3 | [
"MIT"
] | null | null | null | xbrr/edinet/reader/element_schema.py | 5laps2go/xbrr | 4c0824b53bfe971111d60e6c1ff4e36f4f4845a3 | [
"MIT"
] | null | null | null | xbrr/edinet/reader/element_schema.py | 5laps2go/xbrr | 4c0824b53bfe971111d60e6c1ff4e36f4f4845a3 | [
"MIT"
] | null | null | null | from xbrr.base.reader.base_element_schema import BaseElementSchema
from bs4.element import NavigableString, Tag
import bs4
| 41.096491 | 229 | 0.56841 |
0024cde788e4fc1c63bad501dddfdfc712994f43 | 817 | py | Python | app/models.py | james-muriithi/news-hub | 6f0fee2ab6be5bba86c4309050592e000859f8db | [
"Unlicense"
] | null | null | null | app/models.py | james-muriithi/news-hub | 6f0fee2ab6be5bba86c4309050592e000859f8db | [
"Unlicense"
] | null | null | null | app/models.py | james-muriithi/news-hub | 6f0fee2ab6be5bba86c4309050592e000859f8db | [
"Unlicense"
] | null | null | null | from datetime import datetime
| 27.233333 | 103 | 0.623011 |
0024d2528361880227a045d4f7462059c46deebc | 661 | py | Python | post/migrations/0003_auto_20201018_1851.py | hieudmg/django_bloom | 1c244a2f753ed6babb710c83bfd7c3610fef9bb4 | [
"MIT"
] | null | null | null | post/migrations/0003_auto_20201018_1851.py | hieudmg/django_bloom | 1c244a2f753ed6babb710c83bfd7c3610fef9bb4 | [
"MIT"
] | null | null | null | post/migrations/0003_auto_20201018_1851.py | hieudmg/django_bloom | 1c244a2f753ed6babb710c83bfd7c3610fef9bb4 | [
"MIT"
] | null | null | null | # Generated by Django 3.1 on 2020-10-18 11:51
from django.conf import settings
from django.db import migrations
| 23.607143 | 66 | 0.591528 |
002d0e1349cf357ca18a823230bd151a88d70277 | 70,946 | py | Python | stackchat/parse/html/transcript_day_test.py | jeremybanks/ChatExchange | e350de944d0f221a9b2afc545bf60ae309e402b6 | [
"Apache-2.0"
] | 3 | 2017-12-27T02:40:06.000Z | 2018-04-21T00:28:31.000Z | stackchat/parse/html/transcript_day_test.py | jeremybanks/ChatExchange | e350de944d0f221a9b2afc545bf60ae309e402b6 | [
"Apache-2.0"
] | 1 | 2017-12-11T22:45:13.000Z | 2020-09-04T17:49:41.000Z | stackchat/parse/html/transcript_day_test.py | jeremybanks/ChatExchange | e350de944d0f221a9b2afc545bf60ae309e402b6 | [
"Apache-2.0"
] | 1 | 2018-05-08T22:17:58.000Z | 2018-05-08T22:17:58.000Z | from .transcript_day import *
EXAMPLE_DATA = r'''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Charcoal HQ - 2017-11-17 (page 2 of 4)</title>
<link rel="shortcut icon" href="//cdn.sstatic.net/stackexchange/img/favicon.ico?v=da"><link rel="apple-touch-icon" href="//cdn.sstatic.net/stackexchange/img/apple-touch-icon.png?v=da"><link rel="search" type="application/opensearchdescription+xml" title="Chat for chat.stackexchange.com" href="/opensearch.xml">
<link rel="canonical" href="/transcript/11540/2017/11/17/1-2" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="//cdn-chat.sstatic.net/chat/Js/master-chat.js?v=f1e5ed9ea207"></script>
<link rel="stylesheet" href="//cdn-chat.sstatic.net/chat/css/chat.stackexchange.com.css?v=7d154b0411cf">
<script type="text/javascript">
function IMAGE(f) { return ("//cdn-chat.sstatic.net/chat/img/" + f); }
</script>
<script type="text/javascript">
$(function() {
initTranscript(true,
1251, true,
true, 11540,
true);
popupDismisser();
});
</script>
</head>
<body id="transcript-body">
<div id="container">
<div id="main">
<a href="/transcript/11540/2013/11/16" class="button noprint" title="2013-11-16">« first day (1461 days earlier)</a>
<a href="/transcript/11540/2017/11/16" class="button noprint" rel="prev" title="2017-11-16">← previous day</a>
<link rel="prev" title="2017-11-16" href="/transcript/11540/2017/11/16" />
<a href="/transcript/11540/2017/11/18" class="button noprint" rel="next" title="2017-11-18">next day →</a>
<link rel="next" title="2017-11-18" href="/transcript/11540/2017/11/18" />
<a href="/transcript/11540/2017/11/22" class="button noprint" title="2017-11-22"> last day (5 days later) »</a>
<div class="clear-both"></div>
<div class="clear-both"></div><div class="pager"><a href="/transcript/11540/2017/11/17/0-1"><span class="page-numbers">00:00 - 01:00</span></a><span class="page-numbers current">01:00 - 02:00</span><a href="/transcript/11540/2017/11/17/2-13"><span class="page-numbers">02:00 - 13:00</span></a><a href="/transcript/11540/2017/11/17/13-24"><span class="page-numbers">13:00 - 00:00</span></a></div><div class="clear-both"></div>
<br/>
<div id="transcript">
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:00 AM</div>
<div class="message" id="message-41197805">
<a name="41197805" href="/transcript/11540?m=41197805#41197805"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
<div class="onebox ob-image"><a rel="nofollow noopener noreferrer" href="//i.stack.imgur.com/mdGKA.jpg"><img src="//i.stack.imgur.com/mdGKA.jpg" class="user-image" alt="user image" /></a></div>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41197807">
<a name="41197807" href="/transcript/11540?m=41197807#41197807"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
and this :)
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41197831">
<a name="41197831" href="/transcript/11540?m=41197831#41197831"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Mhm
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-120914">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/WyV1l.png?s=16&g=1" alt="SmokeDetector" />
</div>
<div class="username"><a href="/users/120914/smokedetector" title="SmokeDetector">SmokeDetector</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41197902">
<a name="41197902" href="/transcript/11540?m=41197902#41197902"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Merged SmokeDetector <a href="https://github.com/Charcoal-SE/SmokeDetector/pull/1236" rel="nofollow noopener noreferrer">#1236</a>.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-167070">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/AYXNm.png?s=16&g=1" alt="quartata" />
</div>
<div class="username"><a href="/users/167070/quartata" title="quartata">quartata</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41197912">
<a name="41197912" href="/transcript/11540?m=41197912#41197912"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
sorry for the delay
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-120914">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/WyV1l.png?s=16&g=1" alt="SmokeDetector" />
</div>
<div class="username"><a href="/users/120914/smokedetector" title="SmokeDetector">SmokeDetector</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41197915">
<a name="41197915" href="/transcript/11540?m=41197915#41197915"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
<a href="https://codecov.io/gh/Charcoal-SE/SmokeDetector/compare/8c1cd7633587085fff94743dcc9096c646c7344a...afbbeba682ba4094d33c8d9dd2a522b2d713b665" rel="nofollow noopener noreferrer">CI</a> on <a href="https://github.com/Charcoal-SE/SmokeDetector/commit/afbbeba" rel="nofollow noopener noreferrer"><code>afbbeba</code></a> succeeded. Message contains 'autopull', pulling...
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41197923">
<a name="41197923" href="/transcript/11540?m=41197923#41197923"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//github.com/Charcoal-SE/SmokeDetector" rel="nofollow noopener noreferrer">SmokeDetector</a> ] SmokeDetector started at <a href="//github.com/Charcoal-SE/SmokeDetector/commit/6ad928a" rel="nofollow noopener noreferrer">rev 6ad928a (metasmoke: <i>Merge pull request #1236 from Charcoal-SE/auto-blacklist-1510879822.8478458</i>)</a> (running on Henders/EC2)
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41197925">
<a name="41197925" href="/transcript/11540?m=41197925#41197925"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Restart: API quota is 18014.
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41197984">
<a name="41197984" href="/transcript/11540?m=41197984#41197984"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//askubuntu.com/a/977247" rel="nofollow noopener noreferrer">MS</a> ] Potentially bad keyword in answer, blacklisted user: <a href="//askubuntu.com/a/977247">viewer for X.509 certificate</a> by <a href="//askubuntu.com/users/760491">vite11</a> on <code>askubuntu.com</code>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198028">
<a name="41198028" href="/transcript/11540?m=41198028#41198028"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/questions/118122" rel="nofollow noopener noreferrer">MS</a> ] Mostly dots in body: <a href="//es.stackoverflow.com/questions/118122">Por qué el organo varonil se llama pene?</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:15 AM</div>
<div class="message" id="message-41198159">
<a name="41198159" href="/transcript/11540?m=41198159#41198159"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
sd k
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198165">
<a name="41198165" href="/transcript/11540?m=41198165#41198165"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
sd - k
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-120914">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/WyV1l.png?s=16&g=1" alt="SmokeDetector" />
</div>
<div class="username"><a href="/users/120914/smokedetector" title="SmokeDetector">SmokeDetector</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198166">
<a name="41198166" href="/transcript/11540?m=41198166#41198166"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Conflicting feedback across revisions: <a href="//metasmoke.erwaysoftware.com/post/93853" rel="nofollow noopener noreferrer">current</a>, <a href="//metasmoke.erwaysoftware.com/post/93852" rel="nofollow noopener noreferrer">#1</a>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198171">
<a name="41198171" href="/transcript/11540?m=41198171#41198171"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
tpu by QPaysTaxes on <a href="//askubuntu.com/a/977247">viewer for X.509 certificate</a> [<a href="http://metasmoke.erwaysoftware.com/post/93852" rel="nofollow noopener noreferrer">MS</a>]
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198235">
<a name="41198235" href="/transcript/11540?m=41198235#41198235"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/a/118124" rel="nofollow noopener noreferrer">MS</a> ] Blacklisted user: <a href="//es.stackoverflow.com/a/118124">Como mandar un registro de una celda DataGridView a un textbox de otro formulario?</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198237">
<a name="41198237" href="/transcript/11540?m=41198237#41198237"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/a/118127" rel="nofollow noopener noreferrer">MS</a> ] Blacklisted user: <a href="//es.stackoverflow.com/a/118127">Como mandar un registro de una celda DataGridView a un textbox de otro formulario?</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198240">
<a name="41198240" href="/transcript/11540?m=41198240#41198240"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/questions/118125" rel="nofollow noopener noreferrer">MS</a> ] Blacklisted user: <a href="//es.stackoverflow.com/questions/118125">¿Cómo puedo hacer este código funcional para mi website-blog de tecnología?</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198242">
<a name="41198242" href="/transcript/11540?m=41198242#41198242"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/questions/118122" rel="nofollow noopener noreferrer">MS</a> ] Blacklisted user: <a href="//es.stackoverflow.com/questions/118122">Por que el organo varonil se le denomina pene</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198272">
<a name="41198272" href="/transcript/11540?m=41198272#41198272"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198242#41198242"> </a>
<div class="content">
@SmokeDetector tpu-
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198287">
<a name="41198287" href="/transcript/11540?m=41198287#41198287"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198240#41198240"> </a>
<div class="content">
@SmokeDetector tpu-
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198300">
<a name="41198300" href="/transcript/11540?m=41198300#41198300"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198237#41198237"> </a>
<div class="content">
@SmokeDetector tpu-
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198304">
<a name="41198304" href="/transcript/11540?m=41198304#41198304"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
question: can anyone in here do: <code>!!/repor t <link></code> when a case linke above happens?
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198305">
<a name="41198305" href="/transcript/11540?m=41198305#41198305"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198235#41198235"> </a>
<div class="content">
@SmokeDetector tpu-
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198345">
<a name="41198345" href="/transcript/11540?m=41198345#41198345"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198304#41198304"> </a>
<div class="content">
@Videonauth You need to be a <a href="https://charcoal-se.org/smokey/Commands#privileged-commands" rel="nofollow noopener noreferrer">privileged user</a>.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-120914">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/WyV1l.png?s=16&g=1" alt="SmokeDetector" />
</div>
<div class="username"><a href="/users/120914/smokedetector" title="SmokeDetector">SmokeDetector</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198349">
<a name="41198349" href="/transcript/11540?m=41198349#41198349"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Conflicting feedback across revisions: <a href="//metasmoke.erwaysoftware.com/post/93848" rel="nofollow noopener noreferrer">current</a>, <a href="//metasmoke.erwaysoftware.com/post/93847" rel="nofollow noopener noreferrer">#1</a>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:28 AM</div>
<div class="message" id="message-41198350">
<a name="41198350" href="/transcript/11540?m=41198350#41198350"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
ah ok :)
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198423">
<a name="41198423" href="/transcript/11540?m=41198423#41198423"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198350#41198350"> </a>
<div class="content">
@Videonauth There's a <a href="https://charcoal-se.org/pings/mods" rel="nofollow noopener noreferrer">list of mods to ping</a> when things get out of hand.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198457">
<a name="41198457" href="/transcript/11540?m=41198457#41198457"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
oh yes i know a few i would ping then otherwise i drop you guys here a line if i stumble on a missed one
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198542">
<a name="41198542" href="/transcript/11540?m=41198542#41198542"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198457#41198457"> </a>
<div class="content">
@Videonauth Do you understand Spanish?
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198550">
<a name="41198550" href="/transcript/11540?m=41198550#41198550"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
nope only english and german (native)
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198594">
<a name="41198594" href="/transcript/11540?m=41198594#41198594"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
I have no idea what <a href="https://es.stackoverflow.com/a/118124/">this</a> means. It should probably be reported, but I don't know. It sort of looks like Italian though.
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198607">
<a name="41198607" href="/transcript/11540?m=41198607#41198607"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
No wait, it's already caught above.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:45 AM</div>
<div class="message" id="message-41198629">
<a name="41198629" href="/transcript/11540?m=41198629#41198629"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
<span class="deleted">(removed)</span>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198635">
<a name="41198635" href="/transcript/11540?m=41198635#41198635"><span style="display:inline-block;" class="action-link edits"><span class="img"> </span></span></a>
<div class="content">
use google translate, cant let this stand here :) at least not without getting a time out for naughtyness
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198641">
<a name="41198641" href="/transcript/11540?m=41198641#41198641"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198594#41198594"> </a>
<div class="content">
@NisseEngstrm It's spam.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198709">
<a name="41198709" href="/transcript/11540?m=41198709#41198709"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198635#41198635"> </a>
<div class="content">
@Videonauth Google Translate didn't work on that one.
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198714">
<a name="41198714" href="/transcript/11540?m=41198714#41198714"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198641#41198641"> </a>
<div class="content">
@QPaysTaxes Thanks.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198715">
<a name="41198715" href="/transcript/11540?m=41198715#41198715"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
it did
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198719">
<a name="41198719" href="/transcript/11540?m=41198719#41198719"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
dont know if you can see deleted messages
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198731">
<a name="41198731" href="/transcript/11540?m=41198731#41198731"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198719#41198719"> </a>
<div class="content">
@Videonauth Nope.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198769">
<a name="41198769" href="/transcript/11540?m=41198769#41198769"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
its spanish, autodetection did work to english: will post it in a few seconds againhere for short please dont flagbann me
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198776">
<a name="41198776" href="/transcript/11540?m=41198776#41198776"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
<span class="deleted">(removed)</span>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198787">
<a name="41198787" href="/transcript/11540?m=41198787#41198787"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
seen?
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:54 AM</div>
<div class="message" id="message-41198799">
<a name="41198799" href="/transcript/11540?m=41198799#41198799"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198787#41198787"> </a>
<div class="content">
@Videonauth Yes, but that's not the one I linked to.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198835">
<a name="41198835" href="/transcript/11540?m=41198835#41198835"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
ah the one above mhmmm yes doesnt work
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198853">
<a name="41198853" href="/transcript/11540?m=41198853#41198853"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198769#41198769"> </a>
<div class="content">
@Videonauth No one here flag-bans people.
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198854">
<a name="41198854" href="/transcript/11540?m=41198854#41198854"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
You get flag banned if you flag too many things that get declined by mods.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198858">
<a name="41198858" href="/transcript/11540?m=41198858#41198858"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
its gibberish tho talking about a garden party at an uncles place
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198860">
<a name="41198860" href="/transcript/11540?m=41198860#41198860"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Gibberish is a perfectly good reason to red-flag.
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198864">
<a name="41198864" href="/transcript/11540?m=41198864#41198864"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
Whether you flag as spam or r/a doesn't really matter.
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198869">
<a name="41198869" href="/transcript/11540?m=41198869#41198869"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
got it translated via leo.org
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-155243">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/fY1pd.jpg?s=16&g=1" alt="Nisse Engström" />
</div>
<div class="username"><a href="/users/155243/nisse-engstrom" title="Nisse Engström">Nisse Engström</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:58 AM</div>
<div class="message" id="message-41198872">
<a name="41198872" href="/transcript/11540?m=41198872#41198872"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
!!/report <a href="https://es.stackoverflow.com/a/118116/" rel="nofollow noopener noreferrer">es.stackoverflow.com/a/118116</a> <a href="https://es.stackoverflow.com/a/118114/" rel="nofollow noopener noreferrer">es.stackoverflow.com/a/118114</a> <a href="https://es.stackoverflow.com/a/118120/" rel="nofollow noopener noreferrer">es.stackoverflow.com/a/118120</a> <a href="https://es.stackoverflow.com/a/118119/" rel="nofollow noopener noreferrer">es.stackoverflow.com/a/118119</a>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-120914">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/WyV1l.png?s=16&g=1" alt="SmokeDetector" />
</div>
<div class="username"><a href="/users/120914/smokedetector" title="SmokeDetector">SmokeDetector</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198873">
<a name="41198873" href="/transcript/11540?m=41198873#41198873"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/a/118116" rel="nofollow noopener noreferrer">MS</a> ] Manually reported answer (batch report: post 1 out of 4): <a href="//es.stackoverflow.com/a/118116">No logro entender porque me da este error ArrayIndexOutOfBoundsException: 6</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198876">
<a name="41198876" href="/transcript/11540?m=41198876#41198876"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/a/118114" rel="nofollow noopener noreferrer">MS</a> ] Manually reported answer (batch report: post 2 out of 4): <a href="//es.stackoverflow.com/a/118114">Asignar valores a un combobox html con JSOUP</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198880">
<a name="41198880" href="/transcript/11540?m=41198880#41198880"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198873#41198873"> </a>
<div class="content">
@SmokeDetector k
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-120914">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/WyV1l.png?s=16&g=1" alt="SmokeDetector" />
</div>
<div class="username"><a href="/users/120914/smokedetector" title="SmokeDetector">SmokeDetector</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198879">
<a name="41198879" href="/transcript/11540?m=41198879#41198879"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/a/118120" rel="nofollow noopener noreferrer">MS</a> ] Manually reported answer (batch report: post 3 out of 4): <a href="//es.stackoverflow.com/a/118120">Crystal Reports Arroja "E_NOINTERFACE" cuando reporte.SetDataSource(ds);</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198882">
<a name="41198882" href="/transcript/11540?m=41198882#41198882"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<div class="content">
[ <a href="//goo.gl/eLDYqh" rel="nofollow noopener noreferrer">SmokeDetector</a> | <a href="//m.erwaysoftware.com/posts/by-url?url=//es.stackoverflow.com/a/118119" rel="nofollow noopener noreferrer">MS</a> ] Manually reported answer (batch report: post 4 out of 4): <a href="//es.stackoverflow.com/a/118119">Descargar archivos desde la terminal de Mac</a> by <a href="//es.stackoverflow.com/users/66574">Escroto Y Pene Gratis</a> on <code>es.stackoverflow.com</code>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198884">
<a name="41198884" href="/transcript/11540?m=41198884#41198884"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198876#41198876"> </a>
<div class="content">
@SmokeDetector k
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-205533">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/idNpq.jpg?s=16&g=1" alt="Videonauth" />
</div>
<div class="username"><a href="/users/205533/videonauth" title="Videonauth">Videonauth</a></div>
</div></div>
<div class="messages">
<div class="message" id="message-41198888">
<a name="41198888" href="/transcript/11540?m=41198888#41198888"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198853#41198853"> </a>
<div class="content">
@QPaysTaxes well i posted the translation of that other spanish post which was not really PG friendly <i>coughs coughs</i>
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
<div class="monologue user-137388">
<div class="signature"><div class="tiny-signature">
<div class="avatar avatar-16">
<img width="16" height="16" src="https://i.stack.imgur.com/Ma6sp.jpg?s=16&g=1" alt="QPaysTaxes" />
</div>
<div class="username"><a href="/users/137388/qpaystaxes" title="QPaysTaxes">QPaysTaxes</a></div>
</div></div>
<div class="messages">
<div class="timestamp">1:59 AM</div>
<div class="message" id="message-41198889">
<a name="41198889" href="/transcript/11540?m=41198889#41198889"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198879#41198879"> </a>
<div class="content">
@SmokeDetector k
</div>
<span class="flash">
</span>
</div>
<div class="message" id="message-41198893">
<a name="41198893" href="/transcript/11540?m=41198893#41198893"><span style="display:inline-block;" class="action-link"><span class="img"> </span></span></a>
<a class="reply-info" href="/transcript/11540?m=41198882#41198882"> </a>
<div class="content">
@SmokeDetector k
</div>
<span class="flash">
</span>
</div>
</div>
<div class="clear-both" style="height:0"> </div>
</div>
</div>
<div class="clear-both"></div><div class="pager"><a href="/transcript/11540/2017/11/17/0-1"><span class="page-numbers">00:00 - 01:00</span></a><span class="page-numbers current">01:00 - 02:00</span><a href="/transcript/11540/2017/11/17/2-13"><span class="page-numbers">02:00 - 13:00</span></a><a href="/transcript/11540/2017/11/17/13-24"><span class="page-numbers">13:00 - 00:00</span></a></div><div class="clear-both"></div>
<br/>
<a href="/transcript/11540/2013/11/16" class="button noprint" title="2013-11-16">« first day (1461 days earlier)</a>
<a href="/transcript/11540/2017/11/16" class="button noprint" rel="prev" title="2017-11-16">← previous day</a>
<link rel="prev" title="2017-11-16" href="/transcript/11540/2017/11/16" />
<a href="/transcript/11540/2017/11/18" class="button noprint" rel="next" title="2017-11-18">next day →</a>
<link rel="next" title="2017-11-18" href="/transcript/11540/2017/11/18" />
<a href="/transcript/11540/2017/11/22" class="button noprint" title="2017-11-22"> last day (5 days later) »</a>
<div class="clear-both"></div>
<div id="sidebar">
<div id="sidebar-content">
<div id="info">
<form method="get" action="/search">
<input type="text" id="searchbox" name="q"/>
<input type="hidden" name="room" value="11540" />
</form>
<div style="padding-top:3px;"><a href="/" class="button">all rooms</a></div>
<br clear=left />
<h2>Transcript for</h2>
<a class="calendar-small-link" href="/transcript/11540/2017/11/16">
<div class="icon" title="2017-11-16"><div class="calendar-small"><span class="weekday-small">Nov</span>16</div></div>
</a>
<div class="icon" title="2017-11-17"><div class="calendar"><span class="weekday">Nov</span>17</div></div>
<a class="calendar-small-link" href="/transcript/11540/2017/11/18">
<div class="icon" title="2017-11-18"><div class="calendar-small"><span class="weekday-small">Nov</span>18</div></div>
</a>
<br clear=left />
<div class="room-mini"><div class="room-mini-header"><h3><span class="room-name"><a rel="noreferrer noopener" href="/rooms/11540/charcoal-hq">Charcoal HQ</a></span></h3><div title="Where diamonds are made, smoke is detected, and we break things by developing on production. 76,000 true positives and counting. [Recursive] oneboxes are awesome. Handy links: http://charcoal-se.org, https://github.com/Charcoal-SE, http://charcoal-se.org/blaze/" class="room-mini-description">Where diamonds are made, smoke is detected, and we break thing...<a href="http://charcoal-se.org" rel="nofollow noopener noreferrer"></a><a href="https://github.com/Charcoal-SE" rel="nofollow noopener noreferrer"></a><a href="http://charcoal-se.org/blaze/" rel="nofollow noopener noreferrer"></a></div></div><div class="room-current-user-count" title="current users"><a rel="noopener noreferrer" href="/rooms/info/11540/charcoal-hq">33</a></div><div class="room-message-count" title="messages in the last 2h"><a rel="noopener noreferrer" href="/transcript/11540">75</a></div><div class="mspark" style="height:25px;width:205px">
<div class="mspbar" style="width:8px;height:6px;left:0px;"></div><div class="mspbar" style="width:8px;height:7px;left:8px;"></div><div class="mspbar" style="width:8px;height:9px;left:16px;"></div><div class="mspbar" style="width:8px;height:9px;left:24px;"></div><div class="mspbar" style="width:8px;height:16px;left:32px;"></div><div class="mspbar" style="width:8px;height:20px;left:40px;"></div><div class="mspbar" style="width:8px;height:21px;left:48px;"></div><div class="mspbar" style="width:8px;height:25px;left:56px;"></div><div class="mspbar" style="width:8px;height:21px;left:64px;"></div><div class="mspbar" style="width:8px;height:25px;left:72px;"></div><div class="mspbar" style="width:8px;height:20px;left:80px;"></div><div class="mspbar" style="width:8px;height:20px;left:88px;"></div><div class="mspbar" style="width:8px;height:17px;left:96px;"></div><div class="mspbar" style="width:8px;height:13px;left:104px;"></div><div class="mspbar" style="width:8px;height:10px;left:112px;"></div><div class="mspbar" style="width:8px;height:9px;left:120px;"></div><div class="mspbar" style="width:8px;height:13px;left:128px;"></div><div class="mspbar" style="width:8px;height:12px;left:136px;"></div><div class="mspbar" style="width:8px;height:17px;left:144px;"></div><div class="mspbar" style="width:8px;height:15px;left:152px;"></div><div class="mspbar" style="width:8px;height:12px;left:160px;"></div><div class="mspbar" style="width:8px;height:9px;left:168px;"></div><div class="mspbar" style="width:8px;height:7px;left:176px;"></div><div class="mspbar" style="width:8px;height:4px;left:184px;"></div><div class="mspbar now" style="height:25px;left:166px;"></div></div>
<div class="clear-both"></div></div>
<div><a rel="noopener noreferrer" class="tag" href="http://stackexchange.com/tags/best-bad-practices/info">best-bad-practices</a> <a rel="noopener noreferrer" class="tag" href="http://stackexchange.com/tags/dev-on-prod/info">dev-on-prod</a> <a rel="noopener noreferrer" class="tag" href="http://stackexchange.com/tags/panic-driven-development/info">panic-driven-development</a> <a rel="noopener noreferrer" class="tag" href="http://stackexchange.com/tags/plastic-knives/info">plastic-knives</a></div>
<br class="clear-both" />
<div class="noprint">
<div id="transcript-links">
<a id="join-room" href="/rooms/11540/charcoal-hq" class="button">join this room</a><br />
<a href="/rooms/info/11540/charcoal-hq" class="button">about this room</a><br />
<a class="button" href="#" id="bookmark-button">bookmark a conversation</a><br />
</div>
<br />
<div class="mspark" style="height:300px;width:200px">
<div class="mspbar" style="height:12px;width:57px;top:0px;"></div><div class="msplab" style="top:0px;">00:00</div><div class="mspbar" style="height:12px;width:182px;top:12px;"></div><div class="mspbar" style="height:12px;width:54px;top:24px;"></div><div class="mspbar" style="height:12px;width:12px;top:36px;"></div><div class="mspbar" style="height:12px;width:131px;top:48px;"></div><div class="mspbar" style="height:12px;width:110px;top:60px;"></div><div class="mspbar" style="height:12px;width:161px;top:72px;"></div><div class="msplab" style="top:72px;">06:00</div><div class="mspbar" style="height:12px;width:99px;top:84px;"></div><div class="mspbar" style="height:12px;width:113px;top:96px;"></div><div class="mspbar" style="height:12px;width:200px;top:108px;"></div><div class="mspbar" style="height:12px;width:99px;top:120px;"></div><div class="mspbar" style="height:12px;width:110px;top:132px;"></div><div class="mspbar" style="height:12px;width:90px;top:144px;"></div><div class="msplab" style="top:144px;">12:00</div><div class="mspbar" style="height:12px;width:191px;top:156px;"></div><div class="mspbar" style="height:12px;width:18px;top:168px;"></div><div class="mspbar" style="height:12px;width:15px;top:180px;"></div><div class="mspbar" style="height:12px;width:6px;top:192px;"></div><div class="mspbar" style="height:12px;width:75px;top:204px;"></div><div class="mspbar" style="height:12px;width:90px;top:216px;"></div><div class="msplab" style="top:216px;">18:00</div><div class="mspbar" style="height:12px;width:45px;top:228px;"></div><div class="mspbar" style="height:12px;width:57px;top:240px;"></div><div class="mspbar" style="height:12px;width:36px;top:252px;"></div><div class="mspbar" style="height:12px;width:54px;top:264px;"></div><div class="mspbar" style="height:12px;width:27px;top:276px;"></div><a href="/transcript/11540/2017/11/17/0-1"><div class="msparea" style="top:0px;width:200px;height:12px" title="19 messages"></div></a><a href="/transcript/11540/2017/11/17/1-2"><div class="msparea now" style="top:12px;width:200px;height:12px" title="61 messages"></div></a><a href="/transcript/11540/2017/11/17/2-13"><div class="msparea" style="top:24px;width:200px;height:132px" title="395 messages"></div></a><a href="/transcript/11540/2017/11/17/13-24"><div class="msparea" style="top:156px;width:200px;height:132px" title="205 messages"></div></a></div>
<div class="msg-small">
all times are UTC
</div>
<br />
</div>
<br /><br /><div id="transcript-logo"><a rel="noreferrer noopener" href="http://stackexchange.com" title="The Stack Exchange Network"><img style="max-width:150px" src="//cdn-chat.sstatic.net/chat/img/se-logo-white.png?v=da" alt="The Stack Exchange Network"/></a>
</div>
<br class="clear-both" /><br />
<div id="copyright">
site design / logo © 2017 Stack Exchange Inc; <a rel="noopener noreferrer" href="http://stackexchange.com/legal">legal</a>
<br /><br />
<a href="#" class="mobile-on">mobile</a>
</div>
</div>
</div>
</div>
</div>
</div> <input id="fkey" name="fkey" type="hidden" value="64f0ae1fdde80a7b92d9281473795fde" />
</body>
</html>'''
| 43.956629 | 2,383 | 0.536746 |
002d82da21503f07067ace5a4397c6b6011e7cc0 | 4,709 | py | Python | pybps/preprocess/trnsys.py | dtavan/PyBPS | 92bd063daed78a7fcff1af954d7d90d0cde8dcfc | [
"BSD-3-Clause"
] | 9 | 2015-03-12T15:23:42.000Z | 2021-12-21T13:01:42.000Z | pybps/preprocess/trnsys.py | dtavan/PyBPS | 92bd063daed78a7fcff1af954d7d90d0cde8dcfc | [
"BSD-3-Clause"
] | 3 | 2015-09-20T17:31:09.000Z | 2018-02-26T13:11:53.000Z | pybps/preprocess/trnsys.py | dtavan/PyBPS | 92bd063daed78a7fcff1af954d7d90d0cde8dcfc | [
"BSD-3-Clause"
] | 3 | 2019-02-14T08:13:03.000Z | 2020-12-10T07:04:41.000Z | """
A set of functions required to pre-process TRNSYS simulation input files
"""
# Common imports
import os
import sys
import shutil
import re
# Custom imports
from pybps import util
# Handle Python 2/3 compatibility
from six.moves import configparser
import six
if six.PY2:
ConfigParser = configparser.SafeConfigParser
else:
ConfigParser = configparser.ConfigParser
def parse_deck_const(deck_abspath):
"""Parse constants in control cards and equations from TRNSYS deck file
Finds all constants in a TRNSYS deck file and stores constant name and
value in a dict.
Args:
deck_abspath: absolute path to TRNSYS deck file
Returns:
A dict containing all found constants and their values
"""
const_dict = {}
f = open(deck_abspath, 'r')
split_blocks_pat = re.compile(r'[*][-]+')
equa_pat = re.compile(r'[*]\sEQUATIONS\s"(.+?)"')
const_pat = re.compile(r'\b(\w+)\b\s=\s(\d+\.*\d*)\s')
with f:
data = f.read()
blocks = split_blocks_pat.split(data)
for block in blocks:
if block[0] == 'V':
match_par = const_pat.findall(block)
if match_par:
group = "Control Cards"
const_dict[group] = {}
for (m,v) in match_par:
const_dict[group][m] = v
else:
match_eq = equa_pat.findall(block)
if match_eq:
group = match_eq[0]
match_par = const_pat.findall(block)
if match_par:
const_dict[group] = {}
for (m,v) in match_par:
const_dict[group][m] = v
return const_dict
def prepare_deck_template(deck_abspath, param_list):
"""Prepare a template TRNSYS deck file for parametric analysis
Transforms a TRNSYS deck in a template file valid for parametric analysis
by replacing constant values with parameter search strings (the name of
the constant surrounded by '%' signs). That parameters are given in a list.
Args:
deck_abspath: absolute path to TRNSYS deck file
param_list: list of parameters to be included in template
Returns:
A valid template file for parametric analysis with PyBPS
"""
templ_deck_abspath = os.path.splitext(deck_abspath)[0] + "_Template.dck"
shutil.copyfile(deck_abspath, templ_deck_abspath)
f = open(templ_deck_abspath, 'r+')
with f:
data = f.read()
for par in param_list:
data = re.sub(r'(' + par + r')\s=\s(\d+\.*\d*)', r'\g<1> = %\g<1>%', data)
f.seek(0)
f.write(data)
f.truncate()
def gen_type56(model_abspath, select='all'):
"""Generate Type56 matrices and idf files
Calls TRNBUILD.exe with flags to generate matrices and IDF files.
Args:
model_abspath: absolute path to Type56 model file
select: selects which files should by generated by TRNBUILD.
'masks' generates insolation matrix, 'vfm' generates de view factor
matrix, 'matrices' generates both
'idf' generates the IDF file (similar to TRNBUILD 'export' funtion)
'all' generates everything
Returns:
Generated files.
"""
# Get information from config file
conf = SafeConfigParser()
conf_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'..\config.ini')
conf.read(conf_file)
trnbuild_path = os.path.abspath(conf.get('TRNSYS', 'TRNBuild_Path'))
trnsidf_path = os.path.abspath(conf.get('TRNSYS', 'trnsIDF_Path'))
# Get b17 file path from deck file
pattern = re.compile(r'ASSIGN "(.*b17)"')
with open(model_abspath, 'rU') as m_f:
temp = m_f.read()
match = pattern.search(temp)
# TRNBUILD is only called if Type56 is found in deck file.
if match:
b17_relpath = match.group(1)
b17_abspath = os.path.join(os.path.dirname(model_abspath), b17_relpath)
# Generate shading/insolation matrix
if select == 'all' or select == 'matrices' or select == 'masks':
cmd = [trnbuild_path, b17_abspath, '/N', '/masks']
util.run_cmd(cmd)
# Generate view factor matrix
if select == 'all' or select == 'matrices' or select == 'vfm':
cmd = [trnbuild_path, b17_abspath, '/N', '/vfm']
util.run_cmd(cmd)
# Generate trnsys3D idf file, to view geometry in Sketchup
if select == 'all' or select == 'idf':
cmd = [trnsidf_path, b17_abspath]
util.run_cmd(cmd)
| 31.393333 | 86 | 0.601826 |
002fac18e96ba58a8fc58e5945a2e85038de81e9 | 1,650 | py | Python | gof/console.py | jul/game_of_life | 0ffb798679f50dea27b55f8a630c437b6ee4d8f9 | [
"Python-2.0"
] | 1 | 2015-01-13T13:42:32.000Z | 2015-01-13T13:42:32.000Z | gof/console.py | jul/game_of_life | 0ffb798679f50dea27b55f8a630c437b6ee4d8f9 | [
"Python-2.0"
] | null | null | null | gof/console.py | jul/game_of_life | 0ffb798679f50dea27b55f8a630c437b6ee4d8f9 | [
"Python-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Game of Life console.
small play ground for leanning python, or just having fun.
To use the console with an empty grid:
python -i -mgof.console
or
bpython -i -mgof.console
To use the console with a pseudo animation:
python -i -mgof.demo
Avalailble variable :
* grid your playground a matrix of cellular automata
* patterns : pixel, still, oscillator, glider
they are singular patterns to play with in game of life.
* all_pattern : a list of all patterns (except pixel)
* matrix : the class name of grid is imported for educationnal purpose
* DEAD, ALIVE
Available functions:
* intro() : a short summary of all available functions
* bleach(...) a function to init the grid
* at(...) a function to draw a pattern on the grid
* rand_pattern() : a function to add random pattern in your grid
* evolve(...) make the game evolve for some time. If your terminal and/or
interactive python supports it, it will make a continuous animation
* use help(function_name) to know more yes it is a builtin ^_^
"""
from .matrix import matrix
from time import sleep
from .gof import glider, oscillator, still, pixel, all_pattern
from .gof import evolve, bleach,dirty, DEAD, ALIVE, at
#### Constants and globals
__all__ = [
"matrix","at",
"grid", "intro",
"glider", "oscillator", "still","pixel","all_pattern",
"evolve", "bleach", "dirty", "DEAD", "ALIVE" ]
x=10
y=30
grid=matrix(x,y,x*y*[DEAD])
if '__main__' == __name__:
print(__doc__)
| 28.448276 | 79 | 0.693939 |
00307ed891cc3bbf4d17b34c5cc7d2164137d3c2 | 17,263 | py | Python | channels/italiafilmvideohd.py | sodicarus/channels | d77402f4f460ea6daa66959aa5384aaffbff70b5 | [
"MIT"
] | null | null | null | channels/italiafilmvideohd.py | sodicarus/channels | d77402f4f460ea6daa66959aa5384aaffbff70b5 | [
"MIT"
] | null | null | null | channels/italiafilmvideohd.py | sodicarus/channels | d77402f4f460ea6daa66959aa5384aaffbff70b5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# StreamOnDemand-PureITA / XBMC Plugin
# Canal para italiafilmvideohd
# http://www.mimediacenter.info/foro/viewtopic.php?f=36&t=7808
# ------------------------------------------------------------
import base64
import re
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from core.tmdb import infoSod
from servers import servertools
__channel__ = "italiafilmvideohd"
host = "https://italiafilm.network/"
headers = [['User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0'],
['Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'],
['Accept-Encoding', 'gzip, deflate'],
['Referer', host],
['Cache-Control', 'max-age=0']]
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
# ===================================================================================================================================================
| 40.618824 | 154 | 0.553148 |
00316d362ddde2a4019229bccffbafd03e33e693 | 1,129 | py | Python | covid19uk/data/tier_data_test.py | sdwfrost/covid19uk | ffd59342d9daee2d819d2f7211afbe9713880612 | [
"MIT"
] | 10 | 2020-03-21T22:36:24.000Z | 2021-05-23T22:47:13.000Z | covid19uk/data/tier_data_test.py | sdwfrost/covid19uk | ffd59342d9daee2d819d2f7211afbe9713880612 | [
"MIT"
] | 14 | 2020-03-27T19:24:51.000Z | 2021-07-21T12:41:23.000Z | covid19uk/data/tier_data_test.py | sdwfrost/covid19uk | ffd59342d9daee2d819d2f7211afbe9713880612 | [
"MIT"
] | 13 | 2020-03-21T17:17:20.000Z | 2021-05-06T22:50:18.000Z | """Tests Tier Data"""
import numpy as np
from covid.data import TierData
| 30.513514 | 258 | 0.560673 |
00333d9d6b82d73d347ef774e208f7a11fd780ab | 1,550 | py | Python | Baixar um arquivo Excel e mandar o resultado para emails.py | GustavooBueno/Projetos-Python-Automacao | 43ec53040cd543746d88e8523fcffbdb69112ab7 | [
"MIT"
] | null | null | null | Baixar um arquivo Excel e mandar o resultado para emails.py | GustavooBueno/Projetos-Python-Automacao | 43ec53040cd543746d88e8523fcffbdb69112ab7 | [
"MIT"
] | null | null | null | Baixar um arquivo Excel e mandar o resultado para emails.py | GustavooBueno/Projetos-Python-Automacao | 43ec53040cd543746d88e8523fcffbdb69112ab7 | [
"MIT"
] | null | null | null | import pyautogui
import time
import pyperclip
import pandas as pd
#pyautogui.displayMousePosition()
pyautogui.PAUSE = 1
#Passo 1
#Abrir uma nova aba
time.sleep(2)
pyautogui.hotkey('ctrl', 't')
#Entrar no link do sistema
link = "https://drive.google.com/drive/folders/149xknr9JvrlEnhNWO49zPcw0PW5icxga"
pyperclip.copy(link)
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter')
#Passo 2
time.sleep(5)
pyautogui.click(389, 270, clicks = 2)
time.sleep(2)
#Passo 3
pyautogui.click(401, 337) #clicar no arquivo
pyautogui.click(1713, 157) #clicar nos 3 pontos
pyautogui.click(1525, 561) #clicar no fazer download
time.sleep(10)
#Passo 4
tabela = pd.read_excel(r'C:\Users\Pichau\Downloads\Vendas - Dez.xlsx')
faturamento = tabela['Valor Final'].sum()
quantidade = tabela['Quantidade'].sum()
#Passo 5
time.sleep(2)
pyautogui.hotkey('ctrl', 't')
#Entrar no link do sistema
link = "https://mail.google.com/mail/u/0/#inbox"
pyperclip.copy(link)
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter')
time.sleep(7)
pyautogui.click(33, 170)
pyautogui.write('gustavo.ibis.gb+diretoria@gmail.com')
pyautogui.press('tab')
pyautogui.press('tab')
assunto = 'Relatrio de Vendas'
pyperclip.copy(assunto)
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('tab')
texto_email = f"""
Prezados, bom dia
O faturamento de ontem foi de: R${faturamento:,.2f}
A quantidade de produtos foi de: R${quantidade:,.2f}
Abs
"""
pyperclip.copy(texto_email)
pyautogui.hotkey('ctrl', 'v')
pyautogui.hotkey('ctrl', 'enter') | 25 | 82 | 0.713548 |
00341cca0d8a5cb36317216f72b4964ad336e187 | 34,289 | py | Python | brain_class.py | featureCreacle/Baka-battle | 0588216ff08bec1f6d4e0679daa8ac70e7f3d83a | [
"MIT"
] | 1 | 2017-12-23T11:16:35.000Z | 2017-12-23T11:16:35.000Z | brain_class.py | featureCreacle/Baka-battle | 0588216ff08bec1f6d4e0679daa8ac70e7f3d83a | [
"MIT"
] | null | null | null | brain_class.py | featureCreacle/Baka-battle | 0588216ff08bec1f6d4e0679daa8ac70e7f3d83a | [
"MIT"
] | null | null | null | import tkinter
import json
from math import *
from random import *
from tkinter import *
| 46.906977 | 143 | 0.495727 |
0034f805a844662bdcbee5246fde715c74fdfb46 | 761 | py | Python | xiamiu/urls.py | Vida42/xiamiu | 9249a20746d1da050546e3fcdfafbc5ff49ab4d0 | [
"Apache-2.0"
] | null | null | null | xiamiu/urls.py | Vida42/xiamiu | 9249a20746d1da050546e3fcdfafbc5ff49ab4d0 | [
"Apache-2.0"
] | null | null | null | xiamiu/urls.py | Vida42/xiamiu | 9249a20746d1da050546e3fcdfafbc5ff49ab4d0 | [
"Apache-2.0"
] | null | null | null | from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.index, name='home'),
url(r'^artist/(?P<inputID>.*?)/$', views.showArtistPage, name='showArtistPage'),
url(r'^album/(?P<inputID>.*?)/$', views.showAlbumPage, name='showAlbumPage'),
url(r'^song/(?P<inputID>.*?)/$', views.showSongPage, name='showSongPage'),
url(r'^genre/(?P<inputID>.*?)/$', views.showGenrePage, name='showGenrePage'),
url(r'^search/$', views.search, name='search'),
url(r'^search/artist/$', views.searchArtistByName, name='searchArtistByName'),
url(r'^search/album/$', views.searchAlbumByName, name='searchAlbumByName'),
url(r'^search/song/$', views.searchSongByName, name='searchSongByName')
]
| 44.764706 | 84 | 0.672799 |
00350a7f72c371d77bedf708f8a55456f2d37c38 | 19,030 | py | Python | lib/python/treadmill_aws/formatter.py | Morgan-Stanley/treadmill-aws | 4c3d25c477422d83f0cd8dc6851fd02ffa48dcbb | [
"Apache-2.0"
] | 6 | 2018-05-24T17:17:51.000Z | 2020-06-06T02:21:59.000Z | lib/python/treadmill_aws/formatter.py | Morgan-Stanley/treadmill-aws | 4c3d25c477422d83f0cd8dc6851fd02ffa48dcbb | [
"Apache-2.0"
] | 93 | 2018-04-16T16:14:40.000Z | 2019-09-17T22:10:28.000Z | lib/python/treadmill_aws/formatter.py | Morgan-Stanley/treadmill-aws | 4c3d25c477422d83f0cd8dc6851fd02ffa48dcbb | [
"Apache-2.0"
] | 17 | 2017-09-29T10:30:47.000Z | 2019-01-28T21:52:03.000Z | """Table CLI formatter.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import yaml
from treadmill.formatter import tablefmt
def _sort(unsorted):
"""Sort list."""
unsorted.sort()
return '\n'.join(unsorted)
def _state(state):
"""Get status from instance."""
return state['Name']
def _name_from_tags(tags):
"""Get name from tags."""
for tag in tags:
if tag['Key'] == 'Name':
return tag['Value']
return None
def _fmt_tags():
"""Output formatter tags."""
def _fmt(items):
"""Format tags, discard cloudformation tags."""
filtered = [
item for item in items
if not item['Key'].startswith('aws:cloudformation:')
]
schema = [
('key', 'Key', None),
('value', 'Value', None),
]
return tablefmt.list_to_table(
filtered, schema, header=False, align=None
)
return _fmt
def _fmt_secgroups():
"""Output formatter security groups."""
def _fmt(items):
"""Format tags, discard cloudformation tags."""
schema = [
('name', 'GroupName', None),
('id', 'GroupId', None),
]
return tablefmt.list_to_table(
items, schema, header=False, align=None
)
return _fmt
def _fmt_list():
"""Output formatter list."""
def _fmt(items):
"""Format list."""
schema = [
('item', None, None),
]
return tablefmt.list_to_table(
items, schema, header=False, align=None
)
return _fmt
| 31.094771 | 77 | 0.534314 |
00357487ee3571e98c5b7547cf6b9f56fc60e338 | 483 | py | Python | BOJ16360.py | INYEONGKIM/BOJ | 5e83d77a92d18b0d20d26645c7cfe4ba3e2d25bc | [
"MIT"
] | 2 | 2019-03-05T15:42:46.000Z | 2019-07-24T15:52:36.000Z | BOJ16360.py | INYEONGKIM/BOJ | 5e83d77a92d18b0d20d26645c7cfe4ba3e2d25bc | [
"MIT"
] | null | null | null | BOJ16360.py | INYEONGKIM/BOJ | 5e83d77a92d18b0d20d26645c7cfe4ba3e2d25bc | [
"MIT"
] | null | null | null | r=""
for _ in range(int(input())):
s=input();tn=s[-2]+s[-1]
if tn=='ne':
r+=s[:-2]+'anes\n'
else:
t=s[-1]
if t=='a' or t=='o' or t=='u':
r+=s+'s\n'
elif t=='i' or t=='y':
r+=s[:-1]+'ios\n'
elif t=='l' or t=='r' or t=='v':
r+=s+'es\n'
elif t=='n':
r+=s[:-1]+'anes\n'
elif t=='t' or t=='w':
r+=s+'as\n'
else:
r+=s+'us\n'
print(r,end="")
| 23 | 40 | 0.3147 |
0035d39504b6fcd873cb06e3d139aa8135704401 | 10,156 | py | Python | src/newt/db/updater.py | bmjjr/db | 39d3833f4458fcd20d09f383711745842b5db4f2 | [
"MIT"
] | 153 | 2017-01-24T16:55:00.000Z | 2022-03-21T08:24:13.000Z | src/newt/db/updater.py | bmjjr/db | 39d3833f4458fcd20d09f383711745842b5db4f2 | [
"MIT"
] | 14 | 2017-01-25T17:04:49.000Z | 2021-12-05T19:26:35.000Z | src/newt/db/updater.py | bmjjr/db | 39d3833f4458fcd20d09f383711745842b5db4f2 | [
"MIT"
] | 16 | 2017-01-25T07:25:17.000Z | 2022-03-21T08:24:16.000Z | from __future__ import print_function
"""Updates database json representation
"""
import argparse
import itertools
import logging
import relstorage.adapters.postgresql
import relstorage.options
import sys
from . import pg_connection
from . import follow
from .jsonpickle import Jsonifier
from ._adapter import DELETE_TRIGGER
from ._util import closing, table_exists, trigger_exists
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('connection_string', help='Postgresql connection string')
parser.add_argument('-t', '--poll-timeout', type=int, default=300,
help='Change-poll timeout, in seconds')
parser.add_argument('-m', '--transaction-size-limit', type=int, default=100000,
help='Transaction size limit (aproximate)')
parser.add_argument(
'-l', '--logging-configuration', default='info',
help='Logging configuration file path, or a logging level name')
parser.add_argument(
'-d', '--driver', default='auto',
help='Provide an explicit Postgres driver name (e.g. psycopg2)')
parser.add_argument(
'-T', '--remove-delete-trigger', action="store_true",
help="""\
Remove the Newt DB delete trigger, if it exists.
The Newt DB delete trigger is incompatible with the updater. It can cause
deadlock errors is packed while the updater is running.
""")
gc_sql = """
delete from newt n where not exists (
select from object_state s where n.zoid = s.zoid)
"""
parser.add_argument(
'-g', '--gc-only', action="store_true",
help="""\
Collect garbage and exit.
This removes Newt DB records that don't have corresponding database records.
This is done by executing:
%s
Note that garbage collection is normally performed on startup unless
the -G option is used.
""" % gc_sql)
parser.add_argument(
'-G', '--no-gc', action="store_true",
help="Don't perform garbage collection on startup.")
parser.add_argument(
'--compute-missing', action='store_true',
help="""\
Compute missing newt records.
Rather than processing new records, process records written up through
the current time and stop. Only missing records are updated. This
option requires PostgreSQL 9.5.
This is used to compute newt records after adding Newt DB to an existing
PostgreSQL RelStorage application.
""")
parser.add_argument(
'--nagios',
help="""\
Check the status of the updater.
The status is checked by checking the updater lag, which is the
difference between the last transaction committed to the database, and
the last transaction processed by the updater. The option takes 2
numbers, separated by commas. The first number is the lag, in
seconds, for the updater to be considered to be OK. The second number
is the maximum lag for which the updater isn't considered to be in
error. For example, 1,99 indicates OK if 1 or less, WARNING if more
than 1 and less than or equal to 99 and ERROR of more than 99 seconds.
""")
parser.add_argument(
'-x', '--transform',
help = """\
The dotted name of a function (or callable object) to
transform generated JSON data. This provides a way to control
how your JSON data are generated and also provides a mechanism
for ignoring some objects. See the Newt DB transform option.
""")
logging_levels = 'DEBUG INFO WARNING ERROR CRITICAL'.split()
if __name__ == '__main__':
sys.exit(main())
| 35.760563 | 79 | 0.581824 |
00366b8cd6a29a13103561a0ee4650cafb902f88 | 124 | py | Python | pangram/pangram.py | oscantillomen/Exercism-Python | 1a598769aff0e4dd58294fcd692ca0402061717e | [
"MIT"
] | null | null | null | pangram/pangram.py | oscantillomen/Exercism-Python | 1a598769aff0e4dd58294fcd692ca0402061717e | [
"MIT"
] | null | null | null | pangram/pangram.py | oscantillomen/Exercism-Python | 1a598769aff0e4dd58294fcd692ca0402061717e | [
"MIT"
] | null | null | null | import string
ALPHABET = set(string.ascii_lowercase) | 24.8 | 44 | 0.766129 |
00372000fecac8f61456e1d5394b1e5bd0e18f9f | 3,538 | py | Python | medtype-trainer/neleval/scripts/merge_evaluations.py | vsocrates/medtype | 16c6f39d38a73c4c44258bbdf78074a81e07b1c7 | [
"Apache-2.0"
] | 113 | 2015-01-07T14:12:25.000Z | 2022-01-21T12:23:57.000Z | medtype-trainer/neleval/scripts/merge_evaluations.py | vsocrates/medtype | 16c6f39d38a73c4c44258bbdf78074a81e07b1c7 | [
"Apache-2.0"
] | 27 | 2015-02-02T02:45:38.000Z | 2018-09-08T10:33:25.000Z | medtype-trainer/neleval/scripts/merge_evaluations.py | vsocrates/medtype | 16c6f39d38a73c4c44258bbdf78074a81e07b1c7 | [
"Apache-2.0"
] | 24 | 2015-02-16T18:26:48.000Z | 2021-05-25T13:23:53.000Z | #!/usr/bin/env python
"""Merge multiple evaluation files into one with prefixed measure names
If directories are given, and --out-dir, will group by filename.
Example usage:
./scripts/merge_evaluations.py --label-re='[^/]+/?$' -x eval_merged -l =TEDL2015_neleval-no1331 --out-dir /tmp/foobar tac15data/TEDL2015_neleval-no1331 $(find tac15data/TEDL2015_neleval-no1331/00filtered/ -type d )
"""
from __future__ import print_function
import argparse
import os
import glob
import collections
import sys
import re
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('-o', '--out-dir', default=None)
ap.add_argument('-x', '--out-extension', default=None)
ap.add_argument('-l', '--label', dest='labels', action='append',
type=lambda s: s.split('=', 1))
ap.add_argument('-r', '--label-re', default=None, type=re.compile)
ap.add_argument('--fmt', default='{label}/{{}}')
ap.add_argument('paths', nargs='+')
args = ap.parse_args()
nonexist = [path for path in args.paths if not os.path.exists(path)]
if nonexist:
ap.error('Paths do not exist: %r' % nonexist)
is_dir = [os.path.isdir(path) for path in args.paths]
if all(is_dir):
if args.out_dir is None:
ap.error('Must specify --out-dir in path mode')
input_paths = collections.defaultdict(list)
for dir_path in args.paths:
for path in glob.glob(os.path.join(dir_path, '*.evaluation')):
input_paths[os.path.basename(path)].append(path)
outputs = {name: os.path.join(args.out_dir,
_swap_ext(name, args.out_extension))
for name in input_paths}
elif not any(is_dir):
if args.out_dir is not None or args.out_extension is not None:
ap.error('--out-dir and --out-extension not used in files mode; output is STDOUT')
input_paths = {'all': args.paths}
outputs = {'all': sys.stdout}
else:
ap.error('Got mixture of directories (e.g. %r) and files (e.g. %r)' % (args.paths[is_dir.index(True)], args.paths[is_dir.index(False)]))
seen_labels = set()
labels = {src: dst for dst, src in args.labels or []}
for name in input_paths:
fout = outputs[name]
if not hasattr(fout, 'read'):
opened = True
fout = open(fout, 'w')
else:
opened = False
print('Processing', name, 'to', fout.name, file=sys.stderr)
for i, path in enumerate(input_paths[name]):
label = get_label(path)
if label:
fmt = args.fmt.format(label=label)
else:
fmt = '{}'
fmt = '{{}}\t{}'.format(fmt)
with open(path) as fin:
fin = iter(fin)
try:
header = next(fin)
except StopIteration:
print('Found empty file at', path, file=sys.stderr)
if i == 0:
fout.write(header)
for l in fin:
l, measure = l.rstrip('\n\r').rsplit('\t', 1)
print(fmt.format(l, measure), file=fout)
if opened:
fout.close()
unseen_labels = set(labels) - seen_labels
if unseen_labels:
print('WARNING: did not see labels %r' % sorted(unseen_labels), file=sys.stderr)
| 34.349515 | 218 | 0.623799 |
00373487473f078500f863d310d10f7cf34f3397 | 11,276 | py | Python | IQA_BIECON_release/models/BIECON_base.py | lionzhnn/IQA_BIECON_release | 9b9452681460cbd3b670aff62f18c6661a724997 | [
"MIT"
] | 96 | 2017-07-25T07:54:59.000Z | 2022-01-09T03:33:07.000Z | IQA_BIECON_release/models/BIECON_base.py | lionzhnn/IQA_BIECON_release | 9b9452681460cbd3b670aff62f18c6661a724997 | [
"MIT"
] | 4 | 2018-04-25T09:46:05.000Z | 2019-11-08T12:44:39.000Z | IQA_BIECON_release/models/BIECON_base.py | jongyookim/IQA_BIECON_release | 9b9452681460cbd3b670aff62f18c6661a724997 | [
"MIT"
] | 35 | 2017-07-25T02:51:22.000Z | 2022-02-05T03:05:40.000Z | from __future__ import absolute_import, division, print_function
import os
import numpy as np
import theano.tensor as T
from .model_basis import ModelBasis
from .model_record import Record
from ..layers import layers
| 35.796825 | 80 | 0.55321 |
003742f13f9356a906c197142f7555948cd82cbe | 3,964 | py | Python | portfolio/Python/scrapy/bosch_russian/220volt.py | 0--key/lib | ba7a85dda2b208adc290508ca617bdc55a5ded22 | [
"Apache-2.0"
] | null | null | null | portfolio/Python/scrapy/bosch_russian/220volt.py | 0--key/lib | ba7a85dda2b208adc290508ca617bdc55a5ded22 | [
"Apache-2.0"
] | null | null | null | portfolio/Python/scrapy/bosch_russian/220volt.py | 0--key/lib | ba7a85dda2b208adc290508ca617bdc55a5ded22 | [
"Apache-2.0"
] | 5 | 2016-03-22T07:40:46.000Z | 2021-05-30T16:12:21.000Z | import csv
import os
import json
from string import join
from scrapy import log
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse, FormRequest
from scrapy.utils.url import urljoin_rfc
from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader
HERE = os.path.abspath(os.path.dirname(__file__))
| 39.247525 | 184 | 0.693239 |
00375bfd9ff84622fa3d819bbee6225d14901c17 | 97 | py | Python | Streamlit_DEMO/Text_input.py | ysraell/examples | b41df16ddda3db2cbafc4e4c85ac9bd5d000d375 | [
"BSD-3-Clause"
] | 7 | 2020-06-11T19:15:29.000Z | 2021-01-31T22:04:56.000Z | Streamlit_DEMO/Text_input.py | ysraell/examples | b41df16ddda3db2cbafc4e4c85ac9bd5d000d375 | [
"BSD-3-Clause"
] | 2 | 2019-12-30T13:09:07.000Z | 2020-06-22T03:14:28.000Z | Streamlit_DEMO/Text_input.py | ysraell/examples | b41df16ddda3db2cbafc4e4c85ac9bd5d000d375 | [
"BSD-3-Clause"
] | 3 | 2020-06-15T18:17:53.000Z | 2020-06-22T20:32:33.000Z | import streamlit as st
title = st.text_input("Search:", "")
st.write("You search for: ", title)
| 19.4 | 36 | 0.680412 |
00388d39e13165d5d68a97cebd954314afba1ff8 | 908 | py | Python | pi4_software/Examples/WSClient.py | stuckatmarine/srauv-sim | 30f4bae5d22a4529233ffa2705d7631d048a8130 | [
"MIT"
] | 1 | 2020-11-01T13:39:42.000Z | 2020-11-01T13:39:42.000Z | pi4_software/Examples/WSClient.py | stuckatmarine/srauv-sim | 30f4bae5d22a4529233ffa2705d7631d048a8130 | [
"MIT"
] | null | null | null | pi4_software/Examples/WSClient.py | stuckatmarine/srauv-sim | 30f4bae5d22a4529233ffa2705d7631d048a8130 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# WS client example to test server
import asyncio
import websockets
import json
import time
asyncio.get_event_loop().run_until_complete(hello()) | 24.540541 | 61 | 0.480176 |
00389d2165f30aa4a1d559c1fcdd0bbb4c1ad957 | 1,834 | py | Python | scripts/trends.py | iamDyeus/KnickAI | c17d808c949cb3467031498e7252bd2095c04699 | [
"MIT"
] | 31 | 2021-11-08T18:42:17.000Z | 2022-03-25T07:45:46.000Z | scripts/trends.py | iamDyeus/KnickAI | c17d808c949cb3467031498e7252bd2095c04699 | [
"MIT"
] | 6 | 2021-12-20T14:15:44.000Z | 2022-03-28T16:19:12.000Z | scripts/trends.py | iamDyeus/KnickAI | c17d808c949cb3467031498e7252bd2095c04699 | [
"MIT"
] | 3 | 2021-11-13T09:38:12.000Z | 2022-03-25T07:44:17.000Z |
#NOT YET WORKING PROPERLY
#NOT INTEGRATED WITH THE ASSISTANT YET
from pytrends.request import TrendReq
# Only need to run this once, the rest of requests will use the same session.
pytrend = TrendReq()
if __name__ == '__main__':
console_trends() | 35.960784 | 187 | 0.657034 |
00394b6eff0f3c670ab13b288147b361f3297dc6 | 4,902 | py | Python | Speedo/helpers/convert.py | aviskumar/speedo | 758e8ac1fdeeb0b72c3a57742032ca5c79f0b2fa | [
"BSD-3-Clause"
] | null | null | null | Speedo/helpers/convert.py | aviskumar/speedo | 758e8ac1fdeeb0b72c3a57742032ca5c79f0b2fa | [
"BSD-3-Clause"
] | null | null | null | Speedo/helpers/convert.py | aviskumar/speedo | 758e8ac1fdeeb0b72c3a57742032ca5c79f0b2fa | [
"BSD-3-Clause"
] | 3 | 2021-10-12T08:17:01.000Z | 2021-12-21T01:17:54.000Z | import os
import asyncio
import re
import requests
import time
import lottie
import PIL.ImageOps
from os.path import basename
from PIL import Image
from typing import Optional
from .. import LOGS
from ..config import Config
from ..utils.extras import edit_or_reply as eor
from .progress import *
from .runner import runcmd
dwlpath = Config.TMP_DOWNLOAD_DIRECTORY
# convertions are done here...
# make a image
def tgs_to_gif(sticker_path: str, quality: int = 256) -> str:
semx = os.path.join(dwlpath, "Speedotgs.gif")
with open(semx, 'wb') as t_g:
lottie.exporters.gif.export_gif(lottie.parsers.tgs.parse_tgs(sticker_path), t_g, quality, 1)
os.remove(sticker_path)
return semx
# deal with it...
EMOJI_PATTERN = re.compile(
"["
"\U0001F1E0-\U0001F1FF" # flags (iOS)
"\U0001F300-\U0001F5FF" # symbols & pictographs
"\U0001F600-\U0001F64F" # emoticons
"\U0001F680-\U0001F6FF" # transport & map symbols
"\U0001F700-\U0001F77F" # alchemical symbols
"\U0001F780-\U0001F7FF" # Geometric Shapes Extended
"\U0001F800-\U0001F8FF" # Supplemental Arrows-C
"\U0001F900-\U0001F9FF" # Supplemental Symbols and Pictographs
"\U0001FA00-\U0001FA6F" # Chess Symbols
"\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A
"\U00002702-\U000027B0" # Dingbats
"]+"
)
def deEmojify(inputString: str) -> str:
"""Remove emojis and other non-safe characters from string"""
return re.sub(EMOJI_PATTERN, "", inputString)
# Speedo
| 33.346939 | 101 | 0.625663 |
0039f4a3f7a0d18a245aaaaea7e026a31503a73d | 453 | py | Python | src/api/celery.py | Anfevazu/library-api-R5 | 6930226776d0146b7daa34151ee98457f202dbc5 | [
"MIT"
] | null | null | null | src/api/celery.py | Anfevazu/library-api-R5 | 6930226776d0146b7daa34151ee98457f202dbc5 | [
"MIT"
] | null | null | null | src/api/celery.py | Anfevazu/library-api-R5 | 6930226776d0146b7daa34151ee98457f202dbc5 | [
"MIT"
] | null | null | null | from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings.'+os.environ.get('APP_ENV', 'local'))
app = Celery('app')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
| 26.647059 | 76 | 0.739514 |
003c4c33a5e695c65aafeb6d426e17f7228d37ef | 12,953 | py | Python | assemblyline_service_server/api/v1/task.py | CybercentreCanada/assemblyline-service-server | f4fbc7dcab122fa63fcc598db1c23a770c10145f | [
"MIT"
] | 6 | 2020-06-29T14:32:24.000Z | 2022-01-03T19:40:39.000Z | assemblyline_service_server/api/v1/task.py | CybercentreCanada/assemblyline-service-server | f4fbc7dcab122fa63fcc598db1c23a770c10145f | [
"MIT"
] | null | null | null | assemblyline_service_server/api/v1/task.py | CybercentreCanada/assemblyline-service-server | f4fbc7dcab122fa63fcc598db1c23a770c10145f | [
"MIT"
] | 2 | 2021-01-15T18:31:17.000Z | 2021-05-29T15:57:08.000Z | import time
from typing import cast, Dict, Any
from flask import request
from assemblyline.common import forge
from assemblyline.common.constants import SERVICE_STATE_HASH, ServiceStatus
from assemblyline.common.dict_utils import flatten, unflatten
from assemblyline.common.forge import CachedObject
from assemblyline.common.heuristics import HeuristicHandler, InvalidHeuristicException
from assemblyline.common.isotime import now_as_iso
from assemblyline.odm import construct_safe
from assemblyline.odm.messages.service_heartbeat import Metrics
from assemblyline.odm.messages.task import Task as ServiceTask
from assemblyline.odm.models.error import Error
from assemblyline.odm.models.heuristic import Heuristic
from assemblyline.odm.models.result import Result
from assemblyline.odm.models.tagging import Tagging
from assemblyline.remote.datatypes.exporting_counter import export_metrics_once
from assemblyline.remote.datatypes.hash import ExpiringHash
from assemblyline_core.dispatching.client import DispatchClient
from assemblyline_service_server.api.base import make_subapi_blueprint, make_api_response, api_login
from assemblyline_service_server.config import FILESTORE, LOGGER, STORAGE, config
from assemblyline_service_server.helper.heuristics import get_heuristics
status_table = ExpiringHash(SERVICE_STATE_HASH, ttl=60*30)
dispatch_client = DispatchClient(STORAGE)
heuristics = cast(Dict[str, Heuristic], CachedObject(get_heuristics, refresh=300))
heuristic_hander = HeuristicHandler(STORAGE)
tag_safelister = CachedObject(forge.get_tag_safelister,
kwargs=dict(log=LOGGER, config=config, datastore=STORAGE),
refresh=300)
SUB_API = 'task'
task_api = make_subapi_blueprint(SUB_API, api_version=1)
task_api._doc = "Perform operations on service tasks"
def handle_task_result(exec_time: int, task: ServiceTask, result: Dict[str, Any], client_info: Dict[str, str],
freshen: bool):
archive_ts = now_as_iso(config.datastore.ilm.days_until_archive * 24 * 60 * 60)
if task.ttl:
expiry_ts = now_as_iso(task.ttl * 24 * 60 * 60)
else:
expiry_ts = None
# Check if all files are in the filestore
if freshen:
missing_files = []
for f in result['response']['extracted'] + result['response']['supplementary']:
cur_file_info = STORAGE.file.get_if_exists(f['sha256'], as_obj=False)
if cur_file_info is None or not FILESTORE.exists(f['sha256']):
missing_files.append(f['sha256'])
else:
cur_file_info['archive_ts'] = archive_ts
cur_file_info['expiry_ts'] = expiry_ts
cur_file_info['classification'] = f['classification']
STORAGE.save_or_freshen_file(f['sha256'], cur_file_info,
cur_file_info['expiry_ts'], cur_file_info['classification'],
is_section_image=f.get('is_section_image', False))
if missing_files:
return missing_files
service_name = client_info['service_name']
client_id = client_info['client_id']
# Add scores to the heuristics, if any section set a heuristic
total_score = 0
for section in result['result']['sections']:
zeroize_on_sig_safe = section.pop('zeroize_on_sig_safe', True)
section['tags'] = flatten(section['tags'])
if section.get('heuristic'):
heur_id = f"{client_info['service_name'].upper()}.{str(section['heuristic']['heur_id'])}"
section['heuristic']['heur_id'] = heur_id
try:
section['heuristic'], new_tags = heuristic_hander.service_heuristic_to_result_heuristic(
section['heuristic'], heuristics, zeroize_on_sig_safe)
for tag in new_tags:
section['tags'].setdefault(tag[0], [])
if tag[1] not in section['tags'][tag[0]]:
section['tags'][tag[0]].append(tag[1])
total_score += section['heuristic']['score']
except InvalidHeuristicException:
section['heuristic'] = None
# Update the total score of the result
result['result']['score'] = total_score
# Add timestamps for creation, archive and expiry
result['created'] = now_as_iso()
result['archive_ts'] = archive_ts
result['expiry_ts'] = expiry_ts
# Pop the temporary submission data
temp_submission_data = result.pop('temp_submission_data', None)
# Process the tag values
for section in result['result']['sections']:
# Perform tag safelisting
tags, safelisted_tags = tag_safelister.get_validated_tag_map(section['tags'])
section['tags'] = unflatten(tags)
section['safelisted_tags'] = safelisted_tags
section['tags'], dropped = construct_safe(Tagging, section.get('tags', {}))
# Set section score to zero and lower total score if service is set to zeroize score
# and all tags were safelisted
if section.pop('zeroize_on_tag_safe', False) and \
section.get('heuristic') and \
len(tags) == 0 and \
len(safelisted_tags) != 0:
result['result']['score'] -= section['heuristic']['score']
section['heuristic']['score'] = 0
if dropped:
LOGGER.warning(f"[{task.sid}] Invalid tag data from {client_info['service_name']}: {dropped}")
result = Result(result)
result_key = result.build_key(service_tool_version=result.response.service_tool_version, task=task)
dispatch_client.service_finished(task.sid, result_key, result, temp_submission_data)
# Metrics
if result.result.score > 0:
export_metrics_once(service_name, Metrics, dict(scored=1), host=client_id, counter_type='service')
else:
export_metrics_once(service_name, Metrics, dict(not_scored=1), host=client_id, counter_type='service')
LOGGER.info(f"[{task.sid}] {client_info['client_id']} - {client_info['service_name']} "
f"successfully completed task {f' in {exec_time}ms' if exec_time else ''}")
def handle_task_error(exec_time: int, task: ServiceTask, error: Dict[str, Any], client_info: Dict[str, str]) -> None:
service_name = client_info['service_name']
client_id = client_info['client_id']
LOGGER.info(f"[{task.sid}] {client_info['client_id']} - {client_info['service_name']} "
f"failed to complete task {f' in {exec_time}ms' if exec_time else ''}")
# Add timestamps for creation, archive and expiry
error['created'] = now_as_iso()
error['archive_ts'] = now_as_iso(config.datastore.ilm.days_until_archive * 24 * 60 * 60)
if task.ttl:
error['expiry_ts'] = now_as_iso(task.ttl * 24 * 60 * 60)
error = Error(error)
error_key = error.build_key(service_tool_version=error.response.service_tool_version, task=task)
dispatch_client.service_failed(task.sid, error_key, error)
# Metrics
if error.response.status == 'FAIL_RECOVERABLE':
export_metrics_once(service_name, Metrics, dict(fail_recoverable=1), host=client_id, counter_type='service')
else:
export_metrics_once(service_name, Metrics, dict(fail_nonrecoverable=1), host=client_id, counter_type='service')
| 42.608553 | 119 | 0.63576 |
003c669ec9b5a285ed0283853c1db390654e252e | 3,627 | py | Python | install/app_store/tk-framework-qtwidgets/v2.6.5/python/search_completer/global_search_result_delegate.py | JoanAzpeitia/lp_sg | e0ee79555e419dd2ae3a5f31e5515b3f40b22a62 | [
"MIT"
] | null | null | null | install/app_store/tk-framework-qtwidgets/v2.6.5/python/search_completer/global_search_result_delegate.py | JoanAzpeitia/lp_sg | e0ee79555e419dd2ae3a5f31e5515b3f40b22a62 | [
"MIT"
] | null | null | null | install/app_store/tk-framework-qtwidgets/v2.6.5/python/search_completer/global_search_result_delegate.py | JoanAzpeitia/lp_sg | e0ee79555e419dd2ae3a5f31e5515b3f40b22a62 | [
"MIT"
] | 1 | 2020-02-15T10:42:56.000Z | 2020-02-15T10:42:56.000Z | # Copyright (c) 2017 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
import sgtk
from sgtk.platform.qt import QtCore
from .search_result_delegate import SearchResultDelegate
# import the shotgun_model and view modules from the shotgun utils framework
shotgun_model = sgtk.platform.import_framework("tk-framework-shotgunutils", "shotgun_model")
shotgun_globals = sgtk.platform.import_framework("tk-framework-shotgunutils", "shotgun_globals")
views = sgtk.platform.current_bundle().import_module("views")
| 38.585106 | 115 | 0.650675 |
003ca20243cae85d6e1700ea19f81a8feb7a525d | 36 | py | Python | clarity/Alignment/__init__.py | wjguan/phenocell | 80ff7a0b5cc9e1ecedd8fe488b81a3df120096d9 | [
"MIT"
] | null | null | null | clarity/Alignment/__init__.py | wjguan/phenocell | 80ff7a0b5cc9e1ecedd8fe488b81a3df120096d9 | [
"MIT"
] | null | null | null | clarity/Alignment/__init__.py | wjguan/phenocell | 80ff7a0b5cc9e1ecedd8fe488b81a3df120096d9 | [
"MIT"
] | null | null | null | __all__ = ['Elastix', 'Resampling']; | 36 | 36 | 0.666667 |
003d3548a8cf8ece40ea1e41ad2dd7fe0e795e6b | 398 | py | Python | heltour/tournament/migrations/0086_auto_20160901_2352.py | zbidwell/heltour | 3895142695096a81cc65c3fefb7d4501ed796f46 | [
"MIT"
] | 41 | 2016-08-17T19:58:42.000Z | 2021-11-08T10:52:07.000Z | heltour/tournament/migrations/0086_auto_20160901_2352.py | zbidwell/heltour | 3895142695096a81cc65c3fefb7d4501ed796f46 | [
"MIT"
] | 257 | 2016-08-17T22:29:05.000Z | 2022-01-13T00:42:05.000Z | heltour/tournament/migrations/0086_auto_20160901_2352.py | zbidwell/heltour | 3895142695096a81cc65c3fefb7d4501ed796f46 | [
"MIT"
] | 31 | 2016-09-23T23:36:14.000Z | 2022-01-14T17:05:08.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-01 23:52
from django.db import migrations
| 19.9 | 59 | 0.600503 |
003db226f92b023c219ed5b17f0367bc583465db | 124,728 | py | Python | ros_bt_py/test/unittest/test_tree_manager.py | fzi-forschungszentrum-informatik/ros_bt_py | ed65e2b2f0a03411101f455c0ab38401ba50bada | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 4 | 2022-03-11T14:30:43.000Z | 2022-03-31T07:21:35.000Z | ros_bt_py/test/unittest/test_tree_manager.py | fzi-forschungszentrum-informatik/ros_bt_py | ed65e2b2f0a03411101f455c0ab38401ba50bada | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | ros_bt_py/test/unittest/test_tree_manager.py | fzi-forschungszentrum-informatik/ros_bt_py | ed65e2b2f0a03411101f455c0ab38401ba50bada | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | # -------- BEGIN LICENSE BLOCK --------
# Copyright 2022 FZI Forschungszentrum Informatik
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of the {copyright_holder} nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# -------- END LICENSE BLOCK --------
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
import sys
import time
from ros_bt_py_msgs.msg import Node as NodeMsg, Message, Package
from ros_bt_py_msgs.msg import NodeData, NodeDataWiring, NodeDataLocation, Tree
from ros_bt_py_msgs.srv import (WireNodeDataRequest, AddNodeRequest, RemoveNodeRequest,
ControlTreeExecutionRequest, GetAvailableNodesRequest,
SetExecutionModeRequest, SetOptionsRequest, ContinueRequest,
LoadTreeRequest, MoveNodeRequest, ReplaceNodeRequest,
MorphNodeRequest, ClearTreeRequest, LoadTreeFromPathRequest,
SetExecutionModeResponse, ModifyBreakpointsRequest,
GetSubtreeRequest, ReloadTreeRequest, WireNodeDataResponse,
RemoveNodeResponse, GenerateSubtreeRequest, AddNodeAtIndexRequest,
ChangeTreeNameRequest)
from ros_bt_py.node import Node, Leaf, FlowControl, define_bt_node
from ros_bt_py.node_config import NodeConfig
from ros_bt_py.nodes.sequence import Sequence
from ros_bt_py.nodes.mock_nodes import MockLeaf
from ros_bt_py.exceptions import BehaviorTreeException, MissingParentError, TreeTopologyError
from ros_bt_py.tree_manager import TreeManager
from ros_bt_py.tree_manager import (get_success as tm_get_success,
get_error_message as tm_get_error_message)
from ros_bt_py.helpers import json_encode, json_decode
from ros_bt_py.ros_helpers import LoggerLevel
try:
unicode
except NameError:
unicode = str
def get_success(response):
if isinstance(response, dict):
return response['success']
return response.success
def get_error_message(response):
if isinstance(response, dict):
return response['error_message']
return response.error_message
| 43.113723 | 99 | 0.641372 |
003dc875c6b6a3c3cf3b1f0f40f7270a5adb32a6 | 225 | py | Python | examples/plugins/dummy/dummy/main.py | mikiec84/gaffer | 8c5d5b5e2ff3fcb1f7cc7c8fbfc623f97dd0da8d | [
"MIT",
"Unlicense"
] | null | null | null | examples/plugins/dummy/dummy/main.py | mikiec84/gaffer | 8c5d5b5e2ff3fcb1f7cc7c8fbfc623f97dd0da8d | [
"MIT",
"Unlicense"
] | null | null | null | examples/plugins/dummy/dummy/main.py | mikiec84/gaffer | 8c5d5b5e2ff3fcb1f7cc7c8fbfc623f97dd0da8d | [
"MIT",
"Unlicense"
] | 1 | 2018-10-28T00:59:17.000Z | 2018-10-28T00:59:17.000Z | from gaffer import Plugin
__all__ = ['DummyPlugin']
from .app import DummyApp
| 14.0625 | 26 | 0.635556 |
003e8e2269ee664c19971a3c8f0ad03c45a56847 | 2,485 | py | Python | preprocessing/generate_diffs.py | windysavage/dfdc_deepfake_challenge | d10b54cf933282366157a031954b046d87d57009 | [
"MIT"
] | null | null | null | preprocessing/generate_diffs.py | windysavage/dfdc_deepfake_challenge | d10b54cf933282366157a031954b046d87d57009 | [
"MIT"
] | null | null | null | preprocessing/generate_diffs.py | windysavage/dfdc_deepfake_challenge | d10b54cf933282366157a031954b046d87d57009 | [
"MIT"
] | null | null | null | import numpy as np
import cv2
from preprocessing.utils import get_original_with_fakes
from tqdm import tqdm
from multiprocessing.pool import Pool
from functools import partial
# from skimage.measure import compare_ssim
from skimage import metrics
import argparse
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
cv2.ocl.setUseOpenCL(False)
cv2.setNumThreads(0)
cache = {}
if __name__ == '__main__':
main()
| 31.858974 | 70 | 0.612475 |
003fa9552b48b33e85beb33eaf261aef70d7ae40 | 18,905 | py | Python | Model/model_v2.py | Insper-Data/data_bcg_news | 49986db18095759adea00bb0dedc149acebb683b | [
"MIT"
] | null | null | null | Model/model_v2.py | Insper-Data/data_bcg_news | 49986db18095759adea00bb0dedc149acebb683b | [
"MIT"
] | null | null | null | Model/model_v2.py | Insper-Data/data_bcg_news | 49986db18095759adea00bb0dedc149acebb683b | [
"MIT"
] | null | null | null | import ast
import community
import datetime
import lightgbm as lgb
import math
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import pickle
import plotly.express as px
import os
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score
from tqdm import tqdm
from make_boruta import *
| 41.187364 | 118 | 0.598678 |
00433726aac3c77abe8b0c9529d3eb24d0cd9286 | 1,074 | py | Python | recipe_app/forms.py | dbobbgit/recipebox | 8e4e5c6f609e2524726954c9382ca37e844721f9 | [
"MIT"
] | null | null | null | recipe_app/forms.py | dbobbgit/recipebox | 8e4e5c6f609e2524726954c9382ca37e844721f9 | [
"MIT"
] | null | null | null | recipe_app/forms.py | dbobbgit/recipebox | 8e4e5c6f609e2524726954c9382ca37e844721f9 | [
"MIT"
] | null | null | null | from django import forms
from recipe_app.models import Author
from django.contrib.auth.forms import UserCreationForm
# Create two forms: RecipeForm & AuthorForm
"""
Author:
- Name: CharField
- Bio: TextField
Recipe:
- Title: CharField
- Author: ForeignKey
- Description: TextField
- Time Required: CharField (for example, "One hour")
- Instructions: TextField
"""
| 26.195122 | 66 | 0.685289 |
0044e564b42a943f2371101ac16d4cb0e1aee8d7 | 42,840 | py | Python | roosterize/data/DataMiner.py | EngineeringSoftware/roosterize | 2990f7bdef8889045a26f3e9aaaca96d9c92e0bc | [
"MIT"
] | 16 | 2020-06-05T20:01:56.000Z | 2022-02-09T16:10:09.000Z | roosterize/data/DataMiner.py | EngineeringSoftware/roosterize | 2990f7bdef8889045a26f3e9aaaca96d9c92e0bc | [
"MIT"
] | 6 | 2020-07-02T15:22:36.000Z | 2020-12-16T13:04:16.000Z | roosterize/data/DataMiner.py | EngineeringSoftware/roosterize | 2990f7bdef8889045a26f3e9aaaca96d9c92e0bc | [
"MIT"
] | 3 | 2020-07-21T17:37:51.000Z | 2020-12-10T05:36:32.000Z | from typing import *
import collections
import copy
import hashlib
import math
import numpy as np
from pathlib import Path
import random
import re
from tqdm import tqdm
import traceback
import sys
from seutil import LoggingUtils, IOUtils, BashUtils
from seutil.project import Project
from roosterize.data.CoqDocument import CoqDocument
from roosterize.FilesManager import FilesManager
from roosterize.data.Definition import Definition
from roosterize.data.Lemma import Lemma
from roosterize.data.LemmaBackendSexpTransformers import LemmaBackendSexpTransformers
from roosterize.data.LemmaForeendSexpTransformers import LemmaForeendSexpTransformers
from roosterize.Environment import Environment
from roosterize.Macros import Macros
from roosterize.parser.CoqParser import CoqParser
from roosterize.parser.ParserUtils import ParserUtils
from roosterize.parser.SexpAnalyzer import SexpAnalyzer, SexpInfo
from roosterize.sexp import *
from roosterize.Utils import Utils
| 49.016018 | 259 | 0.639519 |
00464d29c3ee1cf1c9de61907d49f9253edbd2f3 | 965 | py | Python | venv/Lib/site-packages/gensim/similarities/__init__.py | saritmaitra/nlp_ner_topic_modeling | 70914b4ae4cd7d3b9cb10776161132216394883c | [
"MIT"
] | 3 | 2021-03-29T19:21:08.000Z | 2021-12-31T09:30:11.000Z | VisionAPI/lib/python3.8/site-packages/gensim/similarities/__init__.py | aniruddhakj/AnswerScriptEvaluation | 7b039b84355ecda1d55dc037ccfc4a4d661ad5e3 | [
"BSD-3-Clause"
] | 1 | 2021-08-30T08:53:09.000Z | 2021-08-30T08:53:09.000Z | venv/Lib/site-packages/gensim/similarities/__init__.py | saritmaitra/nlp_ner_topic_modeling | 70914b4ae4cd7d3b9cb10776161132216394883c | [
"MIT"
] | 1 | 2021-03-30T05:02:53.000Z | 2021-03-30T05:02:53.000Z | """
This package contains implementations of pairwise similarity queries.
"""
# bring classes directly into package namespace, to save some typing
import warnings
try:
import Levenshtein # noqa:F401
except ImportError:
msg = (
"The gensim.similarities.levenshtein submodule is disabled, because the optional "
"Levenshtein package <https://pypi.org/project/python-Levenshtein/> is unavailable. "
"Install Levenhstein (e.g. `pip install python-Levenshtein`) to suppress this warning."
)
warnings.warn(msg)
LevenshteinSimilarityIndex = None
else:
from .levenshtein import LevenshteinSimilarityIndex # noqa:F401
from .docsim import ( # noqa:F401
Similarity,
MatrixSimilarity,
SparseMatrixSimilarity,
SoftCosineSimilarity,
WmdSimilarity)
from .termsim import ( # noqa:F401
TermSimilarityIndex,
UniformTermSimilarityIndex,
WordEmbeddingSimilarityIndex,
SparseTermSimilarityMatrix)
| 32.166667 | 95 | 0.741969 |
0046656ceee49a476e8e983594a595e1bad5bf96 | 27 | py | Python | tpucolab/__init__.py | taomanwai/tpucolab | b822cc145987db96cfb0052dbb10934bedd005e6 | [
"MIT"
] | 1 | 2021-12-24T23:53:08.000Z | 2021-12-24T23:53:08.000Z | tpucolab/__init__.py | taomanwai/tpucolab | b822cc145987db96cfb0052dbb10934bedd005e6 | [
"MIT"
] | null | null | null | tpucolab/__init__.py | taomanwai/tpucolab | b822cc145987db96cfb0052dbb10934bedd005e6 | [
"MIT"
] | 2 | 2018-12-16T14:08:54.000Z | 2019-05-28T14:41:59.000Z | from tpucolab.core import * | 27 | 27 | 0.814815 |
004abcc62f87b11013e726a8b69a3c514744935d | 1,858 | py | Python | src/PIDController.py | methylDragon/momo-emotions | 137161632cc45227884d1a7a46dbd75d261de371 | [
"BSD-2-Clause"
] | 11 | 2019-05-24T00:25:59.000Z | 2021-05-17T07:08:58.000Z | src/PIDController.py | methylDragon/momo-emotions | 137161632cc45227884d1a7a46dbd75d261de371 | [
"BSD-2-Clause"
] | null | null | null | src/PIDController.py | methylDragon/momo-emotions | 137161632cc45227884d1a7a46dbd75d261de371 | [
"BSD-2-Clause"
] | 10 | 2019-06-21T02:38:45.000Z | 2021-07-07T04:50:39.000Z | import time
| 27.731343 | 80 | 0.595264 |
004b29aa8664031730012b088eba2ecb4c151bb6 | 1,420 | py | Python | tilty/emitters/sqlite.py | heresurpizza/tilty | 758fc2513b5fb660ac11163941340e4c10f61081 | [
"MIT"
] | 13 | 2020-02-27T03:07:50.000Z | 2022-01-02T20:01:57.000Z | tilty/emitters/sqlite.py | heresurpizza/tilty | 758fc2513b5fb660ac11163941340e4c10f61081 | [
"MIT"
] | 10 | 2020-03-04T14:57:59.000Z | 2021-07-23T03:54:17.000Z | tilty/emitters/sqlite.py | heresurpizza/tilty | 758fc2513b5fb660ac11163941340e4c10f61081 | [
"MIT"
] | 8 | 2020-03-15T02:23:10.000Z | 2020-11-25T12:42:37.000Z | # -*- coding: utf-8 -*-
""" SQLite emitter """
import logging
import sqlite3
LOGGER = logging.getLogger()
| 26.792453 | 73 | 0.527465 |
004de3fdbd877d9dca8c67922ef30d1cf30e4c3c | 6,043 | py | Python | IFishFarm.py | HussamElden/IFishFarm | c49acc997229b9ae0649d9e4765255cb2db02bfc | [
"CECILL-B"
] | 1 | 2021-08-03T13:24:38.000Z | 2021-08-03T13:24:38.000Z | IFishFarm.py | HussamElden/IFishFarm | c49acc997229b9ae0649d9e4765255cb2db02bfc | [
"CECILL-B"
] | null | null | null | IFishFarm.py | HussamElden/IFishFarm | c49acc997229b9ae0649d9e4765255cb2db02bfc | [
"CECILL-B"
] | 2 | 2021-01-12T11:25:11.000Z | 2022-03-11T21:25:53.000Z | import cv2
import numpy as np
from numpy.linalg import norm
import math
import csv
from operator import itemgetter
from datetime import datetime
import VideoEnhancement
import fishpredictor
import detector
import kmeancluster
import preproccesing
import randomforst
cluster = kmeancluster.kmeans()
classifier = randomforst.randomforst()
samak = []
framenum = 0
sum = 0
max = 0
mylist = [[]]
yolo = detector.detector()
cap = cv2.VideoCapture('chaos1.avi')
ret, frame = cap.read()
fheight, fwidth, channels = frame.shape
resize = False
if (fheight > 352 or fwidth > 640):
resize = True
fwidth = 640
fheight = 352
frame = cv2.resize(frame, (640, 352))
mask = np.zeros_like(frame)
# Needed for saving video
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
dt_string = datetime.now().strftime("%H_%M_%S_%d_%m_%y")
num_seconds = 10
video = cv2.VideoWriter('videonormal/' +str(num_seconds*round(fps))+'_'+str(dt_string)+'.avi', fourcc, fps, (fwidth, fheight))
# Read until video is completed
counter = 0
buffer = [[]]
apperance = [[]]
last_changed = []
top = 0
frms = 0
# Needed to track objects
n_frame = 8
ref_n_frame_axies = []
ref_n_frame_label = []
ref_n_frame_axies_flatten = []
ref_n_frame_label_flatten = []
frm_num = 1
coloredLine = np.random.randint(0, 255, (10000, 3))
arr = []
label_cnt = 1
min_distance = 50
while (cap.isOpened()):
ret, img = cap.read()
if ret == True:
if frms % 2 == 0:
img = VideoEnhancement.enhanceVideo(img, resize)
v = 0
cur_frame_axies = []
cur_frame_label = []
height, width, channels = img.shape
boxes, confidences, centers, colors = yolo.detect(img)
counter += 1
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.1, 0.4)
font = cv2.FONT_HERSHEY_PLAIN
fishcounter = 1
for i in range(len(boxes)):
if i in indexes:
lbl = float('nan')
x, y, w, h, = boxes[i]
center_x, center_y = centers[i]
color = colors[0]
if (len(ref_n_frame_label_flatten) > 0):
b = np.array([(center_x, center_y)])
a = np.array(ref_n_frame_axies_flatten)
distance = norm(a - b, axis=1)
min_value = distance.min()
if (min_value < min_distance):
idx = np.where(distance == min_value)[0][0]
lbl = ref_n_frame_label_flatten[idx]
points = (int(ref_n_frame_axies_flatten[idx][0]), int(ref_n_frame_axies_flatten[idx][1]))
mask = cv2.line(mask, (center_x, center_y), points, coloredLine[lbl].tolist(), 2)
cv2.circle(img, points, 5, coloredLine[lbl].tolist(), -1)
if (math.isnan(lbl)):
lbl = label_cnt
label_cnt += 1
arr.append([counter, lbl, center_x, center_y])
cur_frame_label.append(lbl)
cur_frame_axies.append((center_x, center_y))
samak.append([lbl, x, y, w, h])
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, '{}{}'.format("Fish", lbl), (x, y - 5), font, 1, (255, 255, 255), 2)
if (len(ref_n_frame_axies) == n_frame):
del ref_n_frame_axies[0]
del ref_n_frame_label[0]
ref_n_frame_label.append(cur_frame_label)
ref_n_frame_axies.append(cur_frame_axies)
ref_n_frame_axies_flatten = [a for ref_n_frame_axie in ref_n_frame_axies for a in ref_n_frame_axie]
ref_n_frame_label_flatten = [b for ref_n_frame_lbl in ref_n_frame_label for b in ref_n_frame_lbl]
z = sorted(samak, key=itemgetter(0))
samak = []
if (len(z) != 0):
fishpredictor.predictfish(z, apperance, buffer, last_changed, top, img, color, mylist, framenum)
img = cv2.add(img, mask)
# cv2.imshow("Image", img)
mylist.append([])
framenum += 1
print(frms)
print("----------")
# cap.set(1,frms)
video.write(img)
if (frms % (round(fps) * num_seconds) == 0 and frms!=0):
result = cluster.classify(mask)
print(classifier.classify(z, mask,fps))
if (result == 1):
with open('exceltext/' + str(frms)+'_'+str(dt_string)+ '.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(mylist)
# writer.writerows(preproccesing.featuresCalc(mylist))
cv2.imwrite("trajecstest" + str(frms)+'_'+str(dt_string) + ".png", mask)
video.release()
dt_string = datetime.now().strftime("%H_%M_%S_%d_%m_%y")
video = cv2.VideoWriter('videotest/' + str(frms+(num_seconds*round(fps)))+'_'+str(dt_string)+'.avi', fourcc, fps,
(fwidth, fheight))
print("result " + str(result))
mask = np.zeros_like(frame)
ref_n_frame_axies = []
ref_n_frame_label = []
ref_n_frame_axies_flatten = []
ref_n_frame_label_flatten = []
buffer = [[]]
apperance = [[]]
last_changed = []
# frms = 0
counter = 0
mylist = [[]]
framenum = 0
fishcounter = 1
label_cnt = 1
top = 0
if cv2.waitKey(25) & 0xFF == ord('q'):
break
# Break the loop
else:
break
frms += 1
cap.release()
cv2.destroyAllWindows()
video.release() | 35.547059 | 133 | 0.529869 |
004ed29e696ed2aef36a881fbaccde0ba220306d | 889 | py | Python | nanopores/geometries/W_3D_geo/params_geo.py | jhwnkim/nanopores | 98b3dbb5d36464fbdc03f59d224d38e4255324ce | [
"MIT"
] | 8 | 2016-09-07T01:59:31.000Z | 2021-03-06T12:14:31.000Z | nanopores/geometries/W_3D_geo/params_geo.py | jhwnkim/nanopores | 98b3dbb5d36464fbdc03f59d224d38e4255324ce | [
"MIT"
] | null | null | null | nanopores/geometries/W_3D_geo/params_geo.py | jhwnkim/nanopores | 98b3dbb5d36464fbdc03f59d224d38e4255324ce | [
"MIT"
] | 4 | 2017-12-06T17:43:01.000Z | 2020-05-01T05:41:14.000Z | """ --- geometry parameters for Wei et al stochastic sensing --- """
nm = 1e-0
# @TODO maybe include tolc in parent file
tolc = 1e-2*nm # tolerance for coordinate comparisons
dim = 3
# molecule radius
rMolecule = 5*nm
# effective pore radius ~ d^SAM_p/2
r0 = 13*nm
# aperture angle in degrees
angle = 40
# SiN membrane thickness (in vertical direction)
lsin = 50*nm
# Au membrane thickness (in vertical direction)
lau = 40*nm
# Au thickness in radial direction
rlau = 10*nm
# SAM layer thickness (in vertical direction)
lsam = 3*nm
# Radius of domain
Rz = 150.0*nm
R = 150.0*nm
# fraction of R which is considered as outer membrane boundary
outerfrac = 0.3
# mesh generation parameters
# length scales
lc = 10*nm
lcMolecule = lc*1e-1
lcOuter = lc*5
lcCenter = lc/5
# provide default values for boundary layer around membrane/molecule
membraneblayer = None
moleculeblayer = None
| 20.204545 | 68 | 0.730034 |
004faf5abb1b54060367d19932230f631232c8a0 | 254 | py | Python | Testing/send_test.py | jaronoff97/Flask-Boilerplate | f750f10274f84ba6682e65b3e9eb7d900813ee21 | [
"CC0-1.0"
] | null | null | null | Testing/send_test.py | jaronoff97/Flask-Boilerplate | f750f10274f84ba6682e65b3e9eb7d900813ee21 | [
"CC0-1.0"
] | null | null | null | Testing/send_test.py | jaronoff97/Flask-Boilerplate | f750f10274f84ba6682e65b3e9eb7d900813ee21 | [
"CC0-1.0"
] | null | null | null | import requests
sample_user = {"latitude" : 42.2561110, "longitude" : -71.0741010, "uid" : "0" , "first_name" : "alex", "last_name" : "iansiti"}
send_url = "http://flask-macoder.rhcloud.com/near"
r = requests.post(send_url, sample_user)
print(r.json()) | 36.285714 | 128 | 0.685039 |
005275ffc230ec92bee5ce893b5981ac62fa9054 | 3,293 | py | Python | library/ucs_vlan_find.py | dsoper2/ucsm-ansible-1 | 9eef898d016e8e2c5f07990385ec1b8885edc533 | [
"NTP"
] | 54 | 2017-05-30T19:22:23.000Z | 2021-12-17T07:36:55.000Z | library/ucs_vlan_find.py | dsoper2/ucsm-ansible-1 | 9eef898d016e8e2c5f07990385ec1b8885edc533 | [
"NTP"
] | 50 | 2017-05-10T07:37:09.000Z | 2021-07-26T18:23:30.000Z | library/ucs_vlan_find.py | dsoper2/ucsm-ansible-1 | 9eef898d016e8e2c5f07990385ec1b8885edc533 | [
"NTP"
] | 54 | 2017-05-08T05:31:23.000Z | 2021-11-16T09:34:32.000Z | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: ucs_vlan_find
short_description: Find VLANs on Cisco UCS Manager
description:
- Find VLANs on Cisco UCS Manager based on different criteria.
extends_documentation_fragment: ucs
options:
pattern:
description:
- Regex pattern to find within the name property of the fabricVlan class.
- This is required if C(vlanid) parameter is not supplied.
type: str
fabric:
description:
- "The fabric configuration of the VLAN. This can be one of the following:"
- "common - The VLAN applies to both fabrics and uses the same configuration parameters in both cases."
- "A The VLAN only applies to fabric A."
- "B The VLAN only applies to fabric B."
choices: [common, A, B]
default: common
type: str
vlanid:
description:
- The unique string identifier assigned to the VLAN.
- A VLAN ID can be between '1' and '3967', or between '4048' and '4093'.
- This is required if C(pattern) parameter is not supplied.
type: str
requirements:
- ucsmsdk
author:
- David Martinez (@dx0xm)
- CiscoUcs (@CiscoUcs)
version_added: '2.9'
'''
EXAMPLES = r'''
- name: Get all vlans in fabric A
ucs_vlan_find:
hostname: 172.16.143.150
username: admin
password: password
fabric: 'A'
pattern: '.'
- name: Confirm if vlan 15 is present
ucs_vlan_find:
hostname: 172.16.143.150
username: admin
password: password
vlanid: '15'
'''
RETURN = r'''
vlan_list:
description: basic details of vlans found
returned: on success
type: list
sample: [
{
"id": "0",
"name": "vlcloud1"
}
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.remote_management.ucs import UCSModule, ucs_argument_spec
if __name__ == '__main__':
main()
| 26.991803 | 107 | 0.64379 |
0053cf487a42c750c2cd4aedb2f3962276b8ea47 | 1,660 | py | Python | pytf2/currency.py | mninc/pytf | 3dbf93f6c6b8edd7366f9fdb8f46ad84df3ac819 | [
"MIT"
] | 7 | 2018-03-09T22:50:31.000Z | 2021-08-09T10:17:45.000Z | pytf2/currency.py | mninc/pytf | 3dbf93f6c6b8edd7366f9fdb8f46ad84df3ac819 | [
"MIT"
] | 2 | 2019-06-19T19:18:34.000Z | 2020-08-20T11:10:09.000Z | pytf2/currency.py | mninc/pytf | 3dbf93f6c6b8edd7366f9fdb8f46ad84df3ac819 | [
"MIT"
] | 1 | 2019-08-15T08:23:32.000Z | 2019-08-15T08:23:32.000Z | from functools import total_ordering
| 24.411765 | 65 | 0.56747 |
cc363d4217d466323d8e71cf244f2eebe4bc0f84 | 6,251 | py | Python | course_valve/valve_core.py | sharpblade4/course_valve | 52f1ad5600c17bb9fe876b6cf1ed91151ce41498 | [
"Apache-2.0"
] | null | null | null | course_valve/valve_core.py | sharpblade4/course_valve | 52f1ad5600c17bb9fe876b6cf1ed91151ce41498 | [
"Apache-2.0"
] | null | null | null | course_valve/valve_core.py | sharpblade4/course_valve | 52f1ad5600c17bb9fe876b6cf1ed91151ce41498 | [
"Apache-2.0"
] | null | null | null | from typing import Tuple, Pattern
from urllib.request import urlopen
import os
from ftplib import FTP
from tempfile import TemporaryDirectory
from hashlib import sha256
import re
from course_valve.valve_defs import (
TARGET_FTP,
ENCRYPTED_PASSWORD,
TARGET_FILE_NAME,
IDENTIFIER,
NO_IDENTIFIER,
FTP_USER,
OPENED_TEMPLATE_NAME,
CLOSED_TEMPLATE_NAME,
TEMPLATES_TARGETS_PREFIX,
)
| 41.125 | 99 | 0.648216 |
cc3793708ffd8065396601385980cfad2d4740fe | 1,782 | py | Python | tests/test_base.py | mwibrow/vlnm | f3fc6ba1a207431bc12a457aab4ab847a584a66f | [
"AFL-3.0"
] | null | null | null | tests/test_base.py | mwibrow/vlnm | f3fc6ba1a207431bc12a457aab4ab847a584a66f | [
"AFL-3.0"
] | 4 | 2018-09-25T06:57:29.000Z | 2019-09-09T13:22:00.000Z | tests/test_base.py | mwibrow/vlnm | f3fc6ba1a207431bc12a457aab4ab847a584a66f | [
"AFL-3.0"
] | 1 | 2020-10-20T05:42:45.000Z | 2020-10-20T05:42:45.000Z | """
Tests for the base module
"""
from vlnm.normalizers.base import (
FormantGenericNormalizer,
FormantSpecificNormalizer,
FormantsTransformNormalizer,
Normalizer)
from tests.helpers import Helper
| 32.4 | 90 | 0.685746 |
cc37b7d3f91a095814758d351ed6ae362f360126 | 5,934 | py | Python | arbiter.py | camerongivler/bitcoin-utils | 86e7ba95ef016b24c33fe819a9879b387f7f70f9 | [
"MIT"
] | null | null | null | arbiter.py | camerongivler/bitcoin-utils | 86e7ba95ef016b24c33fe819a9879b387f7f70f9 | [
"MIT"
] | null | null | null | arbiter.py | camerongivler/bitcoin-utils | 86e7ba95ef016b24c33fe819a9879b387f7f70f9 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import os
import sys
import time
import traceback
from itertools import combinations
from multiprocessing.pool import ThreadPool
from exchangebase import ExchangeBase
from exchangepair import ExchangePair
from gdaxapi import Gdax
from krakenapi import Kraken
if __name__ == "__main__":
arbiter = Arbiter()
# Infinite loop
while True:
try:
arbiter.run()
except KeyboardInterrupt:
print("Goodbye.")
break
| 41.496503 | 117 | 0.531345 |
cc3a46291852e6e6df74967b9e59f3edcd3b7c15 | 2,289 | py | Python | demos/dlgr/demos/rumour_stuff_chain/extend_hit.py | allisonmorgan/Dallinger | f171e28c352854a3c6ed6b21f25362cd933b17dc | [
"MIT"
] | 1 | 2019-08-01T16:15:44.000Z | 2019-08-01T16:15:44.000Z | demos/dlgr/demos/rumour_stuff_chain/extend_hit.py | allisonmorgan/Dallinger | f171e28c352854a3c6ed6b21f25362cd933b17dc | [
"MIT"
] | null | null | null | demos/dlgr/demos/rumour_stuff_chain/extend_hit.py | allisonmorgan/Dallinger | f171e28c352854a3c6ed6b21f25362cd933b17dc | [
"MIT"
] | null | null | null | import boto3
import sys
import numpy as np
import random
import time
# endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'
endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com'
##Remember to put the AWS credential in ~/.aws/credential like below:
#######
#[default]
#aws_access_key_id = XXXXX
#aws_secret_access_key = XXXXXX
client = boto3.client('mturk',endpoint_url = endpoint_url,region_name='us-east-1')
#Number of participants
number_participants=int(sys.argv[1])
result_hits= client.list_hits()
number_of_parallel_hits=len(result_hits['HITs'])
vector_completed_experiments = np.zeros(number_of_parallel_hits)
# Check that all the experiments have been completed
while np.mean(vector_completed_experiments) != number_participants:
result_hits= client.list_hits()
number_of_parallel_hits=len(result_hits['HITs'])
vector_completed_experiments=np.zeros(number_of_parallel_hits)
for i in range(number_of_parallel_hits):
hits_completed=int(result_hits['HITs'][i]['NumberOfAssignmentsCompleted'])
vector_completed_experiments[i]=hits_completed
if hits_completed != number_participants:
##Checking if it is necessary to extend the HIT (Available and Pending HIT should be set to zero for extending)
if int(result_hits['HITs'][i]['NumberOfAssignmentsAvailable']) == 0 and int(result_hits['HITs'][i]['NumberOfAssignmentsPending']) == 0:
#There is a little bit of lag when checking whether the HIT has been completed, waiting 30 second to avoid this issue
time.sleep(30)
result_hits= client.list_hits()
hits_completed=int(result_hits['HITs'][i]['NumberOfAssignmentsCompleted'])
if hits_completed < number_participants and hits_completed > 0:
hit = result_hits['HITs'][i]['HITId']
#The request token should always be unique for each additional assignment
request_token= 'Request_{}_{}_{}'.format(hit,random.randint(1,100000),hits_completed)
print("Extending the HIT for the following ID: {}".format(hit))
client.create_additional_assignments_for_hit(HITId = hit, NumberOfAdditionalAssignments=1, UniqueRequestToken=request_token)
#Sleep for 10 minutes..
print("Sleeping for 10 minutes...")
time.sleep(600)
print("Completed participants:",vector_completed_experiments)
| 48.702128 | 138 | 0.769332 |
cc3b53a3879a2fe4a77aa4a8b7af91545a4857ec | 4,623 | py | Python | stable_baselines/low_dim_analysis/eval_util.py | hugerepo-tianhang/low_dim_update_stable | 565f6cbf886d266d0633bc112ccae28f1d116ee1 | [
"MIT"
] | null | null | null | stable_baselines/low_dim_analysis/eval_util.py | hugerepo-tianhang/low_dim_update_stable | 565f6cbf886d266d0633bc112ccae28f1d116ee1 | [
"MIT"
] | null | null | null | stable_baselines/low_dim_analysis/eval_util.py | hugerepo-tianhang/low_dim_update_stable | 565f6cbf886d266d0633bc112ccae28f1d116ee1 | [
"MIT"
] | null | null | null | # def get_param_traj_file_path(dir_name, net_name, index):
# return f'{dir_name}/{net_name}_{index}.txt'
import os
from datetime import datetime
if __name__ == '__main__':
print(get_log_dir("a", 1, "s", False, 0)) | 36.401575 | 134 | 0.784123 |
cc3bb136570430d6501e2f8f63227f6e1d115c10 | 6,018 | py | Python | tests/test_manager.py | rscalzo/sami | 7ac5632e018cdf2384f5ff067c503177684f61c8 | [
"BSD-3-Clause"
] | 1 | 2021-12-07T08:30:38.000Z | 2021-12-07T08:30:38.000Z | tests/test_manager.py | rscalzo/sami | 7ac5632e018cdf2384f5ff067c503177684f61c8 | [
"BSD-3-Clause"
] | null | null | null | tests/test_manager.py | rscalzo/sami | 7ac5632e018cdf2384f5ff067c503177684f61c8 | [
"BSD-3-Clause"
] | 3 | 2021-02-15T19:51:59.000Z | 2021-05-04T05:48:46.000Z | from __future__ import print_function
import pytest
from tempfile import mkdtemp
from glob import glob
import shutil
import fnmatch
import os
import os.path
import sami
TEST_DIR = os.path.join(os.path.split(__file__)[0], "test_data")
# Note: if the test data is changed, then these lists must be updated
# (too hard to automate!)
bias_files = ("22apr10035", "22apr10036", "22apr10037",
"22apr20035", "22apr20036", "22apr20037")
dark_files = ("22apr10001", "22apr10002", "22apr10003",
"22apr20001", "22apr20002", "22apr20003")
lflat_files = ("14apr10027", "22apr10088",
"14apr20027", "22apr20088")
tlm_files = ("22apr10074", "22apr20074")
flat_files = tlm_files
arc_files = ("22apr10075", "22apr20075")
obj_files = ("22apr10078", "22apr20078", "22apr10079", "22apr20079")
all_files = set(bias_files + dark_files + lflat_files + tlm_files + flat_files + arc_files + obj_files)
def find_files(path, pattern):
"""From:
http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
"""
matches = []
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, pattern):
matches.append(filename)
return matches
| 38.088608 | 106 | 0.674643 |
cc3c03312a697ba2de1761ab5b8ccb3cbedb8ca1 | 1,536 | py | Python | test/test_add_contact.py | galarina1880/python_training | f8fefdd484f4409cb6f43be1d791b50306e5bb2d | [
"Apache-2.0"
] | null | null | null | test/test_add_contact.py | galarina1880/python_training | f8fefdd484f4409cb6f43be1d791b50306e5bb2d | [
"Apache-2.0"
] | null | null | null | test/test_add_contact.py | galarina1880/python_training | f8fefdd484f4409cb6f43be1d791b50306e5bb2d | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from model.contact import Contact
# def test_add_empty_contact(app):
# old_contacts = app.contact.get_contact_list()
# contact = Contact(firstname='', middlename='', lastname='', nickname='', title='', company='', address='', home='', mobile='', work='', fax='', email='', email2='', email3='', homepage='', bday='', bmonth='-', byear='', aday='', amonth='-', ayear='', address2='', phone2='', notes='')
# app.contact.create(contact)
# new_contacts = app.contact.get_contact_list()
# assert len(old_contacts) + 1 == len(new_contacts)
# old_contacts.append(contact)
# assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)
| 64 | 438 | 0.684245 |
cc3d4f119ef3b88e30b1e9d3c45699b0745cbf05 | 1,038 | py | Python | AntShares/Network/Inventory.py | OTCGO/sync_antshares | 5724a5a820ec5f59e0c886a3c1646db2d07b4d78 | [
"MIT"
] | 10 | 2017-03-28T05:44:35.000Z | 2021-02-17T03:51:39.000Z | AntShares/Network/Inventory.py | OTCGO/sync_antshares | 5724a5a820ec5f59e0c886a3c1646db2d07b4d78 | [
"MIT"
] | 2 | 2017-07-06T10:00:25.000Z | 2017-08-09T10:14:34.000Z | AntShares/Network/Inventory.py | OTCGO/sync_antshares | 5724a5a820ec5f59e0c886a3c1646db2d07b4d78 | [
"MIT"
] | 3 | 2017-03-28T05:44:39.000Z | 2018-02-09T09:56:03.000Z | # -*- coding:utf-8 -*-
"""
Description:
Inventory Class
Usage:
from AntShares.Network.Inventory import Inventory
"""
from AntShares.IO.MemoryStream import MemoryStream
from AntShares.IO.BinaryWriter import BinaryWriter
from AntShares.Cryptography.Helper import *
from AntShares.Helper import *
import binascii
| 21.183673 | 80 | 0.654143 |
cc3e5392334cf15bfc02e165a4492d59caf3fc7b | 1,585 | py | Python | colorswatch-translator.py | MartyMacGyver/color-swatch-tool | a1351e459a4bea4da2e3dfaf881221109595fa21 | [
"Apache-2.0"
] | null | null | null | colorswatch-translator.py | MartyMacGyver/color-swatch-tool | a1351e459a4bea4da2e3dfaf881221109595fa21 | [
"Apache-2.0"
] | null | null | null | colorswatch-translator.py | MartyMacGyver/color-swatch-tool | a1351e459a4bea4da2e3dfaf881221109595fa21 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
# Copyright (c) 2015-2017 Martin F. Falatic
#
# 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
"""
from __future__ import print_function
from collections import OrderedDict
import re
def TranslateColorTable(infile):
''' Usage: TranslateColorTable("tkcolors") '''
DofL = OrderedDict()
with open(infile) as f:
for line in f:
m = re.match(r"^(.+?)\t(.+?)\t(.+?)\t(.+?)$", line)
if m:
name = m.group(1)
red = int(m.group(2))
grn = int(m.group(3))
blu = int(m.group(4))
rgb = '{0:02X}{1:02X}{2:02X}'.format(red, grn, blu)
if rgb in DofL.keys():
DofL[rgb].append(name)
else:
DofL[rgb] = [name]
print('COLORS_DICT = OrderedDict([')
for d in DofL:
print(' (\'{0}\', {1}),'.format(d, repr(DofL[d])))
print('])')
if __name__ == "__main__":
TranslateColorTable("colors_tk.orig")
| 31.7 | 77 | 0.565931 |
cc3ffb8f152bd3e99ff55c7878559254b86ef957 | 11,024 | py | Python | broker/test_setup/nas/run_jobs.py | ebloc/ebloc-broker | 776a8d9d4642ed1ba4726c94da68d61bd81c098b | [
"MIT"
] | 3 | 2021-12-11T19:26:57.000Z | 2021-12-30T00:17:23.000Z | broker/test_setup/nas/run_jobs.py | ebloc/ebloc-broker | 776a8d9d4642ed1ba4726c94da68d61bd81c098b | [
"MIT"
] | null | null | null | broker/test_setup/nas/run_jobs.py | ebloc/ebloc-broker | 776a8d9d4642ed1ba4726c94da68d61bd81c098b | [
"MIT"
] | 1 | 2021-09-18T11:38:07.000Z | 2021-09-18T11:38:07.000Z | #!/usr/bin/env python3
import os.path
import random
from pathlib import Path
from random import randint
from pymongo import MongoClient
from web3.logs import DISCARD
from broker import cfg
from broker._utils import _log
from broker._utils._log import console_ruler
from broker._utils.tools import _time, _timestamp, countdown, is_process_on, log, run
from broker._utils.web3_tools import get_tx_status
from broker._utils.yaml import Yaml
from broker.libs.mongodb import BaseMongoClass
from broker.submit_base import SubmitBase
from broker.test_setup._users import users
from broker.utils import print_tb
yaml_files = ["job_nas.yaml"]
Ebb = cfg.Ebb
cfg.IS_FULL_TEST = True
_log.ll.LOG_FILENAME = Path.home() / ".ebloc-broker" / "test.log"
provider_addresses = [
"0x3e6FfC5EdE9ee6d782303B2dc5f13AFeEE277AeA",
"0x765508fc8f78a465f518ae79897d0e4b249e82dc",
"0x38cc03c7e2a7d2acce50045141633ecdcf477e9a",
"0xeab50158e8e51de21616307a99c9604c1c453a02",
]
def create_cppr_job_script():
"""Create cppr slurm job script to be submitted."""
registered_data_hashes_small = [
"b6aaf03752dc68d625fc57b451faa2bf",
"f1de03edab51f281815c3c1e5ecb88c6",
"082d2a71d86a64250f06be14c55ca27e",
"03919732a417cb1d14049844b9de0f47",
"983b9fe8a85b543dd5a4a75d031f1091",
"f71df9d36cd519d80a3302114779741d",
"c0fee5472f3c956ba759fd54f1fe843e",
"63ffd1da6122e3fe9f63b1e7fcac1ff5",
"9e8918ff9903e3314451bf2943296d31",
"eaf488aea87a13a0bea5b83a41f3d49a",
"e62593609805db0cd3a028194afb43b1",
"3b0f75445e662dc87e28d60a5b13cd43",
"ebe53bd498a9f6446cd77d9252a9847c",
"f82aa511f8631bfc9a82fe6fa30f4b52",
"761691119cedfb9836a78a08742b14cc",
"f93b9a9f63447e0e086322b8416d4a39",
]
registered_data_hashes_medium = [
"050e6cc8dd7e889bf7874689f1e1ead6",
"9d5d892a63b5758090258300a59eb389",
"779745f315060d1bc0cd44b7266fb4da",
"fe801973c5b22ef6861f2ea79dc1eb9c",
"0d6c3288ef71d89fb93734972d4eb903",
"4613abc322e8f2fdeae9a5dd10f17540",
"dd0fbccccf7a198681ab838c67b68fbf",
"45281dfec4618e5d20570812dea38760",
"fa64e96bcee96dbc480a1495bddbf53c",
"8f6faf6cfd245cae1b5feb11ae9eb3cf",
"1bfca57fe54bc46ba948023f754521d6",
]
hash_small_data = random.choice(registered_data_hashes_small)
hash_med_data = random.choice(registered_data_hashes_medium)
fn = Path.home() / "test_eblocbroker" / "run_cppr" / "run.sh"
f = open(fn, "w+")
f.write("#!/bin/bash\n")
f.write("#SBATCH -o slurm.out # STDOUT\n")
f.write("#SBATCH -e slurm.err # STDERR\n")
f.write("#SBATCH --mail-type=ALL\n\n")
f.write("export OMP_NUM_THREADS=1\n")
f.write("current_date=$(LANG=en_us_88591; date)\n")
f.write(f"DATA_HASH='{hash_small_data}'\n")
f.write("DATA1_DIR='../data_link/'$DATA_HASH'/'\n")
f.write("echo ' * '$current_date > output.log\n")
f.write("find $DATA1_DIR -name '*.max' -print0 | while read -d $'\\0' file\n")
f.write("do\n")
f.write(" echo $file >> output.log\n")
f.write(" (/usr/bin/time -v cppr -a pr $file) >> output.log 2>&1\n")
f.write("done\n")
f.write(f"DATA_HASH='{hash_med_data}'\n")
f.write("DATA2_DIR='../data_link/'$DATA_HASH'/'\n")
f.write("echo ' * '$current_date >> output.log\n")
f.write("find $DATA2_DIR -name '*.max' -print0 | while read -d $'\\0' file\n")
f.write("do\n")
f.write(" echo $file >> output.log\n")
f.write(" (/usr/bin/time -v cppr -a pr $file) >> output.log 2>&1\n")
f.write("done\n")
#
f.write("DATA_HASH='change_folder_hash'\n")
f.write("if [[ '$DATA_HASH' != 'change_folder_hash' ]]; then\n")
f.write(" DATA3_DIR='../data_link/'$DATA_HASH'/'\n")
f.write(" echo ' * '$current_date >> output.log\n")
f.write(" find $DATA3_DIR -name '*.max' -print0 | while read -d $'\\0' file\n")
f.write(" do\n")
f.write(" echo $file >> output.log\n")
f.write(" (/usr/bin/time -v cppr -a pr $file) >> output.log 2>&1\n")
f.write(" done\n")
f.write("fi\n")
f.write("echo ' [ DONE ] ' >> output.log\n")
f.close()
run(["sed", "-i", r"s/\x0//g", fn]) # remove NULL characters from the SBATCH file
return hash_small_data, hash_med_data
def create_nas_job_script(is_small=False):
"""Create NPB3.3-SER slurm job script to be submitted."""
benchmark_names = ["bt", "cg", "ep", "is", "lu", "sp", "ua"]
benchmark_name = random.choice(benchmark_names)
output_fn = "output.log"
hash_str = random.getrandbits(128)
fn = Path.home() / "test_eblocbroker" / "NPB3.3-SER_source_code" / "run.sh"
f = open(fn, "w+")
f.write("#!/bin/bash\n")
f.write("#SBATCH -o slurm.out # STDOUT\n")
f.write("#SBATCH -e slurm.err # STDERR\n")
f.write("#SBATCH --mail-type=ALL\n\n")
f.write(f"make {benchmark_name} CLASS=A > {output_fn}\n")
f.write(f"/usr/bin/time -v bin/{benchmark_name}.A.x >> {output_fn}\n")
if not is_small:
f.write(f"make {benchmark_name} CLASS=B >> {output_fn}\n")
f.write(f"/usr/bin/time -v bin/{benchmark_name}.B.x >> {output_fn}\n")
f.write(f"make {benchmark_name} CLASS=C >> {output_fn}\n")
f.write(f"/usr/bin/time -v bin/{benchmark_name}.C.x >> {output_fn}\n")
f.write(f"# {hash_str}\n")
f.close()
run(["sed", "-i", r"s/\x0//g", fn]) # remove NULL characters from the SBATCH file
return benchmark_name
if __name__ == "__main__":
main()
| 44.273092 | 120 | 0.61484 |
cc4031a6954bcf042bbc85f87eefa7a1869a0a28 | 8,441 | py | Python | src/models/basic.py | ewanlee/mackrl | 6dd505aa09830f16c35a022f67e255db935c807e | [
"Apache-2.0"
] | 26 | 2019-10-28T09:01:45.000Z | 2021-09-20T08:56:12.000Z | src/models/basic.py | ewanlee/mackrl | 6dd505aa09830f16c35a022f67e255db935c807e | [
"Apache-2.0"
] | 1 | 2020-07-25T06:50:05.000Z | 2020-07-25T06:50:05.000Z | src/models/basic.py | ewanlee/mackrl | 6dd505aa09830f16c35a022f67e255db935c807e | [
"Apache-2.0"
] | 6 | 2019-12-18T12:02:57.000Z | 2021-03-03T13:15:47.000Z | from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch as th
from components.transforms import _to_batch, _from_batch, _check_inputs_validity, _tdim, _vdim
| 39.260465 | 120 | 0.621016 |
cc40fcfa271ed898e5b820a6656b997eb787c958 | 401 | py | Python | 02 - Estruturas de controle/ex041.py | epedropaulo/MyPython | cdb3602a01aedac26047f5b11a36a2262d4cc2ea | [
"MIT"
] | null | null | null | 02 - Estruturas de controle/ex041.py | epedropaulo/MyPython | cdb3602a01aedac26047f5b11a36a2262d4cc2ea | [
"MIT"
] | null | null | null | 02 - Estruturas de controle/ex041.py | epedropaulo/MyPython | cdb3602a01aedac26047f5b11a36a2262d4cc2ea | [
"MIT"
] | null | null | null | from datetime import date
nascimento = int(input('Digite o ano de nascimento: '))
idade = date.today().year - nascimento
print(f'Ele tem {idade} anos.')
if idade <= 9:
lugar = 'mirim'
elif idade <= 14:
lugar = 'infantil'
elif idade <= 19:
lugar = 'junior'
elif idade <= 25:
lugar = 'snior'
else:
lugar = 'master'
print(f'Logo ele pertence a classe dos {lugar}.')
| 23.588235 | 56 | 0.618454 |
cc42acd8fcb3b2b7849649f0c10ba4fa44824a33 | 82 | py | Python | utils/__init__.py | HerrYu123/deeplabv3 | 4f29d2bfb725a77b22fb04e1e0006ae742fa5d47 | [
"MIT"
] | null | null | null | utils/__init__.py | HerrYu123/deeplabv3 | 4f29d2bfb725a77b22fb04e1e0006ae742fa5d47 | [
"MIT"
] | null | null | null | utils/__init__.py | HerrYu123/deeplabv3 | 4f29d2bfb725a77b22fb04e1e0006ae742fa5d47 | [
"MIT"
] | null | null | null | from .utils import add_weight_decay, AverageMeter, label_img_to_color, check_mkdir | 82 | 82 | 0.878049 |
cc45ba5985dd0e3782dd94c105224f3ada5ebf10 | 1,159 | py | Python | scripts/collect_infer.py | TsaiTung-Chen/wtbd | 60fb153eec88e83c04ad4eac3c4a94188a28eeac | [
"MIT"
] | null | null | null | scripts/collect_infer.py | TsaiTung-Chen/wtbd | 60fb153eec88e83c04ad4eac3c4a94188a28eeac | [
"MIT"
] | null | null | null | scripts/collect_infer.py | TsaiTung-Chen/wtbd | 60fb153eec88e83c04ad4eac3c4a94188a28eeac | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 27 18:11:58 2021
@author: TSAI, TUNG-CHEN
@update: 2021/10/05
"""
MODEL_NAME = 'PhysicalCNN'
DIRECTORY = r"../dataset/preprocessed/data/"
WALK = True
SUBSET = 'all'
from wtbd.infer import infer
from wtbd.utils import print_info
from wtbd.data_collectors import SubsetDataCollector
# =============================================================================
#
# =============================================================================
# =============================================================================
#
# =============================================================================
if __name__ == '__main__':
data, results = collect_infer(MODEL_NAME,
DIRECTORY,
walk=WALK,
subset=SUBSET)
| 26.953488 | 79 | 0.449525 |
cc48fd52654d6c5c9dcc17149850ed8b8aa26647 | 2,262 | py | Python | coll_plw.py | flychensc/apple | 1b85d05e589b3c53b0ac4df29f53d4793c1a3686 | [
"Apache-2.0"
] | 2 | 2018-12-18T13:00:22.000Z | 2020-01-08T07:40:52.000Z | coll_plw.py | flychensc/apple | 1b85d05e589b3c53b0ac4df29f53d4793c1a3686 | [
"Apache-2.0"
] | null | null | null | coll_plw.py | flychensc/apple | 1b85d05e589b3c53b0ac4df29f53d4793c1a3686 | [
"Apache-2.0"
] | 1 | 2019-04-23T00:16:37.000Z | 2019-04-23T00:16:37.000Z | """
"""
from lottery import get_history
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
CODE = ''
MIN = 1
COUNT = 200
def _calc_prob(num, datas):
"""
numdatas
e.g.:
num = 1
data = [[2,3],[1,7],[3,6]]
retunr 1/3
"""
count = datas.count(num)
# count/len(datas)
return round(count/len(datas)*100)
def calc_loc(historys, loc):
"""
{
0: [0.16, 0.16, 0.15, ...],
1: [0.16, 0.16, 0.22, ...],
...
9: [0.16, 0.16, 0.02, ...],
}
"""
history_numbers = [history['result'][loc-1] for history in historys]
result = dict()
for num in range(0,10): #0-9
# result.setdefault(num, [])
prob_list = list()
size = len(history_numbers)
while size >= MIN:
prob_list.append(_calc_prob(num, history_numbers[:size]))
size -= 1
result[num] = prob_list
return result
if __name__ == '__main__':
historys = get_history(CODE, COUNT)
#gen_xls(historys)
gen_html(historys)
| 23.5625 | 78 | 0.516799 |
cc490adc1922a89384ac9296797453d77a47df06 | 1,947 | py | Python | shipper/build.py | obukhov-sergey/shipper | 574b30b2b76087d6ebb8ccf9824e175bd1c9d123 | [
"Apache-2.0"
] | 1 | 2021-11-27T14:40:26.000Z | 2021-11-27T14:40:26.000Z | shipper/build.py | obukhov-sergey/shipper | 574b30b2b76087d6ebb8ccf9824e175bd1c9d123 | [
"Apache-2.0"
] | null | null | null | shipper/build.py | obukhov-sergey/shipper | 574b30b2b76087d6ebb8ccf9824e175bd1c9d123 | [
"Apache-2.0"
] | 1 | 2021-11-27T14:40:27.000Z | 2021-11-27T14:40:27.000Z | """
Copyright [2013] [Rackspace]
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 or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os.path
import tarfile
from StringIO import StringIO
def parse_build(path=None, fobj=None):
"""Parses build parameters. Returns tuple
(archive, remote)
Where archive is a tar archive and remote is remote url if set.
One of the tuple elements will be null
"""
if path:
for prefix in ('http://', 'https://', 'github.com/', 'git://'):
if path.startswith(prefix):
return None, path
if path.startswith("~"):
path = os.path.expanduser(path)
return _archive_from_folder(path), None
else:
if not fobj:
raise ValueError("Set path or fobj")
return _archive_from_file(fobj), None
| 29.5 | 75 | 0.657422 |
cc49b50c5785fa980c7e85218289793f796ae7da | 266 | py | Python | util/logs.py | seen-idc/disco | c0a2e83ebcb26be469ee2a3243c315429add556b | [
"MIT"
] | 1 | 2021-12-11T12:01:04.000Z | 2021-12-11T12:01:04.000Z | util/logs.py | seen-idc/disco | c0a2e83ebcb26be469ee2a3243c315429add556b | [
"MIT"
] | null | null | null | util/logs.py | seen-idc/disco | c0a2e83ebcb26be469ee2a3243c315429add556b | [
"MIT"
] | null | null | null | from datetime import datetime
today = datetime.today().strftime('%Y-%m-%d %H-%M-%S') | 33.25 | 65 | 0.586466 |
cc4ce47e67db9699366e5b5fb9b6dab99a776e52 | 581 | py | Python | platformio_script.py | aircarto/Nebulo | 3134def3810e5c9579350a63299a33670583a722 | [
"MIT"
] | 1 | 2021-12-27T01:07:26.000Z | 2021-12-27T01:07:26.000Z | platformio_script.py | aircarto/Nebulo | 3134def3810e5c9579350a63299a33670583a722 | [
"MIT"
] | null | null | null | platformio_script.py | aircarto/Nebulo | 3134def3810e5c9579350a63299a33670583a722 | [
"MIT"
] | null | null | null | Import("env")
import hashlib
import os
import shutil
env.AddPostAction("$BUILD_DIR/firmware.bin", after_build)
| 26.409091 | 67 | 0.695353 |
cc4e03aa9fb9cf8d29ed71ffc7fbde9900f6b98a | 8,184 | py | Python | htmldiffer/utils.py | IYIagnus/htmldiffer | 0778e8771905db57f57f32d84471d35cf9a0f39d | [
"MIT"
] | 9 | 2017-10-06T01:39:54.000Z | 2021-08-21T12:59:27.000Z | htmldiffer/utils.py | IYIagnus/htmldiffer | 0778e8771905db57f57f32d84471d35cf9a0f39d | [
"MIT"
] | 21 | 2017-09-08T04:03:12.000Z | 2021-12-23T12:28:44.000Z | htmldiffer/utils.py | anastasia/htmldiff | 2a4e770eca6f742216afd33a1a6e82bb25f5fea0 | [
"MIT"
] | 10 | 2017-10-06T01:40:03.000Z | 2021-12-23T12:30:11.000Z | import re
import os
from bs4 import BeautifulSoup
from . import settings
def html2list(html_string, level='word'):
"""
:param html_string: any ol' html string you've got
level: either 'word' or 'character'. If level='word', elements will be words.
If level='character', elements will be individial characters.
:return: list of elements, making sure not to break up open tags (even if they contain attributes)
Note that any blacklisted tag will not be broken up
Example:
html_str = "<h1>This is a simple header</h1>"
result = html2list(html_str)
result == ['<h1>', 'This ', 'is ', 'a ', 'simple ', 'header', '</h1>']
Blacklisted tag example:
BLACKLISTED_TAGS = ['head']
html_str = "<head><title>Page Title</title></head>"
result = html2list(html_str)
result == ['<head><title>Page Title</title></head>']
"""
# different modes for parsing
CHAR, TAG = 'char', 'tag'
mode = CHAR
cur = ''
out = []
# TODO: use generators
# iterate through the string, character by character
for c in html_string:
# tags must be checked first to close tags
if mode == TAG:
# add character to current element
cur += c
# if we see the end of the tag
if c == '>':
out.append(cur) # add the current element to the output
cur = '' # reset the character
mode = CHAR # set the mode back to character mode
elif mode == CHAR:
# when we are in CHAR mode and see an opening tag, we must switch
if c == '<':
# clear out string collected so far
if cur != "":
out.append(cur) # if we have already started a new element, store it
cur = c # being our tag
mode = TAG # swap to tag mode
# if c is a special character, store 'word', store c, continue
elif is_special_character(c):
out.append(cur)
out.append(c)
cur = ''
# otherwise, simply continue building up the current element
else:
if level == 'word':
cur += c
elif level == 'character':
out.append(c)
else:
raise ValueError('level must be "word" or "character"')
# TODO: move this to its own function `merge_blacklisted` or `merge_tags` return to a generator instead of list
cleaned = list()
blacklisted_tag = None
blacklisted_string = ""
for x in out:
if not blacklisted_tag:
for tag in settings.BLACKLISTED_TAGS:
if verified_blacklisted_tag(x, tag):
blacklisted_tag = tag
blacklisted_string += x
break
if not blacklisted_tag:
cleaned.append(x)
else:
if x == "</{0}>".format(blacklisted_tag):
blacklisted_string += x
cleaned.append(blacklisted_string)
blacklisted_tag = None
blacklisted_string = ""
else:
blacklisted_string += x
return cleaned
def verified_blacklisted_tag(x, tag):
"""
check for '<' + blacklisted_tag + ' ' or '>'
as in: <head> or <head ...> (should not match <header if checking for <head)
"""
initial = x[0:len(tag) + 1 + 1]
blacklisted_head = "<{0}".format(tag)
return initial == (blacklisted_head + " ") or initial == (blacklisted_head + ">")
def compare_tags(tag_a, tag_b):
"""
returns markers for deleted, inserted, and combined
"""
tag_parts_a = chart_tag(tag_a)
tag_parts_b = chart_tag(tag_b)
# first test whether we have any new attributes
deleted_attributes = set(tag_parts_a.keys()) - set(tag_parts_b.keys())
inserted_attributes = set(tag_parts_b.keys()) - set(tag_parts_a.keys())
# then look at every attribute set and check whether the values are the same
changed_attributes = list()
for attribute in set(tag_parts_a.keys()) & set(tag_parts_b.keys()):
if tag_parts_a[attribute] != tag_parts_b[attribute]:
changed_attributes.append(attribute)
return {
'deleted_attributes': list(deleted_attributes),
'inserted_attributes': list(inserted_attributes),
'changed_attributes': changed_attributes,
}
def chart_tag(tag_string):
"""
Takes tag and returns dict that charts out tag parts
example:
tag = '<div title="somewhere">'
parts = chart_tag(tag)
print(parts)
# {'tag': 'div', 'title': 'somewhere'}
"""
tag_parts = dict()
if tag_string[0] != "<" and tag_string[-1] != ">":
raise Exception("Got malformed tag", tag_string)
t = tag_string.split(" ")
for el in t:
if el[0] == "<":
# grab the tag type
tag_parts['tag'] = el[1:]
else:
check_element = el[:-1] if el[-1] == ">" else el
check_element = check_element.replace('"', '').replace('/', '')
if len(check_element.split("=")) > 1:
attribute, values = check_element.split("=")
tag_parts[attribute] = values
else:
# if unattached elements, these are probably extra values from
# the previous attribute, so we add them
tag_parts[attribute] += ' ' + check_element
if el[-1] == ">":
return tag_parts
def get_class_decorator(name, diff_type=''):
"""returns class like `htmldiffer-tag-change`"""
if diff_type:
return "%s_%s" % (settings.HTMLDIFFER_CLASS_STRINGS[name], diff_type)
else:
return "%s" % (settings.HTMLDIFFER_CLASS_STRINGS[name])
# ===============================
# Predicate functions
# ===============================
# Note: These make assumptions about consuming valid html text. Validations should happen before these internal
# predicate functions are used -- these are not currently used for parsing.
| 30.651685 | 115 | 0.568793 |
cc4f335d8706e5da167e24cbfe0bd8271e69c190 | 3,846 | py | Python | pgAdmin/pgadmin4/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/tests/utils.py | WeilerWebServices/PostgreSQL | ae594ed077bebbad1be3c1d95c38b7c2c2683e8c | [
"PostgreSQL"
] | null | null | null | pgAdmin/pgadmin4/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/tests/utils.py | WeilerWebServices/PostgreSQL | ae594ed077bebbad1be3c1d95c38b7c2c2683e8c | [
"PostgreSQL"
] | null | null | null | pgAdmin/pgadmin4/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/tests/utils.py | WeilerWebServices/PostgreSQL | ae594ed077bebbad1be3c1d95c38b7c2c2683e8c | [
"PostgreSQL"
] | null | null | null | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2020, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import os
import sys
import traceback
import json
from regression.python_test_utils.test_utils import get_db_connection
CURRENT_PATH = os.path.dirname(os.path.realpath(__file__))
with open(CURRENT_PATH + "/user_mapping_test_data.json") as data_file:
test_cases = json.load(data_file)
def create_user_mapping(server, db_name, fsrv_name):
"""
This function will create user mapping under the existing
dummy database.
:param server: server details
:type server: dict
:param db_name: database name
:type db_name: str
:param fsrv_name: FS name
:type fsrv_name: str
:return um_id: user mapping id
:rtype: int
"""
try:
connection = get_db_connection(db_name,
server['username'],
server['db_password'],
server['host'],
server['port'],
server['sslmode'])
old_isolation_level = connection.isolation_level
connection.set_isolation_level(0)
pg_cursor = connection.cursor()
query = "CREATE USER MAPPING FOR %s SERVER %s OPTIONS" \
" (user '%s', password '%s')" % (server['username'],
fsrv_name,
server['username'],
server['db_password']
)
pg_cursor.execute(query)
connection.set_isolation_level(old_isolation_level)
connection.commit()
# Get 'oid' from newly created user mapping
pg_cursor.execute(
"select umid from pg_user_mappings where srvname = '%s' order by"
" umid asc limit 1" % fsrv_name)
oid = pg_cursor.fetchone()
um_id = ''
if oid:
um_id = oid[0]
connection.close()
return um_id
except Exception:
traceback.print_exc(file=sys.stderr)
def verify_user_mapping(server, db_name, fsrv_name):
"""
This function will verify current foreign server.
:param server: server details
:type server: dict
:param db_name: database name
:type db_name: str
:param fsrv_name: FS name
:type fsrv_name: str
:return user_mapping: user mapping record
:rtype: tuple
"""
try:
connection = get_db_connection(db_name,
server['username'],
server['db_password'],
server['host'],
server['port'],
server['sslmode'])
pg_cursor = connection.cursor()
pg_cursor.execute(
"select umid from pg_user_mappings where srvname = '%s' order by"
" umid asc limit 1" % fsrv_name)
user_mapping = pg_cursor.fetchone()
connection.close()
return user_mapping
except Exception:
traceback.print_exc(file=sys.stderr)
| 33.736842 | 77 | 0.50286 |
cc4fff28ee4d94fb2b52c842939ccc5bea70cd6b | 1,467 | py | Python | src/litedesk/lib/airwatch/base.py | litedesk/litedesk-lib-airwatch | 19c47a50d606f966497a6e24fd892bca1bf11354 | [
"Apache-2.0"
] | 1 | 2016-12-22T07:10:45.000Z | 2016-12-22T07:10:45.000Z | src/litedesk/lib/airwatch/base.py | litedesk/litedesk-lib-airwatch | 19c47a50d606f966497a6e24fd892bca1bf11354 | [
"Apache-2.0"
] | null | null | null | src/litedesk/lib/airwatch/base.py | litedesk/litedesk-lib-airwatch | 19c47a50d606f966497a6e24fd892bca1bf11354 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests
| 34.928571 | 92 | 0.656442 |
cc50d33be84a339a3707572fbfdb3ba740f84346 | 840 | py | Python | employee_management/employee_management/doctype/valiant/Permission_Override/permission_override.py | Vivekananthan112599/Frappe-Vivek | 6a2b70c736e17e9748c6a30e5722341acfb3b5c5 | [
"MIT"
] | null | null | null | employee_management/employee_management/doctype/valiant/Permission_Override/permission_override.py | Vivekananthan112599/Frappe-Vivek | 6a2b70c736e17e9748c6a30e5722341acfb3b5c5 | [
"MIT"
] | null | null | null | employee_management/employee_management/doctype/valiant/Permission_Override/permission_override.py | Vivekananthan112599/Frappe-Vivek | 6a2b70c736e17e9748c6a30e5722341acfb3b5c5 | [
"MIT"
] | null | null | null | import frappe
# print("///////////******///////******////******///**")
# print(user)
# print(frappe.session.user)
# return """(`tabValiant`.`native`='Salem' )"""
# return "(`tabValiant`.owner = 'i am')".format(user=frappe.db.escape(user))
| 24 | 76 | 0.513095 |
cc52398a725b3573f2ce15c63cfb703dc5d3fa5f | 2,760 | py | Python | test/Django/05/02/BookManager/Book/views.py | Kingworrior007/lchw001 | e59e6f300123bd98d49e81be16e73a4440ffa85a | [
"MIT"
] | 2 | 2018-03-09T02:13:54.000Z | 2020-12-28T01:47:30.000Z | test/Django/05/02/BookManager/Book/views.py | X-Warrior007/lchw001 | e59e6f300123bd98d49e81be16e73a4440ffa85a | [
"MIT"
] | null | null | null | test/Django/05/02/BookManager/Book/views.py | X-Warrior007/lchw001 | e59e6f300123bd98d49e81be16e73a4440ffa85a | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.conf import settings
from Book.models import PictureInfo,AreaInfo
from django.core.paginator import Paginator
# Create your views here.
def sheng(request):
""",JSON,ajax"""
# sheng_list = [AreaInfo,AreaInfo,AreaInfo,AreaInfo,...]
sheng_list = AreaInfo.objects.filter(parent__isnull=True)
# JSON
list = []
for sheng in sheng_list:
list.append([sheng.id, sheng.name])
# JSON
sheng_json_dict = {'shenglist':list}
# JSON : ajaxjson
return JsonResponse(sheng_json_dict)
"""
{
"shenglist":[
[id, name],
[id, name],
]
}
"""
"""
{
"shenglist":[
{"id":id, "name":name},
{"id":id, "name":name},
]
}
"""
"""
<select id="sheng">
<option value="100000"></option>
</select>
<select id="shi">
<option value="100005"></option>
</select>
<select id="qu">
<option value="0"></option>
</select>
"""
def area(request):
""""""
return render(request, 'Book/area.html')
def page(request, page_num):
""""""
# sheng_list = [AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,... 33]
sheng_list = AreaInfo.objects.filter(parent__isnull=True)
# : sheng_list,10
# pagenator = [AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,... 33]
paginator = Paginator(sheng_list, 10)
# ,/page/
# print(type(page_num))
if page_num == '':
page_num = '1'
# page = [AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo,AreaInfo]
page = paginator.page(page_num) # 1 '1'
#
context = {
'page':page
}
#
return render(request, 'Book/page.html', context)
def recv(request):
""",,"""
#
pic = request.FILES.get('pic') # InMemoryUploadF...
#
pic_name = pic.name
# : '/static/media/Book/mm03.jpeg'
path = '%s/Book/%s' % (settings.MEDIA_ROOT, pic_name)
# ,
with open(path, 'ab') as file:
for c in pic.chunks(): # chunks() ,
file.write(c)
# ,
pictureInfo = PictureInfo()
# path
pictureInfo.path = 'Book/%s' % pic_name
# path,
pictureInfo.save()
#
return HttpResponse('')
def upload(request):
""""""
return render(request, 'Book/upload.html')
def staticFile(request):
""""""
return render(request, 'Book/staticfile.html')
| 21.5625 | 113 | 0.63913 |
cc539e34ac77acde6025be508c15b403c3e70d57 | 4,925 | py | Python | stanCode_projects/boggle_game/add2.py | lindcrj/stanCode_projects | 2ce2f7b51fb1e6940ab2b62b05edccfef66739b4 | [
"MIT"
] | null | null | null | stanCode_projects/boggle_game/add2.py | lindcrj/stanCode_projects | 2ce2f7b51fb1e6940ab2b62b05edccfef66739b4 | [
"MIT"
] | null | null | null | stanCode_projects/boggle_game/add2.py | lindcrj/stanCode_projects | 2ce2f7b51fb1e6940ab2b62b05edccfef66739b4 | [
"MIT"
] | null | null | null | """
File: add2.py
Name:
------------------------
TODO:
"""
import sys
####### DO NOT EDIT CODE BELOW THIS LINE ########
def traversal(head):
"""
:param head: ListNode, the first node to a linked list
-------------------------------------------
This function prints out the linked list starting with head
"""
cur = head
while cur.next is not None:
print(cur.val, end='->')
cur = cur.next
print(cur.val)
if __name__ == '__main__':
main()
| 27.361111 | 64 | 0.431878 |
cc53da809995bfcf906eeef477759efe194c27ed | 1,157 | py | Python | node/trust.py | cflynn07/OpenBazaar | 439511e9c81a658cdad2014b02d3fdf13abab5c4 | [
"MIT"
] | null | null | null | node/trust.py | cflynn07/OpenBazaar | 439511e9c81a658cdad2014b02d3fdf13abab5c4 | [
"MIT"
] | null | null | null | node/trust.py | cflynn07/OpenBazaar | 439511e9c81a658cdad2014b02d3fdf13abab5c4 | [
"MIT"
] | null | null | null | import obelisk
import logging
import bitcoin
from twisted.internet import reactor
_log = logging.getLogger('trust')
TESTNET = False
| 21.425926 | 59 | 0.673293 |
cc540b688ab45280f7ea07bb3f403f279507c6f1 | 1,261 | py | Python | backend/collages/__init__.py | dyachoksa/collage-generator | a5682869488f8e5ebbca56a58a7f425dada215ed | [
"MIT"
] | null | null | null | backend/collages/__init__.py | dyachoksa/collage-generator | a5682869488f8e5ebbca56a58a7f425dada215ed | [
"MIT"
] | null | null | null | backend/collages/__init__.py | dyachoksa/collage-generator | a5682869488f8e5ebbca56a58a7f425dada215ed | [
"MIT"
] | null | null | null | # Collage Generator Backend Application
import logging.config
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette_context import plugins
from starlette_context.middleware import ContextMiddleware
from . import settings
from .extensions import db
from .http import routes
from .http.error_handlers import exception_handlers
from .http.security import AppAuthenticationBackend
logging.config.fileConfig("logging.conf", disable_existing_loggers=False)
middleware = [
Middleware(
ContextMiddleware.with_plugins(
plugins.RequestIdPlugin, # request id
plugins.CorrelationIdPlugin, # correlation id
)
),
Middleware(AuthenticationMiddleware, backend=AppAuthenticationBackend()),
Middleware(GZipMiddleware, minimum_size=1024),
]
app = Starlette(
debug=settings.DEBUG,
exception_handlers=exception_handlers,
middleware=middleware,
routes=routes,
)
# App-level events
| 26.829787 | 77 | 0.780333 |
cc575e937de9aeef001a485a8da20d00adb1974e | 2,298 | py | Python | codechef/long-challenge/may21/LKDNGOLF.py | ramanaditya/data-structure-and-algorithms | 8dcfeb011e76b2b38b54842e8ccc7a59728141f8 | [
"MIT"
] | 81 | 2020-05-22T14:22:04.000Z | 2021-12-18T10:11:23.000Z | codechef/long-challenge/may21/LKDNGOLF.py | techhub-community/data-structure-and-algorithms | 8dcfeb011e76b2b38b54842e8ccc7a59728141f8 | [
"MIT"
] | 4 | 2020-08-06T21:08:00.000Z | 2021-03-31T16:07:50.000Z | codechef/long-challenge/may21/LKDNGOLF.py | techhub-community/data-structure-and-algorithms | 8dcfeb011e76b2b38b54842e8ccc7a59728141f8 | [
"MIT"
] | 37 | 2020-05-22T14:25:21.000Z | 2021-12-30T03:13:13.000Z | """
[Golf](https://www.codechef.com/MAY21C/problems/LKDNGOLF)
It's a lockdown. Youre bored in your house and are playing golf in the hallway.
The hallway has N+2 tiles numbered from 0 to N+1 from left to right. There is a hole on tile number x. You hit the ball
standing on tile 0. When you hit the ball, it bounces at lengths of k, i.e. the tiles covered by it are 0,k,2k,, and
so on until the ball passes tile N+1.
If the ball doesn't enter the hole in the first trial, you try again but this time standing on the tile N+1. When you
hit the ball, it bounces at lengths of k, i.e. the tiles covered by it are (N+1),(N+1k),(N+12k),, and so on until
the ball passes tile 0.
Find if the ball will enter the hole, either in its forward journey or backward journey.
Note: The input and output of this problem are large, so prefer using fast input/output methods.
Input
The first line contains an integer T, the number of test cases. Then the test cases follow.
The only line of each test case contains three integers N,x,k.
Output
Output in a single line, the answer, which should be "YES" if the ball enters the hole either in the forward or
backward journey and "NO" if not.
You may print each character of the string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and
"YES" will all be treated as identical).
Constraints
1T105
1x,kN109
Subtasks
Subtask #1 (10 points): N102
Subtask #2 (90 points): original constraints
Sample Input
3
5 4 2
5 3 2
5 5 2
Sample Output
YES
NO
NO
Explanation
In each test case, the tiles covered by the ball for N=5 and k=2 are {0,2,4,6} in the forward journey and {6,4,2,0} in
the backward journey.
Therefore, the answer for the first test case is "YES" since the ball falls in the position of the hole at tile 4. But
the answer for test cases 2 and 3 is "NO" since the ball does not fall in the position of the hole.
"""
import sys
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
T = data[0]
idx = 1
while T > 0:
N, x, k = data[idx:idx+3]
N += 1
if x % k == 0:
print("YES")
elif (N - x) % k == 0:
print("YES")
else:
print("NO")
T -= 1
idx += 3
# Time : 0.14s
| 29.088608 | 119 | 0.679721 |
cc58d71d7ae86ba704bcdd360c5f0a8dc49d8018 | 1,446 | py | Python | yogit/yogit/logger.py | jmaneyrol69/yogit | 347a6ee990e066eab36432dbae93ee05c681f329 | [
"MIT"
] | 17 | 2019-07-15T08:01:08.000Z | 2022-02-16T20:07:20.000Z | yogit/yogit/logger.py | jmaneyrol69/yogit | 347a6ee990e066eab36432dbae93ee05c681f329 | [
"MIT"
] | 5 | 2019-07-16T12:49:08.000Z | 2020-10-20T15:27:41.000Z | yogit/yogit/logger.py | jmaneyrol69/yogit | 347a6ee990e066eab36432dbae93ee05c681f329 | [
"MIT"
] | 4 | 2019-07-16T12:38:46.000Z | 2020-10-19T12:51:37.000Z | """
Application logger
"""
import logging
import os
import sys
from yogit import get_name, get_version
from yogit.yogit.paths import get_log_path, SETTINGS_DIR
def get_logger(stdout=False, logger_name=get_name(), version=get_version()):
"""
Create and configure a logger using a given name.
"""
os.makedirs(SETTINGS_DIR, exist_ok=True)
application_str = logger_name
if version:
application_str += " " + version
formatter = logging.Formatter(
fmt=(
"%(asctime)s "
"[{application}:%(process)d] "
"[%(levelname)s] "
"%(message)s".format(application=application_str)
),
datefmt="%Y-%m-%dT%H:%M:%S%z",
)
file_log_handler = logging.FileHandler(get_log_path())
file_log_handler.setLevel(logging.DEBUG)
file_log_handler.setFormatter(formatter)
local_logger = logging.getLogger(logger_name)
local_logger.setLevel(logging.DEBUG)
local_logger.addHandler(file_log_handler)
if stdout:
console_log_handler = logging.StreamHandler(sys.stdout)
console_log_handler.setLevel(logging.DEBUG)
console_log_handler.setFormatter(formatter)
local_logger.addHandler(console_log_handler)
return local_logger
LOGGER = get_logger()
def enable_stdout():
"""
Prints logs in stdout
"""
global LOGGER # pylint: disable=global-statement
LOGGER = get_logger(stdout=True)
| 24.931034 | 76 | 0.677732 |
cc58da3fac72aacf2a23055a4b3451dabb43f644 | 481 | py | Python | src/mbed_cloud/_backends/statistics/models/__init__.py | GQMai/mbed-cloud-sdk-python | 76ef009903415f37f69dcc5778be8f5fb14c08fe | [
"Apache-2.0"
] | 12 | 2017-12-28T11:18:43.000Z | 2020-10-04T12:11:15.000Z | src/mbed_cloud/_backends/statistics/models/__init__.py | GQMai/mbed-cloud-sdk-python | 76ef009903415f37f69dcc5778be8f5fb14c08fe | [
"Apache-2.0"
] | 50 | 2017-12-21T12:50:41.000Z | 2020-01-13T16:07:08.000Z | src/mbed_cloud/_backends/statistics/models/__init__.py | GQMai/mbed-cloud-sdk-python | 76ef009903415f37f69dcc5778be8f5fb14c08fe | [
"Apache-2.0"
] | 8 | 2018-04-25T17:47:29.000Z | 2019-08-29T06:38:27.000Z | # coding: utf-8
"""
Connect Statistics API
Connect Statistics API provides statistics about other cloud services through defined counters.
OpenAPI spec version: 3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from .error_response import ErrorResponse
from .fields import Fields
from .metric import Metric
from .successful_response import SuccessfulResponse
| 22.904762 | 99 | 0.779626 |
cc5982992e201503c11c0734dd8dc758ba63e2ee | 488 | py | Python | sane_logger/sane_logger.py | JesseAldridge/sane_logger | d8850a67f7ffe6cd3d8b25ef5a9d482a254870bc | [
"MIT"
] | 1 | 2021-06-06T15:37:13.000Z | 2021-06-06T15:37:13.000Z | sane_logger/sane_logger.py | JesseAldridge/sane_logger | d8850a67f7ffe6cd3d8b25ef5a9d482a254870bc | [
"MIT"
] | null | null | null | sane_logger/sane_logger.py | JesseAldridge/sane_logger | d8850a67f7ffe6cd3d8b25ef5a9d482a254870bc | [
"MIT"
] | null | null | null | import logging, sys
if __name__ == '__main__':
logger = sane_logger(logging.DEBUG)
logger.info('test log')
| 24.4 | 85 | 0.684426 |
cc5a9edbb995731c204cc21e2a54a1a17f5290cd | 7,104 | py | Python | core_tools/drivers/hardware/virtual_gate_matrix.py | opietx/core_tools | d5bd2d4beed74791b80ff5bdabd67774403763ef | [
"BSD-2-Clause"
] | null | null | null | core_tools/drivers/hardware/virtual_gate_matrix.py | opietx/core_tools | d5bd2d4beed74791b80ff5bdabd67774403763ef | [
"BSD-2-Clause"
] | null | null | null | core_tools/drivers/hardware/virtual_gate_matrix.py | opietx/core_tools | d5bd2d4beed74791b80ff5bdabd67774403763ef | [
"BSD-2-Clause"
] | null | null | null | from core_tools.data.SQL.SQL_connection_mgr import SQL_database_manager
from core_tools.drivers.hardware.hardware_SQL_backend import virtual_gate_queries
import time
import numpy as np
def lamda_invert(matrix):
return np.linalg.inv(matrix)
def lamda_norm(matrix_norm):
matrix_no_norm = np.empty(matrix_norm.shape)
for i in range(matrix_norm.shape[0]):
matrix_no_norm[i, :] = matrix_norm[i, :]/matrix_norm[i, i]
return matrix_no_norm
def lamda_unnorm(matrix_no_norm):
matrix_norm = np.empty(matrix_no_norm.shape)
for i in range(matrix_norm.shape[0]):
matrix_norm[i, :] = matrix_no_norm[i]/np.sum(matrix_no_norm[i, :])
return matrix_norm
def combine_lamdas(l1, l2):
return new_lamda
def load_virtual_gate(name, real_gates, virtual_gates=None):
conn = SQL_database_manager().conn_local
virtual_gate_queries.generate_table(conn)
virtual_gates = name_virtual_gates(virtual_gates, real_gates)
if virtual_gate_queries.check_var_in_table_exist(conn, name):
real_gate_db, virtual_gate_db, matrix_db = virtual_gate_queries.get_virtual_gate_matrix(conn, name)
entries_to_add = set(real_gates) - set(real_gate_db)
gates = real_gate_db + list(entries_to_add)
dummy_matrix = np.eye(len(gates))
dummy_matrix[:len(real_gate_db) , :len(real_gate_db)] = matrix_db
dummy_v_gates = virtual_gate_matrix('dummy', gates, name_virtual_gates(None, gates), dummy_matrix)
v_gate_matrix = np.eye(len(real_gates))
for i in range(len(real_gates)):
for j in range(len(real_gates)):
v_gate_matrix[i, j] = dummy_v_gates['v' + real_gates[i],real_gates[j]]
return virtual_gate_matrix(name, real_gates, virtual_gates, v_gate_matrix)
else:
return virtual_gate_matrix(name, real_gates, virtual_gates, np.eye(len(real_gates)))
def save(vg_matrix):
conn = SQL_database_manager().conn_local
if virtual_gate_queries.check_var_in_table_exist(conn, vg_matrix.name):
# merge in case there are more entries
real_gate_db, virtual_gate_db, matrix_db = virtual_gate_queries.get_virtual_gate_matrix(conn, vg_matrix.name)
all_gates = list(set(real_gate_db + vg_matrix.gates))
dummy_v_gates = virtual_gate_matrix('dummy', all_gates, name_virtual_gates(None, all_gates), np.eye(len(all_gates)))
for i in range(len(real_gate_db)):
for j in range(len(real_gate_db)):
dummy_v_gates['v' + real_gate_db[i], real_gate_db[j]] = matrix_db[i,j]
for i in range(len(vg_matrix.gates)):
for j in range(len(vg_matrix.gates)):
dummy_v_gates['v' + vg_matrix.gates[i], vg_matrix.gates[j]] = vg_matrix._matrix[i,j]
virtual_gate_queries.set_virtual_gate_matrix(conn, vg_matrix.name,
dummy_v_gates.gates, dummy_v_gates.v_gates, dummy_v_gates._matrix)
else:
virtual_gate_queries.set_virtual_gate_matrix(conn, vg_matrix.name,
vg_matrix.gates, vg_matrix.v_gates, vg_matrix._matrix)
def name_virtual_gates(v_gate_names, real_gates):
if v_gate_names is None:
v_gates = []
for i in real_gates:
v_gates += ['v' + i]
else:
v_gates = v_gate_names
return v_gates
| 36.244898 | 125 | 0.649352 |
cc5d1f2725d275ded5ef2a2efe3f720356553637 | 4,658 | py | Python | koto - backend/backend/views.py | SirJAKfromSpace/Koto-FinanceManager | bfec6f36d97b5986294e348bdf2c0b229449bb19 | [
"MIT"
] | null | null | null | koto - backend/backend/views.py | SirJAKfromSpace/Koto-FinanceManager | bfec6f36d97b5986294e348bdf2c0b229449bb19 | [
"MIT"
] | null | null | null | koto - backend/backend/views.py | SirJAKfromSpace/Koto-FinanceManager | bfec6f36d97b5986294e348bdf2c0b229449bb19 | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from rest_framework import generics
from .models import kotoUser
from .models import transaction
from .models import income
from .serializers import kotoUserserializer, transactionserializer
from django.shortcuts import render, redirect # redirects users to page we (Koto team) wants
from django.contrib.auth import authenticate, login # authenticates whether the user exists in the database (via email and username), login makes sure that our users dont have to input password on every page they browse
from django.views.generic import View
from .forms import UserForm
from django.contrib.auth import logout
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']
# Create your views here.
#rest api requests
| 36.390625 | 219 | 0.678188 |
cc61601dbf922a6709fa7e843196b29dbf744599 | 54,648 | py | Python | outlier-analyzer-wrapper/cal_outlier.py | vasu018/outlier-analyzers | a46102e90f7c87560efa2f33dff3b337561486b5 | [
"Apache-2.0"
] | null | null | null | outlier-analyzer-wrapper/cal_outlier.py | vasu018/outlier-analyzers | a46102e90f7c87560efa2f33dff3b337561486b5 | [
"Apache-2.0"
] | null | null | null | outlier-analyzer-wrapper/cal_outlier.py | vasu018/outlier-analyzers | a46102e90f7c87560efa2f33dff3b337561486b5 | [
"Apache-2.0"
] | null | null | null | import sys
import re
import json
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import MultiLabelBinarizer
from scipy.spatial.distance import cdist
from colorama import Fore, Style
from kneed import KneeLocator
import copy
import time
import pickle
import os
def error_msg(error_msg, arg):
"""
Helper function to display error message on the screen.
Input:
The error message along with its respective argument.
(Values include - filename, selected action).
Output:
The formatted error message on the screen along with the argument.
"""
print("****************************")
print(Fore.RED, end='')
print(error_msg,":", arg)
print(Style.RESET_ALL, end='')
print("****************************")
sys.exit(0)
def printINFO(info):
"""
Helper function to ask the user for Input.
Input:
The message that is to be displayed.
Output:
The formatted message on the screen.
"""
print(Fore.BLUE, end='')
print(info)
print(Style.RESET_ALL, end='')
# *****************************************************************************
# *****************************************************************************
# Helper Methods Start
def calculate_num_clusters(df, acl_weights):
"""
Calculates the optimal number of clusters using the elbow_graph approach.
Input:
The Pandas dataframe of the input file (ACL.json)
output:
The value of k that provides the least MSE.
"""
files = ['IP_Access_List', 'Route_Filter_List', 'VRF', 'AS_Path_Access_List',
'IKE_Phase1_Keys', 'IPsec_Phase2_Proposals', 'Routing_Policy']
k_select_vals = [41, 17, 42, 5, 3, 2, 58]
curr_file = file_name.split(".")[0]
file_index = files.index(curr_file)
return k_select_vals[file_index]
features = df[df.columns]
ran = min(len(df.columns), len(discrete_namedstructure))
if ran > 50:
k_range = range(1, 587)
else:
k_range = range(1, ran)
print(k_range)
k_range = range(1, 580)
distortions = []
np.seed = 0
clusters_list = []
f = open('distortions.txt', 'w')
for k in k_range:
print(k)
kmeans = KMeans(n_clusters=k).fit(features, None, sample_weight=acl_weights)
clusters_list.append(kmeans)
cluster_centers = kmeans.cluster_centers_
k_distance = cdist(features, cluster_centers, "euclidean")
distance = np.min(k_distance, axis=1)
distortion = np.sum(distance)/features.shape[0]
distortions.append(distortion)
f.write(str(distortion))
f.write("\n")
kn = KneeLocator(list(k_range), distortions, S=3.0, curve='convex', direction='decreasing')
print("Knee is: ", kn.knee)
plt.xlabel('k')
plt.ylabel('Distortion')
plt.title('The Elbow Method showing the optimal k')
plt.plot(k_range, distortions, 'bx-')
plt.vlines(kn.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
plt.show()
if kn.knee is None:
if ran < 5:
return ran - 1
else:
return 5
return kn.knee
'''
for i in range(1, len(avg_within)):
if (avg_within[i-1] - avg_within[i]) < 1:
break
# return i-1 if len(avg_within) > 1 else 1
# return i - 1 if i > 1 else 1
'''
def perform_kmeans_clustering(df, ns_weights):
"""
To get a mapping of the rows into respective clusters generated using the K-means algorithm.
Input:
df:The Pandas data-frame of the input file (ACL.json)
ns_weights: The weights of each name structure which allows the weighted k-means algorithm to work.
Output:
Adding respective K-means cluster label to the input dataframe.
Example:
Row1 - Label 0 //Belongs to Cluster 0
Row2 - Label 0 //Belongs to Cluster 0
Row3 - Label 1 //Belongs to Cluster 1
"""
global k_select
k_select = calculate_num_clusters(df, ns_weights)
features = df[df.columns]
kmeans = KMeans(n_clusters=k_select)
kmeans.fit(features, None, sample_weight=ns_weights)
labels = kmeans.labels_
df["kmeans_cluster_number"] = pd.Series(labels)
def extract_keys(the_dict, prefix=''):
"""
Recursive approach to gather all the keys that have nested keys in the input file.
Input:
The dictionary file to find all the keys in.
Output:
All the keys found in the nested dictionary.
Example:
Consider {key1:value1, key2:{key3:value3}, key4:[value4], key5:[key6:{key7:value7}]}
The function returns key2, key5=key6
"""
key_list = []
for key, value in the_dict.items():
if len(prefix) == 0:
new_prefix = key
else:
new_prefix = prefix + '=' + key
try:
if type(value) == dict:
key_list.extend(extract_keys(value, new_prefix))
elif type(value) == list and type(value[0]) == dict:
key_list.extend(extract_keys(value[0], new_prefix))
elif type(value) == list and type(value[0]) != dict:
key_list.append(new_prefix)
else:
key_list.append(new_prefix)
except:
key_list.append(new_prefix)
return key_list
def get_uniques(data):
"""
A helper function to get unique elements in a List.
Input:
A list that we need to capture uniques from.
Output:
A dictionary with unique entries and count of occurrences.
"""
acl_count_dict = {}
for acl in data:
acl = json.dumps(acl)
if acl not in acl_count_dict:
acl_count_dict[acl] = 1
else:
value = acl_count_dict[acl]
value += 1
acl_count_dict[acl] = value
keys = []
values = []
for key, value in acl_count_dict.items():
keys.append(key)
values.append(value)
return keys, values
def overall_dict(data_final):
"""
Parses through the dictionary and appends the frequency with which the keys occur.
Input:
A nested dictionary.
Example:
{key1:{key2:value1, key3:value2, key4:{key5:value3}}
{key6:{key7:value2}
{key8:{key3:value3, key4:value5, key6:value3}}
Output:
Returns a new array with the nested keys appended along with a tuple containing the un-nested value along with
the frequency count.
[{
key1=key2:{'value1':1},
key1=key3:{'value2':2},
key1=key4=key5:{'value3':3},
key6=key7:{'value2':2},
key8=key3:{'value3':3},
key8=key4:{'value5':1},
key8=key6:{'value3':1}
}]
"""
overall_array = []
for data in data_final:
overall = {}
for item in data:
if item[0] is None:
continue
result = extract_keys(item[0])
for element in result:
value = item[0]
for key in element.split("="):
new_value = value[key]
if type(new_value) == list:
if len(new_value) != 0:
new_value = new_value[0]
else:
new_value = "#BUG#"
value = new_value
if element not in overall:
overall[element] = {}
if value not in overall[element]:
overall[element][value] = 1
else:
overall[element][value] += 1
overall_array.append(overall)
return overall_array
def get_overall_dict(data_final):
"""
Parses through the dictionary and appends the frequency with which the keys occur.
Input:
A nested dictionary.
Example:
{key1:{key2:value1, key3:value2, key4:{key5:value3}}
{key6:{key7:value2}
{key8:{key3:value3, key4:value5, key6:value3}}
Output:
Returns a new array with the nested keys appended along with a tuple containing the unnested value along with the frequency count.
[{
key1=key2:{'value1':1},
key1=key3:{'value2':2},
key1=key4=key5:{'value3':3},
key6=key7:{'value2':2},
key8=key3:{'value3':3},
key8=key4:{'value5':1},
key8=key6:{'value3':1}
}]
"""
overall_array = []
for data in data_final:
overall = {}
new_value = None
flag = 0
for item in data:
visited = {"lines=name":1}
if item[0] is None:
continue
result = extract_keys(item[0])
for element in result:
value = item[0]
for key in element.split("="):
if element not in visited:
visited[element] = 1
new_value = value[key]
flag = 0
if type(new_value) == list:
if len(new_value) > 0:
for list_data in new_value:
if element not in overall:
overall[element] = {}
temp = element
temp_val = list_data
temp = temp.split("=", 1)[-1]
while len(temp.split("=")) > 1:
temp_val = temp_val[temp.split("=")[0]]
temp = temp.split("=", 1)[-1]
list_key = temp
check = 0
try:
if type(temp_val[list_key]) == list:
if temp_val[list_key][0] not in overall[element]:
overall[element][temp_val[list_key][0]] = 1
check = 1
else:
if temp_val[list_key] not in overall[element]:
overall[element][temp_val[list_key]] = 1
check = 1
except:
dummy=0
'''
do nothing
'''
try:
if check == 0:
if type(temp_val[list_key]) == list:
if temp_val[list_key][0] in overall[element]:
overall[element][temp_val[list_key][0]] += 1
else:
if temp_val[list_key] in overall[element]:
overall[element][temp_val[list_key]] += 1
except:
dummy=0
flag = 1
value = new_value
else:
'''
Type is not list
'''
value = new_value
else:
if flag == 0:
if element not in overall:
overall[element] = {}
if new_value not in overall[element]:
overall[element][new_value] = 1
else:
overall[element][new_value] += 1
if flag == 0:
if element not in overall:
overall[element] = {}
if new_value not in overall[element]:
overall[element][new_value] = 1
else:
overall[element][new_value] += 1
overall_array.append(overall)
return overall_array
def calculate_z_score(arr):
"""
Calculates the Z-score (uses mean) (or) Modified Z-score (uses median) of data-points
Input:
Data points generated from parsing through the input file.
Also considers the Z_SCORE_FLAG that is set previously with 0 (default) using the Modified Z-score and 1 using Z-score.
Output:
The Z-score of given data-points array.
"""
if len(arr) == 1:
return arr
z_score = []
'''
Calculates the Z-score using mean. Generally used if distribution is normal (Bell curve).
'''
if Z_SCORE_FLAG:
mean = np.mean(arr)
std = np.std(arr)
if std == 0:
return np.ones(len(arr)) * 1000
for val in arr:
z_score.append((val - mean) / std)
'''
Modified Z-score approach.
Calculates the Z-score using median. Generally used if distribution is skewed.
'''
else:
median_y = np.median(arr)
medians = [np.abs(y - median_y) for y in arr]
med = np.median(medians)
median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in arr])
if median_absolute_deviation_y == 0:
return np.ones(len(arr)) * 1000
z_score = [0.6745 * (y - median_y) / median_absolute_deviation_y for y in arr]
return z_score
def calculate_signature_d(overall_arr):
"""
Uses Z-score to generate the signatures of data-points and also maps points on level of significance (include for
signature calculation, include for bug calculation, no significance).
If Z-score is equal to 1000.0 or in between sig_threshold and bug_threshold, no-significance.
If Z-score is >= sig_threshold, include for signature calculation.
If Z-score is <= bug_threshold, include for bug calculation.
Input:
The individual master-signature generated for each Cluster.
Output:
An array containing dictionaries marked with tags that represent the action that needs to be performed on them.
"""
signature = {}
for key, value in overall_arr.items():
sig_threshold = 0.5
bug_threshold = -0.1
key_points = []
data_points = []
sig_values = []
for k, v in value.items():
key_points.append(k)
data_points.append(v)
if len(data_points) == 1:
sig_values.append((key_points[0], (data_points[0])))
'''
Check for two data points case
'''
else:
z_score = calculate_z_score(data_points)
if len(z_score) > 0:
avg_z_score = sum(z_score)/len(z_score)
bug_threshold = bug_threshold + (avg_z_score - sig_threshold)
for i in range(len(z_score)):
present_zscore = z_score[i]
if present_zscore == 1000.0:
sig_values.append((key_points[i], "*", (data_points[i])))
elif present_zscore >= sig_threshold:
sig_values.append((key_points[i], (data_points[i])))
elif present_zscore <= bug_threshold:
sig_values.append((key_points[i], "!", (data_points[i])))
elif (present_zscore < sig_threshold) and (present_zscore > bug_threshold):
sig_values.append((key_points[i], "*", (data_points[i])))
if key in signature:
signature[key].append(sig_values)
else:
signature[key] = []
signature[key] += sig_values
return signature
def transform_data(data):
"""
A helper function to extract nested keys from the ACL and to add the frequency of the repeated value. Helps score data.
Input:
An ACL in the form {key1:value1, key2:{key3:value3}, key4:[value4], key5:[key6:{key7:value7}]}.
Output:
Extracted nested keys from the extract_keys function along with the frequency count.
Example:
[
{key1:{key2:value1, key3:value2, key4:{key5:value3}}
{key6:{key7:value2}
{key8:{key3:value3, key4:value5, key6:value3}}
]
Returns a new array with the nested keys appended along with a tuple containing the unnested value along with the frequency count.
[{
key1=key2:{'value1':1},
key1=key3:{'value2':2},
key1=key4=key5:{'value3':3},
key6=key7:{'value2':2},
key8=key3:{'value3':3},
key8=key4:{'value5':1},
key8=key6:{'value3':3}
}]
"""
count = 1
overall = {}
flag = 0
i = 0
while i < count:
value = None
result = None
new_value = None
for item in data:
result = extract_keys(item)
for element in result:
value = item
for key in element.split("="):
if key in value:
new_value = value[key]
if (type(new_value) == list) and (len(new_value) > 1):
if flag == 0:
count = len(new_value)
flag = 1
try:
new_value = new_value[i]
except:
new_value = new_value[-1]
elif (type(new_value) == list) and (len(new_value) == 1):
new_value = new_value[0]
value = new_value
if element not in overall:
overall[element] = {}
if type(value) != dict and type(value) != list:
if value not in overall[element]:
overall[element][value] = 1
i += 1
return overall
def calculate_signature_score(signature):
"""
Calculates the signature score for each signature as the sum of all the weights in it but ignoring the weights marked with "*".
Input:
A signature that contains tags of whether or not the weight should be included in calculating the signature.
Output:
An array containing the weights of all the signatures that should be considered.
Example:
Consider [
{'key1=key2':['val1', 40], 'key3=key4':['val2':90]}, //40 + 90
{'key5=key6=key7':['val3', *, 20], 'key8=key9':['val4':80]}, //80
{'key10=key11':['val5', 40]} //40
Returns [130, 80, 40].
"""
score_arr = []
for sig in signature:
score = 0
for key, value in sig.items():
for val in value:
if (val[1] != "!") and (val[1] != "*"):
score += val[1]
elif val[1] == "!":
score += val[2]
score_arr.append(score)
return score_arr
def calculate_namedstructure_scores(data_final, all_signatures):
"""
Calculate the individual scores for each discrete-ACL. This includes calculating human_error scores,
signature_scores, and deviant scores.
Input:
data_final:
List of ACLs grouped into a Cluster.
Example:
[
[acl-1, acl-4, acl-5, acl-9], //Cluster-0
[acl-2, acl-3], //Cluster-1
[acl-7], //Cluster-2
[acl-6, acl-8] //Cluster-3
]
all_signatures:
Consolidated signature for each Cluster.
Output:
deviant_arr: Returns all deviant properties for the ACL. Empty list is returned if no deviant property
in the ACL.
count_arr: [[TODO]]
dev_score: Returns the deviant score for the deviant properties found. 0 if no deviant property.
acls_arr: [[TODO]]
sig_score: Returns the signature score of the ACL.
cluster_num: Returns the cluster number that the ACL belongs to.
acls_score: The score that is generated for each acl
human_errors_arr: Returns the human_error properties (IPValidity, DigitRepetition, PortRange) for each ACL and
empty list if no human_error properties present in the ACL.
human_error_score: Returns the score of the human error property calculated for the ACL. 0 is returned if
no human_error property exists in the ACL.
"""
deviant_arr = []
count_arr = []
acls_dict = {}
acls_arr = []
acls_score = []
sig_score = []
dev_score = []
cluster_num = []
human_errors_arr = []
human_errors_score = []
i = 0
for acl_list in data_final:
bug_count = 0
conformer_count = 0
signature = all_signatures[i]
for acl in acl_list:
flag = 0
if str(acl[0]) not in acls_dict:
acls_dict[str(acl[0])] = 1
acls_arr.append(acl[0])
cluster_num.append(i)
flag = 1
else:
print(acl[0])
print(acls_dict)
continue
sig_score.append(signature_scores[i])
deviant = []
count = 0
dev_c = 0
acl_c = 0
human_errors = []
human_error_category = {}
data = transform_data(acl)
for data_key, data_val in data.items():
if data_key in signature:
'''
Key Valid. Now check for actual Value
'''
for val in data_val.items():
(error_key, error_value), error_category = calculateHumanErrors(data_key, val[0], signature[data_key], file_name.split(".")[0])
if error_category:
human_errors.append((error_key, error_value))
if error_category not in human_error_category:
human_error_category[error_category] = 0
human_error_category[error_category] += 1
for sig_val in signature[data_key]:
if val[0] == sig_val[0]:
'''
value also present. Now check if value part of bug/sig/skip
'''
if sig_val[1] == "!":
dev_c += sig_val[2]
acl_c += sig_val[2]
deviant.append((data_key, sig_val[0]))
bug_count += 1
elif sig_val[1] == "*":
conformer_count += 1
continue
else:
conformer_count += 1
count += sig_val[1]
acl_c += sig_val[1]
else:
'''
Deviant Key
'''
if data_key != "lines=name":
deviant.append(data_key)
dev_c += data_val
acl_c += data_val
if flag == 1:
count_arr.append(count)
deviant_arr.append(deviant)
dev_score.append(dev_c)
acls_score.append(acl_c)
human_errors_arr.append(human_errors)
human_errors_score.append(calculate_human_error_score(human_error_category))
i += 1
return deviant_arr, count_arr, dev_score, acls_arr, sig_score, cluster_num, acls_score, human_errors_arr, human_errors_score
def checkIPValidity(ip_address):
"""
A reg-ex check to verify the validity of an IP address.
Input:
A list of IP addresses
Output:
A boolean representing the validity of the IP address.
Returns 'True' if all the IPs are valid and 'False' if any of the IP is invalid.
"""
try:
ip_address = ip_address.split(":")
for ip in ip_address:
IP_check = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])?(\/)?((3[01]|3[02]|[12][0-9]|[0-9])?)$"
match = re.match(IP_check, ip)
if not match:
return False
return True
except e:
print(e)
return True
def checkPortRange(port_range):
"""
A check to verify that the port range is specified correctly (elem0 <= elem1).
Input:
A string that contains two numbers separated by a '-'.
Output:
A boolean representing the validity of the range (elem0 <= elem1).
Example:
52108-52109 (True)
466 - 466 (True)
466 - 465 (False)
"""
try:
port_split = port_range.split("-")
if port_split[-1] < port_split[0]:
return False
return True
except:
return True
def checkDigitRepetition(digit, signature):
"""
Checks for Digit repetition.
Input:
The value for the following keys: srcPorts, dstPorts, lengthRange
Output:
Returns True if there is any Human Error and the digit is repeated twice.
"""
try:
if type(digit) == str:
digit = float(digit.split(":")[0])
if digit == 0:
return False
for item in signature:
if type(item) == str:
item = int(item.split(":")[0])
if digit == (item*10+item%10):
print("--------", digit, item*10 + item%10)
return True
return False
except:
return False
def calculateHumanErrors(data_key, data, signature, namedStructure):
"""
Checks for simple human errors like entering invalid IP Addresses, incorrect port-ranges, and digit repetitions.
Input:
data_key: The nested keys calculated in the overall_dict and get_overall_dict methods.
Example: key1=key2=key4
data: The data value for the keys.
signature: The signature for the keys that was calculated in the calculate_signature_d method.
namedStructure: The type of the IP file.
Possible values: IP_Access_List, Route_Filter_List, Routing_Policy, VRF, others.
Output:
Returns the error and the category it belongs to.
Example:
key1=key2=key3 [1333.0.0.13] [1333.0.0.13] IP_Access_List
Returns:
key1=key2=key3 [1333.0.0.13] IP
"""
human_error = (None, None)
category = None
data_key = data_key.split("=")[-1]
signature_items = []
for sig_item in signature:
signature_items.append(sig_item[0])
if namedStructure == "IP_Access_List":
if data_key == "ipWildcard":
if not checkIPValidity(data):
'''
Invalid IP
'''
human_error = (data_key, data)
category = "IP"
elif data_key in ["dstPorts", "srcPorts"]:
if not checkPortRange(data):
'''
Invalid Ports Range
'''
human_error = (data_key, data)
category = "RANGE"
elif namedStructure == "Route_Filter_List":
if data_key == "ipWildcard":
if not checkIPValidity(data):
'''
Invalid IP
'''
human_error = (data_key, data)
category = "IP"
elif data_key == "lengthRange":
if not checkPortRange(data):
'''
Invalid Ports Range
'''
human_error = (data_key, data)
category = "RANGE"
elif namedStructure == "Routing_Policy":
if data_key == "communities":
if checkDigitRepetition(data, signature_items):
'''
Error Copying digits
'''
human_error = (data_key, data)
category = "DIGIT"
elif data_key == "ips":
if not checkIPValidity(data):
'''
Invalid IP
'''
human_error = (data_key, data)
category = "IP"
elif namedStructure == "VRF":
if data_key in ["administrativeCost", "remoteAs", "metric", "localAs", "referenceBandwidth", ]:
if checkDigitRepetition(data, signature_items):
'''
Error Copying digits
'''
human_error = (data_key, data)
category = "DIGIT"
elif data_key in ["peerAddress", "localIp", "routerId", "network"]:
if not checkIPValidity(data):
'''
Invalid IP
'''
human_error = (data_key, data)
category = "IP"
'''
Any Other namedStructure
'''
else:
try:
if re.search('IP|ip', data_key) and not re.search('[a-zA-Z]', data):
if not checkIPValidity(data):
'''
Invalid IP
'''
human_error = (data_key, data)
category = "IP"
elif not re.search("[a-zA-Z]", data):
if checkDigitRepetition(data, signature_items):
'''
Error Copying digits
'''
human_error = (data_key, data)
category = "DIGIT"
except:
pass
return human_error, category
def calculate_human_error_score(category_dict):
"""
Scores the human_errors that have been found with IPValidity and DigitRepetition errors
weighed as 'high,' i.e, 0.8 and PortRange errors weighed 'medium,' i.e., 0.5.
Input:
A dictionary containing the count of the error occurrences.
Output:
A weighted sum of all the errors found.
"""
total_score = 0
low = 0.2
medium = 0.5
high = 0.8
weightage_dict = {"IP": high, "RANGE": medium, "DIGIT": high}
for category, count in category_dict.items():
if count != 0:
#print("* Human Error Found *")
total_score += weightage_dict[category]/np.log(1+count)
return round(total_score/len(category_dict), 2) if category_dict else total_score
def flatten_json(data, delimiter):
"""
Flattens a JSON file.
Input:
data:
A JSON dictionary of hierarchical format.
{key1: {key2: value2, key3: value3}, key4: {key5: value5, key6: [value6, value7, value8]}}
delimiter:
A parameter to separate the keys in order to facilitate easy splitting.
Output:
A flattened dictionary with keys separated by the delimiter parameter.
key1_key2:value2, key1_key3:value3, key4_key5:value5, key4_key6:value6, key4_key6:value7, key4_key6:value8
"""
out = {}
flatten(data)
return out
def encode_data(data):
"""
Converts categorical values into numeric values. We use MultiLabelBinarizer to encode categorical data.
This is done in order to pass the data into clustering and other similar algorithms that can only handle numerical data.
Flattens each ACL list and then encodes them.
Input:
A Python list that contains all discrete-ACLs.
Output:
A Python list after encoding.
"""
flattenedData = []
allKeys = []
for NS in data:
flattenedNamedStructure = flatten_json(NS, '_')
flattenedData.append(flattenedNamedStructure)
for key in flattenedNamedStructure.keys():
if key not in allKeys:
allKeys.append(key)
mergedData = []
for NS in flattenedData:
mergedNS = []
for key, value in NS.items():
mergedNS.append(str(value))
mergedData.append(mergedNS)
mlb = MultiLabelBinarizer()
data_T = mlb.fit_transform(mergedData)
print("MLb classes=")
print(mlb.classes_)
return data_T, mlb.classes_
def export_clusters(data, acl_weight_mapper):
"""
Helper Method to verify authenticity of Clusters being formed.
Input:
The data that is sorted into list of Clusters.
Example:
[
[acl-1, acl-4, acl-5, acl-9], //Cluster-0
[acl-2, acl-3], //Cluster-1
[acl-7], //Cluster-2
[acl-6, acl-8] //Cluster-3
]
We also make use of acl_dict and node_name_dict dictionaries by searching for the ACL and
then getting the appropriate ACL_name and the nodes that the ACL is present in.
Output:
A csv file by the name of Generated_Clusters is written in the format:
Cluster-0 |||| Cluster-0 Names |||| Cluster-0 Nodes |||| Cluster-1 |||| Cluster-1 Names |||| Cluster-1 Nodes
acl-1 |||| permit tcp eq 51107 |||| st55in15hras |||| acl-2 |||| permit udp any eq 1200 |||| rt73ve11m5ar
acl-4 |||| permit tcp eq 51102 |||| st55in15hras, st55in17hras |||| acl-3 |||| permit udp any eq 120002 |||| rt73ve10m4ar
acl-5 |||| permit tcp eq 51100 |||| st55in17hras ||||
acl-9 |||| permit tcp eq 51109 |||| st55in17hras ||||
"""
column_labels = []
for index in range(len(data)):
column_labels.append("Cluster " + str(index))
column_labels.append("Cluster " + str(index) + " ACL Weights")
column_labels.append("Cluster " + str(index) + " Nodes")
data_to_export = pd.DataFrame(columns=column_labels)
for cluster_index, cluster_data in enumerate(data):
discrete_ACL_nodes = []
cluster_weights = []
for discrete_ACL in cluster_data:
temp = json.dumps(discrete_ACL[0], sort_keys=True)
temp_arr = []
try:
for node in namedstructure_node_mapper[temp]:
temp_arr.append(node)
discrete_ACL_nodes.append(temp_arr)
except:
discrete_ACL_nodes.append(None)
cluster_weights.append(acl_weight_mapper[temp])
cluster_data = pd.Series(cluster_data)
cluster_weights_series = pd.Series(cluster_weights)
discrete_ACL_nodes = pd.Series(discrete_ACL_nodes)
data_to_export["Cluster " + str(cluster_index)] = cluster_data
data_to_export["Cluster " + str(cluster_index) + " ACL Weights"] = cluster_weights_series
data_to_export["Cluster " + str(cluster_index) + " Nodes"] = discrete_ACL_nodes
file = file_name.split(".")[0]
print(file)
title = "Clusters_" + file + ".csv"
print(title)
data_to_export.to_csv(title)
def parse_data():
"""
A helper method to parse through the input configuration files and capture necessary information.
Input:
None. The file path parameter is read from the commandline arguments.
Output:
discrete_namedstructure: A list that contains stringified named-structures.
namedstructure_nod_mapper: A dictionary that contains the named-structure configuration as key and a list of
nodes it is a part of as value.
"""
df = pd.read_json(sys.argv[2], orient="index")
discrete_namedstructure = []
namedstructure_node_mapper = {} # Maps each discrete_acl with all the nodes that it belongs to
discrete_nodes = []
for column in df.columns:
for index, data in df[column].iteritems():
if data is not None:
if 'lines' in data[0]:
data_holder = 'lines'
data_to_look_under = data[0][data_holder]
elif 'statements' in data[0]:
data_holder = 'statements'
data_to_look_under = data[0][data_holder]
else:
data_to_look_under = data
for discrete_acl in data_to_look_under:
if 'name' in discrete_acl:
del discrete_acl['name']
discrete_acl = json.dumps(discrete_acl, sort_keys=True)
discrete_namedstructure.append(discrete_acl)
if discrete_acl in namedstructure_node_mapper:
nodes = namedstructure_node_mapper[discrete_acl]
if index not in nodes:
nodes.append(index)
namedstructure_node_mapper[discrete_acl] = nodes
else:
namedstructure_node_mapper[discrete_acl] = [index]
if index not in discrete_nodes:
discrete_nodes.append(index)
print("The number of discrete nodes in a network is: ", len(discrete_nodes))
return discrete_namedstructure, namedstructure_node_mapper
def perform_pca_analysis(encoded_data, column_names):
"""
A helper method to analyse the data using PCA
"""
pca = PCA()
pca.fit(encoded_data)
cumulative_variance = np.cumsum(np.round(pca.explained_variance_ratio_, decimals=8) * 100);
labels = [x for x in range(1, len(cumulative_variance) + 1)];
loadings = pd.DataFrame(pca.components_.T, columns=labels, index=column_names)
significance = {}
for index in loadings.index:
temp_list = loadings.loc[index]
sig = 0
for value in temp_list:
sig += value * value
significance[index] = sig
plt.plot(cumulative_variance)
plt.xlabel("N-components")
plt.ylabel("Cumulative Explained Variance")
plt.show()
sorted_significance = sorted(significance.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
top_ten_attributes = []
for sigAttr in sorted_significance:
top_ten_attributes.append(sigAttr[0])
print("Top Ten Attributes:")
print(top_ten_attributes)
def silhouette_analysis(data, acl_weights):
"""
A helper method to perform an analysis of various scoring functions
"""
from sklearn.metrics import silhouette_score, davies_bouldin_score
k_range = range(2, 30)
elbow_scores = []
silhouette_scores = []
davies_bouldin_scores = []
elbow_file = open("elbow_scores.txt", "w")
silhouette_file = open("silhouette_scores.txt", "w")
davies_bouldin_file = open("davies_bouldin_scores.txt", "w")
for num_clusters in k_range:
print(num_clusters)
kmeans = KMeans(n_clusters=num_clusters)
cluster_labels = kmeans.fit_predict(data, None, sample_weight=acl_weights)
cluster_centers = kmeans.cluster_centers_
k_distance = cdist(data, cluster_centers, "euclidean")
distance = np.min(k_distance, axis=1)
distortion = np.sum(distance) / data.shape[0]
silhouette_avg = silhouette_score(data, cluster_labels)
davies_bouldin_avg = davies_bouldin_score(data, cluster_labels)
silhouette_scores.append(silhouette_avg)
davies_bouldin_scores.append(davies_bouldin_avg)
elbow_scores.append(distortion)
silhouette_file.write(str(silhouette_avg) + " ")
davies_bouldin_file.write(str(davies_bouldin_avg) + " ")
elbow_file.write(str(distortion) + " ")
kn_elbow = KneeLocator(list(k_range), elbow_scores, S=5.0, curve='convex', direction='decreasing')
plt.scatter(x=k_range, y=elbow_scores)
plt.xlabel("Range")
plt.ylabel("Elbow Score")
plt.vlines(kn_elbow.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
plt.show()
kn_silhouette = KneeLocator(list(k_range), silhouette_scores, S=5.0, curve='convex', direction='increasing')
plt.scatter(x=k_range, y=silhouette_scores)
plt.xlabel("Range")
plt.ylabel("Silhouette Score")
plt.vlines(kn_silhouette.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
plt.show()
kn_davies_bouldin = KneeLocator(list(k_range), davies_bouldin_scores, S=5.0, curve='convex', direction='decreasing')
plt.scatter(x=k_range, y=davies_bouldin_scores)
plt.xlabel("Range")
plt.ylabel("Davies Bouldin Score")
plt.vlines(kn_davies_bouldin.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
plt.show()
'''
# Helper Methods End
# *****************************************************************************
# *****************************************************************************
'''
whitelistDict = {}
Z_SCORE_FLAG = 0
ACTION_FLAG = 0
k_select = 0
'''
Parsing Data
'''
try:
file_name = sys.argv[2].split("/")[-1]
network_name = "DATA_HERE_" + sys.argv[2].split("/")[-2]
print(network_name)
'''
Making Outlier Directory for Current Network
'''
if not os.path.exists(network_name):
os.makedirs(network_name)
flag_file = network_name + '/' + '.flag_' + file_name
if sys.argv[1] == "-j":
df = pd.read_json(sys.argv[2], orient="index")
try:
if sys.argv[4] == "-a":
ACTION_FLAG = 3
except:
ACTION_FLAG = 0
try:
Z_SCORE_FLAG = int(sys.argv[3])
except:
error_msg("Invalid Z-Score Argument sent", sys.argv[3])
f = open(flag_file,'w')
f.write('{}'.format(ACTION_FLAG))
f.close()
elif sys.argv[1] == "-e":
df = pd.read_json(sys.argv[2], orient= "index")
try:
with open(sys.argv[3], 'rb') as handle:
whitelistDict = pickle.load(handle)
except:
print("FileNotFoundError: Please check if file exists.")
ACTION_FLAG = 1
elif sys.argv[1] == "-d":
df = pd.read_json(sys.argv[2],orient = "index")
ACTION_FLAG = 2
else:
error_msg("Invalid Argument or flags sent", sys.argv[1])
except:
error_msg("Invalid File specified. Please check the input dataset", sys.argv[2])
outlier_filename = network_name + '/' + 'outlier_' + file_name
cluster_filename = network_name + '/' + '.cluster_' + file_name
sig_filename = network_name + '/' + '.sig_' + file_name
outlier_nodes_filename = network_name + '/' + '.outlier_nodes_' + file_name
print(outlier_filename, cluster_filename ,sig_filename, outlier_nodes_filename)
print("===========================================================")
print(Fore.BLUE, end='')
print("outlier-analyzer code started ...")
print(Style.RESET_ALL)
print(Fore.GREEN, end='')
start = time.time()
'''
Calculating outliers selected
'''
f = open(flag_file, 'r')
flag = f.readline()
f.close()
discrete_namedstructure, namedstructure_node_mapper = parse_data()
if (ACTION_FLAG == 0) or (ACTION_FLAG == 3):
mlb = MultiLabelBinarizer()
ns_weight_mapper = {}
data_for_clustering = []
namedstructure_weights = []
for ns in discrete_namedstructure:
if ns not in ns_weight_mapper.keys():
ns_weight_mapper[ns] = 1
else:
value = ns_weight_mapper[ns]
ns_weight_mapper[ns] += 1
for ns, weight in ns_weight_mapper.items():
ns = json.loads(ns)
data_for_clustering.append(ns)
namedstructure_weights.append(weight)
encodedLists, column_names = encode_data(data_for_clustering)
df_enc = pd.DataFrame(encodedLists)
df_enc = df_enc.dropna(axis=1, how='any')
# perform_pca_analysis(encodedLists, column_names)
print("data encoding done...")
'''
Perform K-Means
'''
print("starting data clustering...")
perform_kmeans_clustering(df_enc, namedstructure_weights)
print("data clustering done...")
# silhouette_analysis(df_enc, acl_weights)
'''
Grouping data based on their Clusters
'''
cluster_range = np.arange(k_select)
data_final = []
data_final_enc = []
for index in cluster_range:
temp = []
temp_enc = []
for i in range(len(df_enc)):
if df_enc['kmeans_cluster_number'][i] == index:
temp.append([data_for_clustering[i]])
temp_enc.append([data_for_clustering[i]])
data_final.append(temp)
data_final_enc.append(temp_enc)
# export_clusters(data_final, acl_weight_mapper)
'''
Writing Clustered Data into a file
'''
with open(cluster_filename, 'w') as f:
f.write(json.dumps(data_final))
'''
Calculating Overall Structure per Cluster
'''
if ACTION_FLAG == 3:
overall_array_0 = overall_dict(data_final)
try:
overall_array = get_overall_dict(data_final)
except:
overall_array = overall_dict(data_final)
'''
Generating Signatures
'''
all_signatures = []
for i in range(len(overall_array)):
signature = calculate_signature_d(overall_array[i])
all_signatures.append(signature)
print("signature creation done...")
'''
Retuning Signature
'''
elif ACTION_FLAG == 1:
all_signatures = []
try:
with open(sig_filename, 'r') as f:
for item in f:
all_signatures.append(json.loads(item))
except FileNotFoundError:
print(Fore.RED, end='')
print("\nERROR: Calculate outliers on this data first!\n")
print(Style.RESET_ALL)
print("__________________________________")
print(Fore.RED, end='')
print("outlier-analyzer code failed #")
print(Style.RESET_ALL)
print("__________________________________")
sys.exit()
all_signatures = all_signatures[0]
wlDict = copy.deepcopy(whitelistDict['deviant'])
for edit_key, edit_value in whitelistDict['deviant']:
flag = 0
for signature in all_signatures:
if edit_key in signature:
for j in range(len(signature[edit_key])):
if edit_value in signature[edit_key][j][0]:
if signature[edit_key][j][1] == "!" or signature[edit_key][j][1] == "*":
try:
temp = (edit_value, signature[edit_key][j][2])
signature[edit_key][j] = temp
flag = 1
except Exception as e:
print(e)
if flag == 1:
wlDict.remove((edit_key, edit_value))
if wlDict:
print(Fore.RED, end='')
print("\nERROR : Specified Attributes {} either\n\tnot present or not a bug!".format(wlDict))
print(Style.RESET_ALL, end='')
print("__________________________________")
print(Fore.RED, end='')
print("outlier-analyzer code failed #")
print(Style.RESET_ALL, end='')
print("__________________________________")
sys.exit(0)
print("signature re-tuning done...")
data_final = []
with open(cluster_filename, 'r') as f:
for item in f:
data_final.append(json.loads(item))
data_final = data_final[0]
'''
Displaying the Outlier Nodes
'''
elif ACTION_FLAG == 2:
outlier_nodes_arr = []
try:
with open(outlier_nodes_filename, 'r') as f:
for item in f:
outlier_nodes_arr.append(json.loads(item))
except FileNotFoundError:
print(Fore.RED, end='')
print("\nERROR: Calculate outliers on this data first!\n")
print(Style.RESET_ALL)
print("__________________________________")
print(Fore.RED, end='')
print("outlier-analyzer code failed #")
print(Style.RESET_ALL)
print("__________________________________")
sys.exit()
print(Style.RESET_ALL)
print("########################")
print("Outlier Nodes are:")
outlier_nodes_arr = outlier_nodes_arr[0]
print(Fore.RED, end='')
print(*outlier_nodes_arr, sep="\n")
print(Style.RESET_ALL)
print("########################")
sys.exit(0)
'''
Scoring Signature
'''
signature_scores = calculate_signature_score(all_signatures)
print("signature scoring done...")
'''
Scoring ACLs
'''
deviant_arr, count_arr, dev_score, acls_arr, sig_score, cluster_num, acls_score, human_errors_arr, human_errors_score \
= calculate_namedstructure_scores(data_final, all_signatures)
print("acl scoring done...")
'''
Calculate outlier nodes
'''
count = 0
outlier_nodes = set()
for i in range(len(deviant_arr)):
if len(deviant_arr[i]) > 0:
count += 1
temp = json.dumps(acls_arr[i], sort_keys=True)
for item in namedstructure_node_mapper[temp]:
outlier_nodes.add(item)
with open(outlier_nodes_filename, 'w') as f:
f.write(json.dumps(list(outlier_nodes)))
'''
writing all signature to a hidden file
'''
with open(sig_filename, 'w') as f:
f.write(json.dumps(all_signatures))
nodes = []
for i in range(len(acls_arr)):
temp = json.dumps(acls_arr[i], sort_keys=True)
tempArr = []
try:
for item in namedstructure_node_mapper[temp]:
tempArr.append(item)
nodes.append(tempArr)
except:
nodes.append(None)
'''
Creating dataframe and exporting as a json file
'''
df_final = pd.DataFrame()
with open("deviant_array.txt", "w") as f:
print(deviant_arr, file=f)
print(human_errors_arr)
master_signatures = []
for i in range(len(data_final)):
for index in data_final[i]:
master_signatures.append(all_signatures[i])
# df_final['acl_name'] = acl_names
df_final['cluster_number'] = cluster_num
df_final['Conformer/Signature Definition'] = master_signatures
df_final['acl_structure'] = acls_arr
df_final['nodes'] = nodes
df_final['deviant_properties'] = deviant_arr
df_final['human_error_properties'] = human_errors_arr
df_final['human_error_score'] = human_errors_score
df_final['similarity_score'] = count_arr
df_final['acl_score'] = acls_score
df_final['max_sig_score'] = sig_score
outlier_flag = ['T' if len(deviant_prop)==0 else 'F' for deviant_prop in deviant_arr]
df_final['Outlier Flag'] = outlier_flag
df_final.to_json(outlier_filename, orient='split', index=False)
print(Style.RESET_ALL, end="")
end = time.time()
print(df_final)
print("###")
print(Fore.BLUE, end='')
print("OUTLIER-ANALYZER SUCCESSFUL #")
print("time to run : {} seconds".format(round(end - start), 3))
print(Style.RESET_ALL, end='')
print()
print("###########################################################")
print(outlier_nodes)
print(Fore.BLUE, end='')
print("\nTotal Outliers Count = {}".format(len(outlier_nodes)))
print(Style.RESET_ALL, end='')
print("\nTo view the detailed report, open the")
print("json file named: '{}'\n".format(outlier_filename))
print("###########################################################")
print()
sys.exit(0)
| 34.326633 | 170 | 0.549114 |
cc61b60657d94c8b13604d637733f5892011c4df | 748 | py | Python | war.py | hiraokusky/pronwar | bfc9afb958dcd0523578075a734350007d3f55ff | [
"MIT"
] | null | null | null | war.py | hiraokusky/pronwar | bfc9afb958dcd0523578075a734350007d3f55ff | [
"MIT"
] | null | null | null | war.py | hiraokusky/pronwar | bfc9afb958dcd0523578075a734350007d3f55ff | [
"MIT"
] | null | null | null | import json
from collections import OrderedDict
import pprint
import json
import sys
# prons = sys.argv
prons = ['pron1.json', 'pron2.json','pron3.json','pron4.json']
for pron in prons:
synset = war(pron)
print(json.dumps(synset, indent=2, ensure_ascii=False))
| 29.92 | 85 | 0.580214 |
cc61c5747c8e80d78815a2359b70248eed632e99 | 495 | py | Python | app/main/__init__.py | ChegeDaniella/Pitches | 40b6bea69fe8774ca39e6199e9e80f32429503fd | [
"MIT"
] | null | null | null | app/main/__init__.py | ChegeDaniella/Pitches | 40b6bea69fe8774ca39e6199e9e80f32429503fd | [
"MIT"
] | null | null | null | app/main/__init__.py | ChegeDaniella/Pitches | 40b6bea69fe8774ca39e6199e9e80f32429503fd | [
"MIT"
] | null | null | null | from flask import Blueprint,Flask
main = Blueprint('main',__name__)
from app.main import views
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
bootstrap= Bootstrap()
db = SQLAlchemy()
| 16.5 | 43 | 0.739394 |
cc62fe75b877b6b99c9222c7927faf2a48f691e2 | 506 | py | Python | tkinter/grid-pack/example-1.py | whitmans-max/python-examples | 881a8f23f0eebc76816a0078e19951893f0daaaa | [
"MIT"
] | 140 | 2017-02-21T22:49:04.000Z | 2022-03-22T17:51:58.000Z | tkinter/grid-pack/example-1.py | whitmans-max/python-examples | 881a8f23f0eebc76816a0078e19951893f0daaaa | [
"MIT"
] | 5 | 2017-12-02T19:55:00.000Z | 2021-09-22T23:18:39.000Z | tkinter/grid-pack/example-1.py | whitmans-max/python-examples | 881a8f23f0eebc76816a0078e19951893f0daaaa | [
"MIT"
] | 79 | 2017-01-25T10:53:33.000Z | 2022-03-11T16:13:57.000Z | #!/usr/bin/env python3
'''set frame height 10%, 80%, 10%'''
import tkinter as tk
root = tk.Tk()
root.geometry('400x300')
header = tk.Frame(root, bg='green')
content = tk.Frame(root, bg='red')
footer = tk.Frame(root, bg='green')
root.columnconfigure(0, weight=1) # 100%
root.rowconfigure(0, weight=1) # 10%
root.rowconfigure(1, weight=8) # 80%
root.rowconfigure(2, weight=1) # 10%
header.grid(row=0, sticky='news')
content.grid(row=1, sticky='news')
footer.grid(row=2, sticky='news')
root.mainloop()
| 21.083333 | 40 | 0.679842 |
cc646705f21a4dc7ee92c166bbcc05bcef77bd7a | 2,524 | py | Python | step_7_generate_pr_bins.py | byuccl/fiate | 318f634badd69f241091277ead59d7ead64ee6aa | [
"Apache-2.0"
] | 1 | 2021-05-12T09:42:14.000Z | 2021-05-12T09:42:14.000Z | step_7_generate_pr_bins.py | byuccl/fiate | 318f634badd69f241091277ead59d7ead64ee6aa | [
"Apache-2.0"
] | null | null | null | step_7_generate_pr_bins.py | byuccl/fiate | 318f634badd69f241091277ead59d7ead64ee6aa | [
"Apache-2.0"
] | 3 | 2021-04-19T19:36:06.000Z | 2021-08-17T01:46:23.000Z | from lib import *
generate_bins("./bld/bits/vex_pb0_partial.bit","./bld/bins/vex_pb0.bin",0x8D)
generate_bins("./bld/bits/vex_pb1_partial.bit","./bld/bins/vex_pb1.bin",0x8D)
generate_bins("./bld/bits/vex_pb2_partial.bit","./bld/bins/vex_pb2.bin",0x8D)
generate_bins("./bld/bits/vex_tmr_pb0_partial.bit","./bld/bins/vex_tmr_pb0.bin",0x8D)
generate_bins("./bld/bits/vex_tmr_pb1_partial.bit","./bld/bins/vex_tmr_pb1.bin",0x8D)
generate_bins("./bld/bits/vex_tmr_pb2_partial.bit","./bld/bins/vex_tmr_pb2.bin",0x8D)
generate_bins("./bld/bits/mb_pb0_partial.bit","./bld/bins/mb_pb0.bin",0x8D)
generate_bins("./bld/bits/mb_pb1_partial.bit","./bld/bins/mb_pb1.bin",0x8D)
generate_bins("./bld/bits/mb_pb2_partial.bit","./bld/bins/mb_pb2.bin",0x8D)
generate_bins("./bld/bits/mb_tmr_pb0_partial.bit","./bld/bins/mb_tmr_pb0.bin",0x8D)
generate_bins("./bld/bits/mb_tmr_pb1_partial.bit","./bld/bins/mb_tmr_pb1.bin",0x8D)
generate_bins("./bld/bits/mb_tmr_pb2_partial.bit","./bld/bins/mb_tmr_pb2.bin",0x8D)
generate_bins("./bld/bits/taiga_pb0_partial.bit","./bld/bins/taiga_pb0.bin",0x8D)
generate_bins("./bld/bits/taiga_pb1_partial.bit","./bld/bins/taiga_pb1.bin",0x8D)
generate_bins("./bld/bits/taiga_pb2_partial.bit","./bld/bins/taiga_pb2.bin",0x8D)
generate_bins("./bld/bits/taiga_tmr_pb0_partial.bit","./bld/bins/taiga_tmr_pb0.bin",0x8D)
generate_bins("./bld/bits/taiga_tmr_pb1_partial.bit","./bld/bins/taiga_tmr_pb1.bin",0x8D)
generate_bins("./bld/bits/taiga_tmr_pb2_partial.bit","./bld/bins/taiga_tmr_pb2.bin",0x8D)
generate_bins("./bld/bits/pico_pb0_partial.bit","./bld/bins/pico_pb0.bin",0x8D)
generate_bins("./bld/bits/pico_pb1_partial.bit","./bld/bins/pico_pb1.bin",0x8D)
generate_bins("./bld/bits/pico_pb2_partial.bit","./bld/bins/pico_pb2.bin",0x8D)
generate_bins("./bld/bits/pico_tmr_pb0_partial.bit","./bld/bins/pico_tmr_pb0.bin",0x8D)
generate_bins("./bld/bits/pico_tmr_pb1_partial.bit","./bld/bins/pico_tmr_pb1.bin",0x8D)
generate_bins("./bld/bits/pico_tmr_pb2_partial.bit","./bld/bins/pico_tmr_pb2.bin",0x8D)
generate_bins("./bld/bits/kron_pb0_partial.bit","./bld/bins/kron_pb0.bin",0x8D)
generate_bins("./bld/bits/kron_pb1_partial.bit","./bld/bins/kron_pb1.bin",0x8D)
generate_bins("./bld/bits/kron_pb2_partial.bit","./bld/bins/kron_pb2.bin",0x8D)
generate_bins("./bld/bits/kron_tmr_pb0_partial.bit","./bld/bins/kron_tmr_pb0.bin",0x8D)
generate_bins("./bld/bits/kron_tmr_pb1_partial.bit","./bld/bins/kron_tmr_pb1.bin",0x8D)
generate_bins("./bld/bits/kron_tmr_pb2_partial.bit","./bld/bins/kron_tmr_pb2.bin",0x8D) | 60.095238 | 89 | 0.768225 |
cc64f175ff792df752b089599b18bdca929aecf6 | 922 | py | Python | tests/dsl/set_unit_test.py | chen0040/pysie | 5e5edeae214009b963405cb1e5c948980bb4ae93 | [
"MIT"
] | 2 | 2019-04-13T19:50:46.000Z | 2020-10-11T07:26:29.000Z | tests/dsl/set_unit_test.py | chen0040/pysie | 5e5edeae214009b963405cb1e5c948980bb4ae93 | [
"MIT"
] | null | null | null | tests/dsl/set_unit_test.py | chen0040/pysie | 5e5edeae214009b963405cb1e5c948980bb4ae93 | [
"MIT"
] | 1 | 2020-06-15T10:30:47.000Z | 2020-06-15T10:30:47.000Z | import unittest
from pysie.dsl.set import TernarySearchTrie
if __name__ == '__main__':
unittest.main() | 30.733333 | 54 | 0.614967 |
cc66060295d57944997a0a9eb2202003307a5a50 | 825 | py | Python | server/dataplay/usersvc/service.py | data2068/dataplay3 | 6834bbf589cefa6007176da3577b5146eda70f52 | [
"Apache-2.0"
] | 153 | 2019-04-19T22:14:43.000Z | 2022-03-17T08:48:46.000Z | server/dataplay/usersvc/service.py | diandian11/dataplay3 | 59d41028e9fc1d64f5abc0ede93a4f8b9184854c | [
"Apache-2.0"
] | 10 | 2019-04-14T16:10:11.000Z | 2021-01-04T02:54:13.000Z | server/dataplay/usersvc/service.py | diandian11/dataplay3 | 59d41028e9fc1d64f5abc0ede93a4f8b9184854c | [
"Apache-2.0"
] | 51 | 2019-04-14T16:02:52.000Z | 2022-03-05T00:52:42.000Z | from sanic import Blueprint
from sanic import response
from sanic.log import logger
from sanic_openapi import doc
from .user import get_user, get_routes
user_svc = Blueprint('user_svc')
| 26.612903 | 53 | 0.699394 |
cc6617c6b503c309c32e9fd739483b4b5f04738c | 15,071 | py | Python | dnabot/test_ot2_scripts/purification_template_2.8_test.py | BASIC-DNA-ASSEMBLY/dnabot | d53710d58a4ae3fb2e950f2ca21765fe25abc2e8 | [
"MIT"
] | 3 | 2019-11-17T17:28:55.000Z | 2019-11-19T19:24:58.000Z | dnabot/test_ot2_scripts/purification_template_2.8_test.py | BASIC-DNA-ASSEMBLY/dnabot | d53710d58a4ae3fb2e950f2ca21765fe25abc2e8 | [
"MIT"
] | 2 | 2019-11-15T20:33:03.000Z | 2019-11-16T12:41:55.000Z | dnabot/test_ot2_scripts/purification_template_2.8_test.py | BASIC-DNA-ASSEMBLY/dnabot | d53710d58a4ae3fb2e950f2ca21765fe25abc2e8 | [
"MIT"
] | 7 | 2019-11-15T20:21:19.000Z | 2019-11-25T11:53:27.000Z | from opentrons import protocol_api
# Rename to 'purification_template' and paste into 'template_ot2_scripts' folder in DNA-BOT to use
metadata = {
'apiLevel': '2.8',
'protocolName': 'purification_template',
'description': 'Implements magbead purification reactions for BASIC assembly using an opentrons OT-2'}
# example values produced by DNA-BOT for a single construct containing 5 parts, un-comment and run to test the template:
sample_number=8
ethanol_well='A3'
| 47.393082 | 159 | 0.618141 |
cc67238765ba95b77b94fefb1d5fa168307525e1 | 1,921 | py | Python | DjangoBlog/articles/migrations/0009_auto_20210815_1840.py | Dimple278/Publication-Repository | ec274bf5822e160b90f0a5bc8559c1d199e12854 | [
"Unlicense",
"MIT"
] | null | null | null | DjangoBlog/articles/migrations/0009_auto_20210815_1840.py | Dimple278/Publication-Repository | ec274bf5822e160b90f0a5bc8559c1d199e12854 | [
"Unlicense",
"MIT"
] | 1 | 2021-08-08T06:46:46.000Z | 2021-08-08T06:46:46.000Z | DjangoBlog/articles/migrations/0009_auto_20210815_1840.py | Dimple278/Publication-Repository | ec274bf5822e160b90f0a5bc8559c1d199e12854 | [
"Unlicense",
"MIT"
] | 2 | 2021-07-03T11:55:11.000Z | 2021-08-09T08:27:52.000Z | # Generated by Django 3.2.4 on 2021-08-15 12:55
from django.db import migrations, models
| 30.015625 | 142 | 0.548673 |
cc676366b3fceddf1caf5ecfe78cd52bb3870d2d | 2,567 | py | Python | ecommerce/api/tests/views_tests.py | MayaraMachado/sns_and_sqs_project | 4fcc5bbb5f6841543ea8dda353dd85a43024f683 | [
"MIT"
] | 5 | 2020-06-22T21:29:54.000Z | 2021-11-01T20:12:04.000Z | ecommerce/api/tests/views_tests.py | MayaraMachado/sns_and_sqs_project | 4fcc5bbb5f6841543ea8dda353dd85a43024f683 | [
"MIT"
] | 5 | 2021-03-30T13:38:15.000Z | 2021-09-22T19:10:27.000Z | ecommerce/api/tests/views_tests.py | MayaraMachado/sns_and_sqs_project | 4fcc5bbb5f6841543ea8dda353dd85a43024f683 | [
"MIT"
] | null | null | null | import pytest
import json
from django.urls import reverse
| 35.652778 | 105 | 0.700818 |
cc6abadfa6473eb99280316b2542ed0cff6cc265 | 3,056 | py | Python | Features/CAI.py | jcg/d-tailor | 7ea83bcf7a2cda21eb8727575ff2b20ac8b49606 | [
"BSD-2-Clause"
] | 14 | 2016-05-19T08:31:44.000Z | 2021-08-05T08:56:56.000Z | Features/CAI.py | jcg/d-tailor | 7ea83bcf7a2cda21eb8727575ff2b20ac8b49606 | [
"BSD-2-Clause"
] | 1 | 2018-09-25T12:00:23.000Z | 2018-12-10T18:42:31.000Z | Features/CAI.py | jcg/d-tailor | 7ea83bcf7a2cda21eb8727575ff2b20ac8b49606 | [
"BSD-2-Clause"
] | 4 | 2016-06-23T21:40:49.000Z | 2021-02-02T03:05:35.000Z | '''
Created on Nov 16, 2011
@author: jcg
'''
from Features.Feature import Feature
import Functions
from uuid import uuid4
import Solution
| 51.79661 | 200 | 0.571008 |
cc6aeaaae4e5bb3332145b24a68cddaba311806b | 132 | py | Python | portfolio/urls.py | radoslawdabrowski/radoslawdabrowski.pl | b3d4f92ea51b40b104449259a376134aeb11766b | [
"Apache-2.0"
] | 1 | 2019-05-17T10:57:25.000Z | 2019-05-17T10:57:25.000Z | portfolio/urls.py | radoslawdabrowski/radoslawdabrowski.pl | b3d4f92ea51b40b104449259a376134aeb11766b | [
"Apache-2.0"
] | 1 | 2019-08-06T01:55:54.000Z | 2019-08-06T01:55:54.000Z | portfolio/urls.py | radoslawdabrowski/personal-website | b3d4f92ea51b40b104449259a376134aeb11766b | [
"MIT"
] | 1 | 2019-05-07T21:23:57.000Z | 2019-05-07T21:23:57.000Z | from django.urls import path
from .views import portfolio_view
urlpatterns = [
path('', portfolio_view, name='projects_view')
] | 22 | 50 | 0.75 |
cc6c1dd9f30f9947c241979383cf14113417045e | 17,690 | py | Python | ebot_main/scripts/task5.py | Jovian-Dsouza/sahayak_bot | 3565e910218e73e95ed8ce9b9d92dfcbe537894e | [
"MIT"
] | 3 | 2021-10-02T10:36:48.000Z | 2022-03-18T15:47:17.000Z | ebot_main/scripts/task5.py | Jovian-Dsouza/sahayak_bot | 3565e910218e73e95ed8ce9b9d92dfcbe537894e | [
"MIT"
] | 2 | 2021-10-06T07:21:57.000Z | 2022-03-04T03:20:27.000Z | ebot_main/scripts/task5.py | Jovian-Dsouza/sahayak_bot | 3565e910218e73e95ed8ce9b9d92dfcbe537894e | [
"MIT"
] | 1 | 2021-09-06T16:34:45.000Z | 2021-09-06T16:34:45.000Z | #! /usr/bin/env python
'''
This node uses the detection_info topic and performs the actual Ur5 arm manipulation
'''
import rospy
import random
from math import pi, sin, cos
from geometry_msgs.msg import Point, Quaternion, Pose, PointStamped, PoseStamped
from std_msgs.msg import Header
from object_msgs.msg import ObjectPose
from std_srvs.srv import Empty
from tf.transformations import quaternion_from_euler
from tf.transformations import euler_from_quaternion
from ebot_mani.srv import *
from testNav import Ebot
from perception.srv import *
transformPose = rospy.ServiceProxy('/get_transform_pose', GetTransformPose)
transformPoint = rospy.ServiceProxy('/get_transform_point', GetTransformPoint)
# width estimate = 0.2 + width of detection window (printed in terminal)
# w_dict uses real model names
w_dict = {'coke_can': 0.27086,
'battery': 0.26500,
'glue': 0.31,
'eYFi_board': 0.5,
'adhesive': 0.267674286664,
'water_glass': 0.2,
'robot_wheels': 0.26,
'FPGA_board': 0.3
}
def create_pose_quaternion(x, y, z, qx, qy, qz, qw):
'''
returns a Pose() object from the given x, y, z, qx, qy , qz, qw values
'''
pose = Pose()
pose.position.x = x
pose.position.y = y
pose.position.z = z
pose.orientation.x = qx
pose.orientation.y = qy
pose.orientation.z = qz
pose.orientation.w = qw
return pose
def orient_from_euler(roll, pitch, yaw):
'''
Input is roll, pitch, yaw
output is Quaternion pose.orientation
'''
q = quaternion_from_euler(roll, pitch, yaw)
o = Quaternion()
o.x, o.y, o.z, o.w = q[0], q[1], q[2], q[3]
return o
def pickupObject(object_name):
'''
Note : object_name should be the real model name and not the gazebo model name
'''
ur5.openGripper()
graspPose_pub.publish(createPoseStamped(detect.dict[object_name]))
if object_name == 'eYFi_board':
# TODO need a better way of finding the object's yaw angle instead of manually giving it
return ur5.graspObjectVertical(detect.dict[object_name], width=w_dict[object_name], yaw=pi/4).success
elif object_name == 'FPGA_board':
# return ur5.graspObjectVertical(detect.dict[object_name], width=w_dict[object_name], yaw=pi/3).success
return ur5.graspObjectHorizontal(detect.dict[object_name], width=w_dict[object_name], yaw=-pi/6)
else:
# .success
return ur5.graspObjectHorizontal(detect.dict[object_name], width=w_dict[object_name], yaw=0)
def main():
# maind()
getFPGA()
ur5.openGripper()
def maind():
ur5.go_to_named_pose("navPose")
# ebot.go_to_goal('store_table_fpga')
ebot.go_to_goal('store_table')
# ebot.go_to_goal_precise('store_table')
ebot.print_current_pose()
# detect.detectTable()
# ur5.go_to_named_pose("seeObjectJ")
ur5.go_to_named_pose("fpgaPoseOdom")
detect.detect()
object_name = 'FPGA_board'
pointBaseLink = detect.dict[object_name]
graspPose_pub.publish(createPoseStamped(pointBaseLink))
pointOdom = TransformPoint(pointBaseLink, 'base_link', 'odom')
ur5.go_to_named_pose("graspVerticalJ")
pose = Pose()
pose.position.z = 0.1
ur5.go_to_pose_relative(pose)
ebot.go_to_goal_precise('store_table_close')
ebot.go_to_waypoint_relative(0.4, 0 ,0)
pointBaseLink = TransformPoint(pointOdom,'odom', 'base_link')
graspPose_pub.publish(createPoseStamped(pointBaseLink))
detect.detectTable()
rospy.sleep(0.1)
flag = ur5.graspObjectVerticalOld(
pointBaseLink, width=w_dict[object_name], yaw=pi/3)
while flag == False:
ebot.go_to_waypoint_relative(0.2, 0, 0)
detect.detect()
flag = ur5.graspObjectVerticalOld(
pointBaseLink, width=w_dict[object_name], yaw=pi/3)
ur5.openGripper()
def getFPGAnew():
ur5.go_to_named_pose("navPose")
# ebot.go_to_goal('store_table_fpga')
ebot.go_to_goal('store_table')
ebot.go_to_goal_precise('store_table_fpga')
ebot.print_current_pose()
detect.detectTable()
ur5.go_to_named_pose("seeObjectJ")
ur5.go_to_named_pose("fpgaPoseOdom")
ebot.go_to_waypoint_relative(0.25, 0, 0)
ur5.go_to_named_pose("fpgaPoseOdom")
detect.detect()
detect.detectTable()
ur5.openGripper()
object_name = 'FPGA_board'
graspPose_pub.publish(createPoseStamped(detect.dict[object_name]))
printPoint(detect.dict[object_name])
ur5.go_to_named_pose("graspVerticalJ")
pose = Pose()
pose.position.z = 0.1
ur5.go_to_pose_relative(pose)
flag = ur5.graspObjectVerticalOld(
detect.dict[object_name], width=w_dict[object_name], yaw=pi/3)
while flag == False:
ebot.go_to_waypoint_relative(0.2, 0, 0)
detect.detect()
flag = ur5.graspObjectVerticalOld(
detect.dict[object_name], width=w_dict[object_name], yaw=pi/3)
ebot.go_to_pose_relative(-1, 0, 0, rospy.Duration(5))
ur5.go_to_named_pose("navPose")
ebot.go_to_goal("store_exit")
def getFPGA():
ur5.go_to_named_pose("navPose")
# ebot.go_to_goal('store_table_fpga')
ebot.go_to_goal('store_table')
ebot.go_to_goal_precise('store_table_fpga')
ebot.print_current_pose()
detect.detectTable()
ur5.go_to_named_pose("seeObjectJ")
ur5.go_to_named_pose("fpgaPoseOdom")
ebot.go_to_waypoint_relative(0.25, 0, 0)
ur5.go_to_named_pose("fpgaPoseOdom")
detect.detect()
detect.detectTable()
ur5.openGripper()
object_name = 'FPGA_board'
graspPose_pub.publish(createPoseStamped(detect.dict[object_name]))
printPoint(detect.dict[object_name])
ur5.go_to_named_pose("seeObjectJ")
flag = ur5.graspObjectVerticalOld(
detect.dict[object_name], width=w_dict[object_name], yaw=pi/3)
while flag == False:
ebot.go_to_waypoint_relative(0.2, 0, 0)
detect.detect()
flag = ur5.graspObjectVerticalOld(
detect.dict[object_name], width=w_dict[object_name], yaw=pi/3)
ebot.go_to_pose_relative(-1, 0, 0, rospy.Duration(5))
ur5.go_to_named_pose("navPose")
ebot.go_to_goal("store_exit")
def getGlue():
ur5.go_to_named_pose("navPose")
# TODO check if in meeting Room
# ebot.go_to_goal('meeting_entry')
# print("Entered room")
ebot.print_current_pose()
ebot.go_to_goal_precise('meeting_table')
ebot.go_to_goal('meeting_table')
print("Reached Goal")
ebot.print_current_pose()
ebot.applyBrakes()
detect.detectTable()
ur5.go_to_named_pose("meetingTable")
detect.detect()
pickupObject('glue')
ur5.go_to_named_pose("navPose")
ebot.releaseBrakes()
def enter_pantry():
ur5.go_to_named_pose("navPose")
ebot.go_to_goal('pantry_entry')
ebot.go_to_waypoint_relative(1.3, 0, 0)
printReached("pantry")
def getCoke():
enter_pantry()
ebot.go_to_goal_precise('pantry_table1')
ebot.go_to_goal('pantry_table1')
ebot.applyBrakes()
detect.detectTable()
ur5.go_to_named_pose("pantryTable1Odom")
detect.detect()
pickupObject('coke_can')
ur5.go_to_named_pose("navPoseOld")
ebot.releaseBrakes()
exit_pantry()
def exit_pantry():
# ebot.go_to_goal('pantry_exit')
# ebot.go_to_waypoint_relative(1.2,0,0)
# ebot.go_to_goal('pantry_exit_old')
ebot.go_to_goal_precise('pantry_exit')
ebot.set_yaw(pi/2)
ebot.go_to_waypoint_relative(1.2, 0, 0)
def dropbox3():
ebot.go_to_goal('research_entry')
ebot.print_current_pose()
ebot.go_to_goal('research_dropbox')
ebot.print_current_pose()
ebot.applyBrakes()
detect.detectTable()
ur5.go_to_named_pose("researchDropbox")
ur5.openGripper()
rospy.sleep(0.5)
ur5.go_to_named_pose("navPose")
ebot.releaseBrakes()
def exit_meeting():
ebot.go_to_goal_precise('meeting_exit')
ebot.go_to_goal('meeting_exit')
def enter_meeting():
ebot.go_to_goal('meeting_entry')
ebot.go_to_waypoint_relative(1, 0, 0)
def dropbox2():
ebot.go_to_goal_precise('meeting_dropbox')
# ebot.go_to_goal('meeting_dropbox')
ebot.print_current_pose()
detect.detectTable()
ur5.go_to_named_pose("researchDropboxJ")
ur5.go_to_named_pose("meetingDropboxOdom")
ur5.openGripper()
rospy.sleep(0.5)
ur5.go_to_named_pose("navPose")
# ebot.go_to_pose_relative(0.95,0,0)
def enter_conference_room():
ebot.go_to_goal('conference_entry')
ebot.go_to_waypoint_relative(1, 0, 0)
def dropbox1():
ur5.go_to_named_pose("navPose")
enter_conference_room()
ebot.go_to_goal('conference_dropbox')
ebot.print_current_pose()
ebot.applyBrakes()
detect.detectTable()
ur5.go_to_named_pose("conferenceDropbox")
ur5.openGripper()
rospy.sleep(0.5)
ur5.go_to_named_pose("navPose")
ebot.releaseBrakes()
exit_conference_room()
def exit_conference_room():
ebot.set_yaw(-3*pi/2)
ebot.go_to_waypoint_relative(1, 0, 0)
def subtask1():
getFPGA()
dropbox1()
def subtask2():
getCoke()
enter_meeting()
dropbox2()
def subtask3():
getGlue()
exit_meeting()
dropbox3()
if __name__ == '__main__':
rospy.init_node('grasping_node')
graspPose_pub = rospy.Publisher("/graspPose", PoseStamped, queue_size=1)
ur5 = Ur5()
ebot = Ebot()
detect = Detect()
# main()
getFPGA()
# subtask1()
# subtask2()
# subtask3()
# ebot.releaseBrakes()
| 28.624595 | 111 | 0.656981 |
cc6ca3b5cf9fc18b22965b52903b9910ca3fbede | 2,224 | py | Python | attacks.py | giuscri/thesis | d7aa0a8476f53ad304495b437841af1a8d6c87d4 | [
"MIT"
] | null | null | null | attacks.py | giuscri/thesis | d7aa0a8476f53ad304495b437841af1a8d6c87d4 | [
"MIT"
] | 10 | 2018-05-11T08:40:48.000Z | 2018-06-29T16:14:27.000Z | attacks.py | giuscri/thesis | d7aa0a8476f53ad304495b437841af1a8d6c87d4 | [
"MIT"
] | null | null | null | import tensorflow as tf
from cleverhans.attacks import FastGradientMethod
from cleverhans.utils_keras import KerasModelWrapper
from keras.utils import to_categorical
import keras.backend as K
import numpy as np
from functools import lru_cache
from pickle import loads, dumps
from models import filter_correctly_classified_examples
| 34.215385 | 86 | 0.748201 |
cc6f7c4f27c2a00ff15ccd7856ec922db8699702 | 2,187 | py | Python | chime/href.py | sanAkdam/chime | 1adbddbdddcdc2669086dee60d1bfb2f97535cff | [
"BSD-3-Clause"
] | 8 | 2015-02-05T22:12:41.000Z | 2015-05-15T16:15:14.000Z | chime/href.py | sanAkdam/chime | 1adbddbdddcdc2669086dee60d1bfb2f97535cff | [
"BSD-3-Clause"
] | 168 | 2015-02-02T23:02:52.000Z | 2015-05-15T21:54:07.000Z | chime/href.py | codeforamerica/bizarro-cms | 1adbddbdddcdc2669086dee60d1bfb2f97535cff | [
"BSD-3-Clause"
] | 5 | 2016-11-20T15:51:32.000Z | 2021-04-16T09:44:08.000Z | from urlparse import urlparse
from re import match
def get_redirect(req_path, ref_url):
'''
>>> get_redirect('/style.css', 'http://preview.local/tree/foo/view/')
'/tree/foo/view/style.css'
>>> get_redirect('/style.css', 'http://preview.local/tree/foo/view/quux.html')
'/tree/foo/view/style.css'
>>> get_redirect('/quux/style.css', 'http://preview.local/tree/foo/view/')
'/tree/foo/view/quux/style.css'
'''
_, ref_host, ref_path, _, _, _ = urlparse(ref_url)
ref_git_preamble_match = match(r'((/[^/]+){3})', ref_path)
return ref_git_preamble_match.group(1) + req_path
def needs_redirect(req_host, req_path, ref_url):
'''
Don't redirect when the request and referer hosts don't match:
>>> needs_redirect('preview.local', '/style.css', 'http://example.com/tree/foo/view/')
False
Don't redirect when the referer doesn't appear to include a git path.
>>> needs_redirect('preview.local', '/style.css', 'http://preview.local/about/')
False
Don't redirect when the request path already includes the git preamble.
>>> needs_redirect('preview.local', '/tree/foo/view/style.css', 'http://preview.local/tree/foo/view/')
False
>>> needs_redirect('preview.local', '/', 'http://preview.local/tree/foo/view/')
True
>>> needs_redirect('preview.local', '/style.css', 'http://preview.local/tree/foo/view/')
True
>>> needs_redirect('preview.local', '/fee/fi/fo/fum/style.css', 'http://preview.local/tree/foo/view/')
True
'''
_, ref_host, ref_path, _, _, _ = urlparse(ref_url)
#
# Don't redirect when the request and referer hosts don't match.
#
if req_host != ref_host:
return False
ref_git_preamble_match = match(r'(/tree/[^/]+/view/)', ref_path)
#
# Don't redirect when the referer doesn't appear to include a git path.
#
if not ref_git_preamble_match:
return False
#
# Don't redirect when the request path already includes the git preamble.
#
if req_path.startswith(ref_git_preamble_match.group(1)):
return False
return True
if __name__ == '__main__':
import doctest
doctest.testmod()
| 31.242857 | 106 | 0.652492 |
cc7140d5ec453c262b76c09e1ad92c183427766b | 237 | py | Python | backend/routers/home.py | b1team/Python-OCR | fe8237978ab0eec18db3bd674dae772ec7c48a3c | [
"MIT"
] | null | null | null | backend/routers/home.py | b1team/Python-OCR | fe8237978ab0eec18db3bd674dae772ec7c48a3c | [
"MIT"
] | null | null | null | backend/routers/home.py | b1team/Python-OCR | fe8237978ab0eec18db3bd674dae772ec7c48a3c | [
"MIT"
] | null | null | null | from flask import Blueprint, render_template
home_bp = Blueprint(
"home_bp",
__name__,
)
| 18.230769 | 103 | 0.704641 |
cc749c4fcb4807611aed92e6a739be63d7aba80c | 1,746 | py | Python | demos/matplotlib/gradient_chart.py | 0lru/p3ui | 162c6c68f4a55ec109a593c8ced66a62520b5602 | [
"MIT"
] | 21 | 2021-07-22T21:33:01.000Z | 2022-02-12T15:17:46.000Z | demos/matplotlib/gradient_chart.py | 0lru/p3ui | 162c6c68f4a55ec109a593c8ced66a62520b5602 | [
"MIT"
] | 3 | 2021-07-26T19:00:39.000Z | 2021-12-12T09:29:09.000Z | demos/matplotlib/gradient_chart.py | 0lru/p3ui | 162c6c68f4a55ec109a593c8ced66a62520b5602 | [
"MIT"
] | 2 | 2021-07-23T04:57:21.000Z | 2021-12-15T22:51:45.000Z | from p3ui import *
import matplotlib.pyplot as plt
import numpy as np
| 34.92 | 138 | 0.555556 |
cc757cd407448942e86aaa6d46fed30c9d25b05b | 816 | py | Python | Stack/StackOperations.py | prash-kr-meena/GoogleR | 27aca71e51cc2442e604e07ab00406a98d8d63a4 | [
"Apache-2.0"
] | null | null | null | Stack/StackOperations.py | prash-kr-meena/GoogleR | 27aca71e51cc2442e604e07ab00406a98d8d63a4 | [
"Apache-2.0"
] | null | null | null | Stack/StackOperations.py | prash-kr-meena/GoogleR | 27aca71e51cc2442e604e07ab00406a98d8d63a4 | [
"Apache-2.0"
] | null | null | null | from collections import deque
"""
Operations
* Enqueue
* Dequeue
* Peek (first element)
* Size
* IsEmpty
* Print
"""
if __name__ == '__main__':
demo_queue_operation_using_deque()
pass
"""
deque([1, 2, 3, 4, 5])
deque([3, 4, 5])
3
"""
| 16.653061 | 42 | 0.610294 |
cc7588de324a87e070270762efbca68576fe8829 | 85 | py | Python | ndarray/same.py | Hupengyu/Paddle_learning | 0ac1e2ad32e41ac87bbb19e4535a4bc253ca9b0f | [
"Apache-2.0"
] | 1 | 2021-08-02T01:51:35.000Z | 2021-08-02T01:51:35.000Z | ndarray/same.py | Hupengyu/Paddle_learning | 0ac1e2ad32e41ac87bbb19e4535a4bc253ca9b0f | [
"Apache-2.0"
] | 1 | 2021-11-03T08:58:30.000Z | 2021-11-03T08:58:30.000Z | ndarray/same.py | Hupengyu/Paddle_learning | 0ac1e2ad32e41ac87bbb19e4535a4bc253ca9b0f | [
"Apache-2.0"
] | null | null | null | mask = 255
print(mask == 255)
blue_mask = mask == 255
print(mask)
print(blue_mask) | 10.625 | 23 | 0.682353 |
cc7685e77b5702f2bcf63b723074355167f96c83 | 7,664 | py | Python | app/data_model/find_songs.py | TemsyChen/Spotifinder | b069ffcd63bd7654e1afd51cde3288c9678d121a | [
"MIT"
] | null | null | null | app/data_model/find_songs.py | TemsyChen/Spotifinder | b069ffcd63bd7654e1afd51cde3288c9678d121a | [
"MIT"
] | 3 | 2021-04-23T22:52:32.000Z | 2021-04-26T04:02:51.000Z | app/data_model/find_songs.py | TemsyChen/Spotifinder | b069ffcd63bd7654e1afd51cde3288c9678d121a | [
"MIT"
] | 6 | 2021-04-28T21:14:10.000Z | 2021-10-15T01:47:55.000Z | '''
Contains the implementation of the FindSongs class.
'''
from re import compile as rcompile
from zipfile import ZipFile
from os.path import dirname
import pandas as pd
from tensorflow.keras.models import load_model
from sklearn.neighbors import NearestNeighbors
from joblib import load
DIR = dirname(__file__)
rex = rcompile('[^a-zA-Z 0-9]')
tokenize = lambda x: rex.sub('', x.lower().replace(',', ' ').replace('-', ' '))
MODELS_DIR = DIR + '/../../models/'
DATA_DIR = DIR + '/../../data/'
ENCODER = 'encoder.h5'
FG_ENCODER = 'fg_encoder.h5'
ENCODER_PATH = MODELS_DIR + ENCODER + '.zip'
ENCODED_DTM = MODELS_DIR + 'encoded_dtm.pkl'
TFIDF = MODELS_DIR + 'tfidf.pkl'
FG_ENCODER_PATH = MODELS_DIR + FG_ENCODER
FG_ENCODED_DF = MODELS_DIR + 'fg_encoded_df.pkl'
GENRES_TFIDF = MODELS_DIR + 'genres_tfidf.pkl'
SCALER = MODELS_DIR + 'scaler.pkl'
TRACKS = DATA_DIR + 'tracks_genres_lyrics_en.csv.zip'
| 41.204301 | 99 | 0.656315 |
cc775b2e46440022feb26f05b0cd7bb859a90f65 | 3,516 | py | Python | ecua_vac.py | andradf/ecua_vac | acc7153bc8d0a7fcf08352f79c4112386dd72744 | [
"MIT"
] | null | null | null | ecua_vac.py | andradf/ecua_vac | acc7153bc8d0a7fcf08352f79c4112386dd72744 | [
"MIT"
] | null | null | null | ecua_vac.py | andradf/ecua_vac | acc7153bc8d0a7fcf08352f79c4112386dd72744 | [
"MIT"
] | null | null | null | import tweepy
import time
import pandas as pd
import datetime
import re
from auth import consumer_key,consumer_secret,key,secret,user_ID
# twitter auth process
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
api = tweepy.API(auth)
bot_id = api.me().id #1382664940587261954
# defining variables
interval = 60 * 60 * 24 # every 24 hours
# interval = 5 # every 5 seconds, for testing
#define numero de dias hasta el 1 de septiembre
today = datetime.date.today()
future = datetime.date(2021,9,1)
diff = future - today
lim_dias=diff.days
while True:
df=pd.read_csv("https://raw.githubusercontent.com/andrab/ecuacovid/master/datos_crudos/vacunas/vacunas.csv")
fecha_rep=df["fecha"].iloc[-1]
ult_fecha_datos = datetime.datetime.strptime(df["fecha"].iloc[-1], '%d/%m/%Y')
lastTweet = api.user_timeline(id = bot_id, count = 1)
if (len(lastTweet) > 0):
text = lastTweet[0].text
m = re.search('Hasta el (?P<date>\d{2}/\d{2}/\d{4}) el MSP', text)
if m:
ult_fecha_tweet = datetime.datetime.strptime(m.group('date'), '%d/%m/%Y')
if ult_fecha_tweet >= ult_fecha_datos:
print("Ya se tweeteo la ultima fecha disponible fecha %d", ult_fecha_datos)
time.sleep(interval)
continue
vaxs_1dosis=df["primera_dosis"].iloc[-1]
vaxs_2dosis=df["segunda_dosis"].iloc[-1]
left_2_vax= int(9e6-vaxs_1dosis)
#escenario1 en el que todavia tiene tiempo pero no acaba de vacunar
if (left_2_vax > 0 and lim_dias > 0):
tweet= 'A G.Lasso le quedan {} das para vacunar {} personas. Hasta el {} el MSP ha reportado {} personas vacunadas con primera dosis, {} personas con segunda dosis. Su ofrecimiento en campaa: 9M de vacunadxs en 100 das'
tweet = trimtweet(tweet.format(lim_dias, left_2_vax, fecha_rep,vaxs_1dosis,vaxs_2dosis))
print(tweet, flush=True)
api.send_direct_message(user_ID, tweet)
api.update_status(tweet)
lim_dias -= 1
time.sleep(interval)
#escenario2 en el que se le acabo el tiempo. recordatorio de cuantos dias va sin cumplir so objetivo
elif (left_2_vax > 0 and lim_dias <= 0):
tweet='Hace {} das G.Lasso debera haber vacunado 9M de personas y todavia le faltan {} personas para llegar a 9M. Hasta el {} el MSP ha reportado {} personas vacunadas con primera dosis, {} personas con segunda dosis #accountabilitybot #AI4good'
print(tweet.format(abs(lim_dias), left_2_vax, fecha_rep,vaxs_1dosis,vaxs_2dosis),flush=True)
tweet = trimtweet(tweet.format(abs(lim_dias), left_2_vax, fecha_rep,vaxs_1dosis,vaxs_2dosis))
api.send_direct_message(user_ID, tweet)
api.update_status(tweet)
lim_dias -= 1
time.sleep(interval)
#escenario3 en el que vacuna a 9M antes de que se acabe el tiempo
else #!((a and b) or (a and !b)) = !a
tweet= 'Guillermo Lasso logr vacunar al menos 9M personas en sus primeros 100 das de gobierno. Voy a buscar algo ms que hacer. Chao #accountabilitybot #AI4good'
tweet = trimtweet(tweet)
print(tweet,flush=True)
api.send_direct_message(user_ID,tweet)
api.update_status(tweet)
time.sleep(interval)
#to run in the back ground <sudo nohup python3 ecua_vac.py &>
# to check real time log file <sudo tail -f nohup.out>
| 44.506329 | 255 | 0.685154 |
cc78ed70d34e15e55d4c89613eb5c38a3da4d0ac | 1,277 | py | Python | py_lecture/scripts/rosbag_analisys_pose.py | yasutomo57jp/ros_lecture | 811afaded5a5780fa1291bd41196d80446da1e53 | [
"MIT"
] | 110 | 2018-11-13T15:04:35.000Z | 2022-03-27T20:48:03.000Z | py_lecture/scripts/rosbag_analisys_pose.py | yasutomo57jp/ros_lecture | 811afaded5a5780fa1291bd41196d80446da1e53 | [
"MIT"
] | 4 | 2020-07-16T13:32:22.000Z | 2022-01-11T01:08:12.000Z | py_lecture/scripts/rosbag_analisys_pose.py | yasutomo57jp/ros_lecture | 811afaded5a5780fa1291bd41196d80446da1e53 | [
"MIT"
] | 57 | 2019-07-02T23:43:17.000Z | 2022-03-27T20:47:28.000Z | #!/usr/bin/env python
import rosbag
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
args = sys.argv
print(len(args))
assert len(args)>=2, "you must specify the argument."
# get path
filename=os.path.normpath(os.path.join(os.getcwd(),args[1]))
print(filename)
# read from bag file
bag = rosbag.Bag(filename)
np_poses=None
for topic, msg, t in bag.read_messages():
if topic=="/pose":
np_pose=np.array([[0.0, 0.0, 0.0, 0.0, 0.0]])
np_pose[0,0]=msg.position.x
np_pose[0,1]=msg.position.y
np_pose[0,2]=msg.position.z
np_pose[0,3]=t.secs
np_pose[0,4]=t.nsecs
if np_poses is None:
np_poses=np_pose
else:
np_poses=np.append(np_poses,np_pose,axis=0)
# reform time
start_sec=np_poses[0,3]
start_nsec=np_poses[0,4]
t=np.zeros(np_poses.shape[0],dtype='float32')
for i in range(np_poses.shape[0]):
t[i]=(np_poses[i,3]-start_sec)+(np_poses[i,4]-start_nsec)/1000000000.0
# plot
plt.subplot(121)
plt.title("time vs x,y")
plt.plot(t, np_poses[:,0], 'r', label="x")
plt.plot(t, np_poses[:,1], 'b', label="y")
plt.xlabel("time[s]")
plt.ylabel("vel[m/s]")
plt.legend()
plt.subplot(122)
plt.title("x vs y")
plt.plot(np_poses[:,0], np_poses[:,1], 'g')
plt.show()
bag.close()
| 23.648148 | 74 | 0.651527 |
cc7af5edf4c13756157ef5543e25175963fa44f3 | 1,748 | py | Python | ambra/temporal_feature_extraction.py | vene/ambra | e220dbb332b86ed60ecb025efbefbb33080118b7 | [
"BSD-2-Clause"
] | 1 | 2016-04-14T07:11:00.000Z | 2016-04-14T07:11:00.000Z | ambra/temporal_feature_extraction.py | vene/ambra | e220dbb332b86ed60ecb025efbefbb33080118b7 | [
"BSD-2-Clause"
] | null | null | null | ambra/temporal_feature_extraction.py | vene/ambra | e220dbb332b86ed60ecb025efbefbb33080118b7 | [
"BSD-2-Clause"
] | null | null | null | '''
Created on Dec 21, 2014
@author: Alina Maria Ciobanu
'''
import numpy
import re
TOKEN_NER_TAGS = ['DATE', 'NUMBER']
WIKI_NER_TAGS = ['PERSON', 'ORGANIZATION', 'LOCATION']
DEFAULT_YEAR_VALUE = 1858 # the mean of the lowest and highest value for all possible intervals, hardcoded for now
def get_temporal_feature_for_zip(zipped, wiki_dict=None):
""" entry format: [(token_1, ner_tag_1), (token_2, ner_tag_2), (token_3, ner_tag_3)] """
years = []
years.extend(get_years_from_token(zipped))
if years:
return numpy.median(numpy.array(years))
elif wiki_dict:
years.extend(get_years_from_wiki(zipped, wiki_dict))
if years:
return numpy.median(numpy.array(years))
return DEFAULT_YEAR_VALUE
if __name__ == "__main__":
zipped = zip(['the 1990s', '1967', '1875', '123x4'], ['DATE', 'DAT', 'NUMBER', 'NUMBER'])
print get_temporal_feature_for_zip(zipped)
| 28.655738 | 115 | 0.627574 |
cc7c0a236ab84be9186e7062cc86b20f502b6f05 | 7,270 | py | Python | src/academia_tag_recommender/classwise_classifier.py | gefei-htw/academia_tag_recommender | aea56d36e16584824ef217d1f2caaee3414098f8 | [
"MIT"
] | null | null | null | src/academia_tag_recommender/classwise_classifier.py | gefei-htw/academia_tag_recommender | aea56d36e16584824ef217d1f2caaee3414098f8 | [
"MIT"
] | null | null | null | src/academia_tag_recommender/classwise_classifier.py | gefei-htw/academia_tag_recommender | aea56d36e16584824ef217d1f2caaee3414098f8 | [
"MIT"
] | 1 | 2021-01-29T19:41:47.000Z | 2021-01-29T19:41:47.000Z | """This module handles classifier calculation."""
from academia_tag_recommender.definitions import MODELS_PATH
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, recall_score
from sklearn.model_selection import StratifiedKFold
from joblib import dump, load
from pathlib import Path
import random
import numpy as np
DATA_FOLDER = Path(MODELS_PATH) / 'experimental_classifier' / 'classwise'
SAMPLE_RATIO = 1 / 25
RANDOM_STATE = 0
random.seed(RANDOM_STATE)
scorer = make_scorer(recall_score)
k_fold = StratifiedKFold(shuffle=True, random_state=RANDOM_STATE)
| 31.068376 | 122 | 0.573315 |
cc8419824483cd3b9a3d2944955bdaa815ca7106 | 2,332 | py | Python | Lib/site-packages/node/tests/test_nodespace.py | Dr8Ninja/ShareSpace | 7b445783a313cbdebb1938e824e98370a42def5f | [
"MIT"
] | 11 | 2015-04-02T17:47:44.000Z | 2020-10-26T20:27:43.000Z | Lib/site-packages/node/tests/test_nodespace.py | Dr8Ninja/ShareSpace | 7b445783a313cbdebb1938e824e98370a42def5f | [
"MIT"
] | 5 | 2017-01-18T11:05:42.000Z | 2019-03-30T06:19:21.000Z | Lib/site-packages/node/tests/test_nodespace.py | Dr8Ninja/ShareSpace | 7b445783a313cbdebb1938e824e98370a42def5f | [
"MIT"
] | 2 | 2015-09-15T06:50:22.000Z | 2016-12-01T11:12:01.000Z | from node.behaviors import Adopt
from node.behaviors import DefaultInit
from node.behaviors import Nodespaces
from node.behaviors import Nodify
from node.behaviors import OdictStorage
from node.tests import NodeTestCase
from odict import odict
from plumber import plumbing
###############################################################################
# Mock objects
###############################################################################
###############################################################################
# Tests
###############################################################################
class TestNodespace(NodeTestCase):
| 29.15 | 79 | 0.565609 |